问:
i am insert write php code some error logo and image
I want to insert some data using PHP 7.2 table name seller_login and field user_id, username, password, type_login, image, logo PHP insert in a script. not working. always logo and image about error show please help me

show error here

```<code>Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94

Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94

Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95

Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95
</code>```

PHP code line number like 94

```<code>move_uploaded_file($_FILES["logo"]

  ["tmp_name"],"../sellerimage/$user_id/".$_FILES["logo"]["name"]);
</code>```

PHP code line number like 95

```<code>move_uploaded_file($_FILES["image"]

["tmp_name"],"../sellerimage/$user_id/".$_FILES["image"]["name"]);
</code>```

PHP all script here

```<code><?php
    $username = $password = $confirm_password = "";
    $username_err = $password_err = $confirm_password_err = "";
    $type_login = $type_err = $type_login = "";
    $logo = $logo_err = $logo='';
    $image = $image_err = $image='';

    if($_SERVER["REQUEST_METHOD"] == "POST"){

        if(empty(trim($_POST["username"]))){
            $username_err = "Please enter a username.";
        } else{
            $sql = "SELECT user_id FROM  seller_login WHERE username = ?";

            if($stmt = mysqli_prepare($conn, $sql)){
                mysqli_stmt_bind_param($stmt, "s", $param_username);

                $param_username = trim($_POST["username"]);

                if(mysqli_stmt_execute($stmt)){
                    mysqli_stmt_store_result($stmt);

                    if(mysqli_stmt_num_rows($stmt) == 1){
                        $username_err = "This username is already taken.";
                    } else{
                        $username = trim($_POST["username"]);
                    }
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }

            mysqli_stmt_close($stmt);
        }
        //------------------------
             if(empty(trim($_POST["type_login"]))){
                    $type_err = "Please Select User Type.";
             } else{
                    $type_login = trim($_POST["type_login"]);
                }
        //------------grant----------------

        //------------------------
        if(empty(trim($_POST["password"]))){
            $password_err = "Please enter a password.";
        } elseif(strlen(trim($_POST["password"])) < 6){
            $password_err = "Password must have atleast 6 characters.";
        } else{
            $password = trim($_POST["password"]);
        }

        if(empty(trim($_POST["confirm_password"]))){
            $confirm_password_err = "Please confirm password.";
        } else{
            $confirm_password = trim($_POST["confirm_password"]);
            if(empty($password_err) && ($password != $confirm_password)){
                $confirm_password_err = "Password did not match.";
            }
        }
        //-------------------seller logo insert------------------------

        if(empty($_FILES["logo"]["name"])){$logo_err = "Please Select Logo.";}
        else{ $logo =$_FILES["logo"]["name"];}
        //-------------------image---------------------------

        if(empty($_FILES["image"]["name"])){$image_err = "Please Select image.";}
        else{$image =$_FILES["image"]["name"];}

        //--------------------directory creation for Seller images---------------

        $query=mysqli_query($conn,"select max(user_id) as pid from seller_login");
        $result=mysqli_fetch_array($query);
        $sellerid=$result['pid']+1;
        $dir="../sellerimage/$sellerid";
        mkdir($dir);// directory creation for Seller images
        move_uploaded_file($_FILES["logo"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["logo"]["name"]);
        move_uploaded_file($_FILES["image"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["image"]["name"]);

        //----------------------------------------------------------------

        if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

            $sql = "INSERT INTO seller_login (username, password, type_login, logo, image) VALUES (?, ?, ?, ?, ?)";

            if($stmt = mysqli_prepare($conn, $sql)){
                mysqli_stmt_bind_param($stmt, "sssss", $param_username, $param_password, $type_login, $logo, $image);

                $param_username = $username;

                $param_password = password_hash($password, PASSWORD_DEFAULT);

                if(mysqli_stmt_execute($stmt)){
                    $msg="Successfully Login";
                } else{
                     $msg="Something went wrong. Please try again later.";
                }
            }
            mysqli_stmt_close($stmt);
        }
        mysqli_close($conn);
    }
    ?>
</code>```

HTML form

```<code><form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                                <div class="row text-center ">
                                <div class="col-md-2"></div>
                                    <div class="col-md-8"><h3 class="btn-success p-2">Please fill this form to create an account.</h3></div>
                                <div class="col-md-2"></div>
                                </div></br>

                                <!----------------Username---------------->
                                    <div class="row">
                                        <div class="col-md-1"></div>
                                        <div class="col-md-2"><b>Username</b></div>
                                        <div class="form-group col-md-3 <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                                            <input type="text" name="username" class="form-control" value="<?php echo $username; ?>" offset>
                                            <span class="help-block"style="color: #ff0000;text-align:center;"><?php echo $username_err; ?></span>
                                        </div>

                                        <div class="col-md-2"><b>Password</b></div>
                                        <div class="form-group col-md-3 <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                                            <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
                                            <span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $password_err; ?></span>
                                        </div>
                                        <div class="col-md-1"></div>
                                    </div>
                                <!-------------Password------------------->

                                    <div class="row">
                                        <div class="col-md-1"></div>
                                        <div class="col-md-2"><b>Confirm Password</b></div>

                                        <div class="form-group col-md-3 <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
                                            <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
                                            <span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $confirm_password_err; ?></span>
                                        </div>
                                        <div class="col-md-2"><b>Select User Type</b></div>
                                        <div class="form-group col-md-3 <?php echo (!empty($type_err)) ? 'has-error' : ''; ?>">
                                            <select  name="type_login"  class="form-control">
                                                <option value="">Select</option>
                                                <option value="1">Add Seller</option>
                                            </select>
                                           <span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $type_err; ?></span>
                                        </div>

                                        <div class="col-md-1"></div>
                                    </div>

                                 <!------------Select picture------------>
                                    <div class="row">
                                        <div class="col-md-1"></div>
                                        <div class="col-md-2"><b>Profile Picture</b></div>
                                        <div class="form-group col-md-3 <?php echo (!empty($image_err)) ? 'has-error' : ''; ?>">
                                            <input type="file" name="image" class="form-control p-0" value="<?php echo $image; ?>">
                                            <span class="help-block"style="color: #ff0000;text-align:center;"><?php echo $image_err; ?></span>
                                        </div>

                                        <div class="col-md-2"><b>Company Logo</b></div>
                                        <div class="form-group col-md-3 <?php echo (!empty($logo_err)) ? 'has-error' : ''; ?>">
                                            <input type="file" name="logo" class="form-control p-0" value="<?php echo $logo; ?>">
                                            <span class="help-block" style="color: #ff0000;text-align:center;"><?php echo $logo_err; ?></span>
                                        </div>
                                        <div class="col-md-1"></div>
                                    </div>

                                    <hr><hr>
                                    <!----------------------------->
                                    <div class="row">
                                        <div class="col-md-5"></div>

                                        <div class="form-group col-md-2">
                                             <button type="submit" name="submit" class="btn btn-success"size="40" style="cursor: pointer;">Insert</button>
                                        </div>
                                        <div class="form-group col-md-3">
                                            <input type="reset" class="btn btn-default" value="Reset">
                                        </div>
                                        <div class="col-md-2"></div>
                                    </div>

                                </form>
</code>```

答:
Use enctype when u open form (enctype="multipart/form-data):</p>

```<code><form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
</code>```

Body:
I want to insert some data using PHP 7.2 table name seller_login and field user_id, username, password, type_login, image, logo PHP insert in a script. not working. always logo and image about error show please help me

show error here

Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94

Notice: Undefined index: logo in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 94

Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95

Notice: Undefined index: image in D:\xammp\htdocs\multivender\myhomeportal\seller-register.php on line 95

PHP code line number like 94

move_uploaded_file($_FILES["logo"]

  ["tmp_name"],"../sellerimage/$user_id/".$_FILES["logo"]["name"]);

PHP code line number like 95

move_uploaded_file($_FILES["image"]

["tmp_name"],"../sellerimage/$user_id/".$_FILES["image"]["name"]);

PHP all script here

<?php
    $username = $password = $confirm_password = "";
    $username_err = $password_err = $confirm_password_err = "";
    $type_login = $type_err = $type_login = "";
    $logo = $logo_err = $logo='';
    $image = $image_err = $image='';

    if($_SERVER["REQUEST_METHOD"] == "POST"){

        if(empty(trim($_POST["username"]))){
            $username_err = "Please enter a username.";
        } else{
            $sql = "SELECT user_id FROM  seller_login WHERE username = ?";

            if($stmt = mysqli_prepare($conn, $sql)){
                mysqli_stmt_bind_param($stmt, "s", $param_username);

                $param_username = trim($_POST["username"]);

                if(mysqli_stmt_execute($stmt)){
                    mysqli_stmt_store_result($stmt);

                    if(mysqli_stmt_num_rows($stmt) == 1){
                        $username_err = "This username is already taken.";
                    } else{
                        $username = trim($_POST["username"]);
                    }
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }

            mysqli_stmt_close($stmt);
        }
        //------------------------
             if(empty(trim($_POST["type_login"]))){
                    $type_err = "Please Select User Type.";
             } else{
                    $type_login = trim($_POST["type_login"]);
                }
        //------------grant----------------

        //------------------------
        if(empty(trim($_POST["password"]))){
            $password_err = "Please enter a password.";
        } elseif(strlen(trim($_POST["password"])) < 6){
            $password_err = "Password must have atleast 6 characters.";
        } else{
            $password = trim($_POST["password"]);
        }

        if(empty(trim($_POST["confirm_password"]))){
            $confirm_password_err = "Please confirm password.";
        } else{
            $confirm_password = trim($_POST["confirm_password"]);
            if(empty($password_err) && ($password != $confirm_password)){
                $confirm_password_err = "Password did not match.";
            }
        }
        //-------------------seller logo insert------------------------

        if(empty($_FILES["logo"]["name"])){$logo_err = "Please Select Logo.";}
        else{ $logo =$_FILES["logo"]["name"];}
        //-------------------image---------------------------

        if(empty($_FILES["image"]["name"])){$image_err = "Please Select image.";}
        else{$image =$_FILES["image"]["name"];}

        //--------------------directory creation for Seller images---------------

        $query=mysqli_query($conn,"select max(user_id) as pid from seller_login");
        $result=mysqli_fetch_array($query);
        $sellerid=$result['pid']+1;
        $dir="../sellerimage/$sellerid";
        mkdir($dir);// directory creation for Seller images
        move_uploaded_file($_FILES["logo"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["logo"]["name"]);
        move_uploaded_file($_FILES["image"]["tmp_name"],"../sellerimage/$sellerid/".$_FILES["image"]["name"]);

        //----------------------------------------------------------------

        if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

            $sql = "INSERT INTO seller_login (username, password, type_login, logo, image) VALUES (?, ?, ?, ?, ?)";

            if($stmt = mysqli_prepare($conn, $sql)){
                mysqli_stmt_bind_param($stmt, "sssss", $param_username, $param_password, $type_login, $logo, $image);

                $param_username = $username;

                $param_password = password_hash($password, PASSWORD_DEFAULT);

                if(mysqli_stmt_execute($stmt)){
                    $msg="Successfully Login";
                } else{
                     $msg="Something went wrong. Please try again later.";
                }
            }
            mysqli_stmt_close($stmt);
        }
        mysqli_close($conn);
    }
    ?>

HTML form

<form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

Please fill this form to create an account.

Username

                                        <div class="form-group col-md-3 <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                                            <input type="text" name="username" class="form-control" value="<?php echo $username; ?>" offset>
                                            <?php echo $username_err; ?>

Password

                                        <div class="form-group col-md-3 <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                                            <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
                                            <?php echo $password_err; ?>

Confirm Password

                                        <div class="form-group col-md-3 <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
                                            <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
                                            <?php echo $confirm_password_err; ?>

Select User Type

                                        <div class="form-group col-md-3 <?php echo (!empty($type_err)) ? 'has-error' : ''; ?>">
                                            <select  name="type_login"  class="form-control">
                                                <option value="">Select</option>
                                                <option value="1">Add Seller</option>
                                            </select>
                                           <?php echo $type_err; ?>

Profile Picture

                                        <div class="form-group col-md-3 <?php echo (!empty($image_err)) ? 'has-error' : ''; ?>">
                                            <input type="file" name="image" class="form-control p-0" value="<?php echo $image; ?>">
                                            <?php echo $image_err; ?>

Company Logo

                                        <div class="form-group col-md-3 <?php echo (!empty($logo_err)) ? 'has-error' : ''; ?>">
                                            <input type="file" name="logo" class="form-control p-0" value="<?php echo $logo; ?>">
                                            <?php echo $logo_err; ?>

                                             <button type="submit" name="submit" class="btn btn-success"size="40" style="cursor: pointer;">Insert</button>

                                            <input type="reset" class="btn btn-default" value="Reset">

                                </form>

Body:
Use enctype when u open form (enctype="multipart/form-data):

<form style="border: 2px solid #28a745;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">


来源: stackexchange

问:
Django encoding error when reading from a CSV
When I try to run:

```<code>import csv

with open('data.csv', 'rU') as csvfile:
  reader = csv.DictReader(csvfile)
  for row in reader:
    pgd = Player.objects.get_or_create(
      player_name=row['Player'],
      team=row['Team'],
      position=row['Position']
    )
</code>```

Most of my data gets created in the database, except for one particular row. When my script reaches the row, I receive the error:

```<code>ProgrammingError: You must not use 8-bit bytestrings unless you use a
text_factory that can interpret 8-bit bytestrings (like text_factory = str).
It is highly recommended that you instead just switch your application to Unicode strings.`
</code>```

The particular row in the CSV that causes this error is:

```<code>>>> row
{'FR\xed\x8aD\xed\x8aRIC.ST-DENIS', 'BOS', 'G'}
</code>```

I've looked at the other similar Stackoverflow threads with the same or similar issues, but most aren't specific to using Sqlite with Django. Any advice?

If it matters, I'm running the script by going into the Django shell by calling python manage.py shell, and copy-pasting it in, as opposed to just calling the script from the command line.

This is the stacktrace I get:

```<code>Traceback (most recent call last):
  File "<console>", line 4, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 108, in next
    row = self.reader.next()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 302, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcc in position 1674: invalid continuation byte
</code>```

EDIT: I decided to just manually import this entry into my database, rather than try to read it from my CSV, based on Alastair McCormack's feedback

Based on the output from your question, it looks like the person who made the CSV mojibaked it - it doesn't seem to represent FRÉDÉRIC.ST-DENIS. You can try using windows-1252 instead of utf-8 but I think you'll end up with FRíŠDíŠRIC.ST-DENIS in your database.

答: In Django, decode with  latin-1, csv.DictReader(io.StringIO(csv_file.read().decode('latin-1'))), it would devour all special characters and all comma exceptions you get in utf-8.

ContentLicense: CC BY-SA 3.0

Body:
When I try to run:

import csv

with open('data.csv', 'rU') as csvfile:
  reader = csv.DictReader(csvfile)
  for row in reader:
    pgd = Player.objects.get_or_create(
      player_name=row['Player'],
      team=row['Team'],
      position=row['Position']
    )

Most of my data gets created in the database, except for one particular row. When my script reaches the row, I receive the error:

ProgrammingError: You must not use 8-bit bytestrings unless you use a
text_factory that can interpret 8-bit bytestrings (like text_factory = str).
It is highly recommended that you instead just switch your application to Unicode strings.`

The particular row in the CSV that causes this error is:

>>> row
{'FR\xed\x8aD\xed\x8aRIC.ST-DENIS', 'BOS', 'G'}

I've looked at the other similar Stackoverflow threads with the same or similar issues, but most aren't specific to using Sqlite with Django. Any advice?

If it matters, I'm running the script by going into the Django shell by calling python manage.py shell, and copy-pasting it in, as opposed to just calling the script from the command line.

This is the stacktrace I get:

Traceback (most recent call last):
  File "<console>", line 4, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 108, in next
    row = self.reader.next()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 302, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcc in position 1674: invalid continuation byte

EDIT: I decided to just manually import this entry into my database, rather than try to read it from my CSV, based on Alastair McCormack's feedback

Based on the output from your question, it looks like the person who made the CSV mojibaked it - it doesn't seem to represent FRÉDÉRIC.ST-DENIS. You can try using windows-1252 instead of utf-8 but I think you'll end up with FRíŠDíŠRIC.ST-DENIS in your database.

ContentLicense: CC BY-SA 4.0


问:
What kills the parent process?
What ends the parent process in this code? I see don't see him exiting anywhere...
A friend of mine says that the parent isn't ended/kiled, the code simply stops at the last exit(0). If this is the case, then what wakes the parent process from sleep? Thank you in advance

```<code>adghtesd
</code>```

the results of the program:

```<code>    parent: I'm the parent
    child: I'm the child
    child: I'm exiting
    parent: child process (PID=1919) exited with value 123
    parent: exiting
    test
</code>```

答:
From this POSIX reference on sleep:

If sleep() returns because the requested time has elapsed, the value returned shall be 0. If sleep() returns due to delivery of a signal, the return value shall be the "unslept" amount (the requested time minus the time actually slept) in seconds.

What happens for you is that when the parent process receives the SIGCHLD signal, it causes the sleep function to be interrupted, and the parent continues after the sleep call.

If you want to sleep the full amount, you need to check what sleep returns, and call sleep in a loop until it returns 0.

Title: What kills the parent process?

Body:
What ends the parent process in this code? I see don't see him exiting anywhere...
A friend of mine says that the parent isn't ended/kiled, the code simply stops at the last exit(0). If this is the case, then what wakes the parent process from sleep? Thank you in advance

adghtesd

the results of the program:

    parent: I'm the parent
    child: I'm the child
    child: I'm exiting
    parent: child process (PID=1919) exited with value 123
    parent: exiting
    test


问:
Evaluate Azure ARM template before deployment
I want to evaluate ARM template file which contains actual values passed by the user before it passed to deployment engine.

Is there any way to do that?

I have started creating evaluation code through PEGJS library of nodejs by using which I can evaluate only particular condition or expression present in AZURE ARM functions but can't evaluate actual template which is passed to deployment engine to create any service.

Also, I have checked sdk azure-rest-client but can't find any way please help me to find the solution for the above issue?

答:
There is no built-in way of doing that, you can use validate deployment api call (its also implemented in different sdk's\cli's) but it doesnt actually guarantee that the template will work, it does some basic sanity checks.

You best bet is to write a script that would deploy the template and a set of tests that would validate the outcode.


问:
UIWebView autorotation bug?
Please, any help in my problem:

I have UIWebView as subview at viewController.view, and it has autoresizing set properly to fit screen bounds in any orientation. The problem is:

Rotation works properly, but if I do zoom out, and then rotate, UIWebView frame sets right, but its content is still in landscape. Seems to its UIWebView bug, but maybe someone know the solution.

P.S.
webView.scalesPagesToFit = YES;
Without any pinch (to zoom out), works great.
I've attached video link, to make the problem more clear (autoresizing mask is visible in IB).
http://dl.dropbox.com/u/11819370/Bugs/RotationBug.mov

Thanks.

答:
Try using these:</p>

```<code>[self.view setNeedDisplay];
[self.view setNeedsLayout];
</code>```

Title: UIWebView autorotation bug?

Body:
Try using these:

[self.view setNeedDisplay];
[self.view setNeedsLayout];


问:
Select from a 3-dimensional array with a 2-dimensional array
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

```<code>import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)
</code>```

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

答:
As @jdehesa sugests, we can use np.ogrid to obtain the indices for the first two axes:

```<code>ax0, ax1 = np.ogrid[:b.shape[0], :b.shape[1]]
</code>```

And then we can use b to directly index along the last axis. Note that ax0 and ax1 will be broadcast to the shape of b:

```<code>desired = a[ax0, ax1 ,b]

print(desired)
array([[ 1,  3,  5],
       [ 7,  9, 11],
       [13, 15, 17]])
</code>```

Body:
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
As @jdehesa sugests, we can use np.ogrid to obtain the indices for the first two axes:

ax0, ax1 = np.ogrid[:b.shape[0], :b.shape[1]]

And then we can use b to directly index along the last axis. Note that ax0 and ax1 will be broadcast to the shape of b:

desired = a[ax0, ax1 ,b]

print(desired)
array([[ 1,  3,  5],
       [ 7,  9, 11],
       [13, 15, 17]])


问:
Choosing transaction isolation levels
I don't have a specific example here, I was just trying to understand the different levels of transaction isolation and how one might go about deciding which is best for a given situation.

I'm trying to think of situations in which I would want a transaction that is not serializable, other than to possibly increase performance in situations where I'm willing to give up a little data integrity.

Can anybody provide an example of a situation in which "read uncommitted", "read committed", and/or "repeatable read" would be the preferable isolation level?

答:
Using the serializable isolation level does not only have advantages, but also disadvantages:

You have to accept increased performance overhead.

You have to handle serialization errors by redoing transactions, which complicates your application code and hurts performance if it happens often.

I'll come up with use cases for the other transaction levels. This list is of course not complete:

READ UNCOMMITTED: If you request this isolation level, you will actually get READ COMMITTED. So this isolation level is irrelevant. On database systems that use read locks, you use that isolation level to avoid them.

READ COMMITTED: This is the best isolation level if you are ready to deal with concurrent transactions yourself by locking rows that you want to be stable. The big advantage is that you never have to deal with serialization errors (except when you get a deadlock).

REPEATABLE READ: This isolation level is perfect for long running read-only transactions that want to see a consistent state of the database. The prime example is pg_dump.

Title: Choosing transaction isolation levels


问:
How can I make my front end app access my node server apis
I have created a front end app by creat-react-app.

The command "npm run start" can create a webpack-dev-server and serve my

front end app for developing. Here is the problem comes:

My front end app must request some api from a node server I had created before.

By default create-react-app start a webpack-dev-server on port 3000

My node server was started on port 3001

Access port 3001 directly may cause cross-origin problems

How can I gracefully start my developing story from those problems !

答:
An easy way to deal with CORS with a NodeJS backend is to use ExpressJS middleware and the "cors" extension, as detailed in the ExpressJS documentation:

ExpressJS CORS guide

For testing purposes there are various browser extensions that implement CORS headers  in all your requests automatically (Access-Control-Allow-Origin, Access-Control-Allow-Methods
, Access-Control-Allow-Headers).
Using this extension makes all your request from the browser CORS enabled (NOT GOOD FOR PRODUCTION, JUST FOR TEST/DEV).

Note that the so called "simple requests", ones using only GET / HEAD / POST and the following content types: application/x-www-form-urlencoded, multipart/form-data, text/plain do not trigger a CORS preflight request so they are allowed.

For a general understanding of CORS i would refer to the Mozilla MDN docs:

Mozilla MDN CORS guide


问:
How to get file from storage by public URL?
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

```<code>http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx
</code>```

But it does not work for me.

Also I tried to return file in backend side:

```<code>$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;
</code>```

答:
Open your filesystem.php on config folder.

```<code>'reports' => [
        'driver' => 'local',
        'root' => storage_path('app/reports'),
        'url' => env('APP_URL').'/storage/app/reports',
        'visibility' => 'public',
    ],
</code>```

add this to disk array.

After the symlink probably works. Never tried, but could work. Give it a try.

Body:
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx

But it does not work for me.

Also I tried to return file in backend side:

$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;

Body:
Open your filesystem.php on config folder.

'reports' => [
        'driver' => 'local',
        'root' => storage_path('app/reports'),
        'url' => env('APP_URL').'/storage/app/reports',
        'visibility' => 'public',
    ],

add this to disk array.

After the symlink probably works. Never tried, but could work. Give it a try.


问:
Close browser or page about vue
i try to close the page even and the browser in order to logoff user,but i failed.

1.window.onunload;
2.window.onbeforeunload.

```<code>window.onunload = function() {
  differTime = new Date().getTime() - beginTime;
  if (differTime <= 5) {
    clear(CURRENT_LOGIN_INFO, false);
  } else {}
  clear(CURRENT_LOGIN_INFO, false);
};

window.onbeforeunload = function(e) {
  beginTime = new Date().getTime();
  e = e || window.event;
  if (e) {
    clear(CURRENT_LOGIN_INFO, false);
    e.returnValue = "close!!!";
  }
  clear(CURRENT_LOGIN_INFO, false);
  return "close!!!";
};
</code>```

the user has been logout but actually it still here.

答: Invalidating the user client-side is a bad practice. You should try to expire a users session server-side. That being said, you should check where you session information is kept in the browser (eg. LocalStorage, sessionStorage, Cookies). Have a look at https://www.w3schools.com/jsref/met_storage_clear.asp</p>

Title: Close browser or page about vue

Body:
i try to close the page even and the browser in order to logoff user,but i failed.

1.window.onunload;
2.window.onbeforeunload.

window.onunload = function() {
  differTime = new Date().getTime() - beginTime;
  if (differTime <= 5) {
    clear(CURRENT_LOGIN_INFO, false);
  } else {}
  clear(CURRENT_LOGIN_INFO, false);
};

window.onbeforeunload = function(e) {
  beginTime = new Date().getTime();
  e = e || window.event;
  if (e) {
    clear(CURRENT_LOGIN_INFO, false);
    e.returnValue = "close!!!";
  }
  clear(CURRENT_LOGIN_INFO, false);
  return "close!!!";
};

the user has been logout but actually it still here.


问:
How to create a Javascript Object with sorted keys in a for loop?
I have an array like this:

```<code>[
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
]
</code>```

I need to create an object from the array, with the state as a key, and sorted.

```<code>{
  "New South Wales": [
    {
      "name": "Name NSW",
      "state": "New South Wales"
    }
  ],
  "Victoria": [
    {
      "name": "Name VIC",
      "state": "Victoria"
    }
  ],
}
</code>```

Notice that the NSW state has to be first in the object, but it is not the first item in the array. So after using loop through the array to create an object, the result is that the Victoria state appears first. I know that I can sort the result object, with many more codes. But is there any ways to create an object, whereas the keys are sorted immediately? (please check my code below)

```<code>function () {
  let result = {}
  array.forEach((item) => {
    if (!result[item.state]) {
      result[item.state] = []
    }
    result[item.state].push(item)
  })
  return result
}
</code>```

Update
Please read my question again. I know that there are a lot of ways for sorting the keys, but it's not what I meant. I want the keys to be sorted right in the loop, not after the object is created.

答:
You can use Object.fromEntries to create such an object. But one thing to note here is that Object does not have sorted keys.

var data = [
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
];

var newData = Object.fromEntries(data.map(el => [el.state, el]));

console.log(newData);```

Body:
I have an array like this:

[
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
]

I need to create an object from the array, with the state as a key, and sorted.

{
  "New South Wales": [
    {
      "name": "Name NSW",
      "state": "New South Wales"
    }
  ],
  "Victoria": [
    {
      "name": "Name VIC",
      "state": "Victoria"
    }
  ],
}

Notice that the NSW state has to be first in the object, but it is not the first item in the array. So after using loop through the array to create an object, the result is that the Victoria state appears first. I know that I can sort the result object, with many more codes. But is there any ways to create an object, whereas the keys are sorted immediately? (please check my code below)

function () {
  let result = {}
  array.forEach((item) => {
    if (!result[item.state]) {
      result[item.state] = []
    }
    result[item.state].push(item)
  })
  return result
}

Update
Please read my question again. I know that there are a lot of ways for sorting the keys, but it's not what I meant. I want the keys to be sorted right in the loop, not after the object is created.


问:
React Intl `undefined()` must be called with an object expression
React intl doesn't build on CI with following error:

[React Intl] undefined() must be called with an object expression with values that are React Intl Message Descriptors, also defined as object expressions.

Tried this:
Issue link
But it doesn't help.

```<code>import ConnectedComponent from './ConnectedComponent';
import {connect} from 'react-redux';
import {injectIntl, defineMessages} from 'react-intl';

const messages = defineMessages({
    LABEL: {id: "CONNECTED.COMPONENT.LABEL", defaultMessage: "Label"},
});

const mapStateToProps = (state, ownProps) => {
    const { intl } = ownProps;
    return {
        inputLabel: intl.formatMessage(messages.LABEL),
    };
};

export default injectIntl(connect(
    mapStateToProps
)(ConnectedComponent));
</code>```

答:
Looks like it's a bug in babel-plugin-react-intl [1], which is supposedly fixed already. </p>

<p>[1] https://github.com/formatjs/formatjs/issues/37</p>

Body:
React intl doesn't build on CI with following error:

[React Intl] undefined() must be called with an object expression with values that are React Intl Message Descriptors, also defined as object expressions.

Tried this:
Issue link
But it doesn't help.

import ConnectedComponent from './ConnectedComponent';
import {connect} from 'react-redux';
import {injectIntl, defineMessages} from 'react-intl';

const messages = defineMessages({
    LABEL: {id: "CONNECTED.COMPONENT.LABEL", defaultMessage: "Label"},
});

const mapStateToProps = (state, ownProps) => {
    const { intl } = ownProps;
    return {
        inputLabel: intl.formatMessage(messages.LABEL),
    };
};

export default injectIntl(connect(
    mapStateToProps
)(ConnectedComponent));

Body:
Looks like it's a bug in babel-plugin-react-intl [1], which is supposedly fixed already.

[1] https://github.com/formatjs/formatjs/issues/37


问:
Update a single document in mongodb using spark with java
I just started apache-spark with java. There is many documents saved in a collection I want to find a document on the basis of some key and update it.
Simply I want to do find and update in apache-spark with java

This is the code to read a document form mongo

```<code>Map<String, String> readOverrides = new HashMap<String, String>();
readOverrides.put("collection", "bb_playing22");
ReadConfig readConfig = ReadConfig.create(createJavaSparkContext()).withOptions(readOverrides);
JavaMongoRDD<Document> customRdd = MongoSpark.load(createJavaSparkContext(), readConfig);
        JavaRDD<Document> rdd = customRdd.filter(((t1) -> {
            return t1.getLong("playing22_id") == 3; //To change body of generated lambdas, choose Tools | Templates.
        }));
</code>```

but not able to update this document

答:
Spark does a lazy evaluation of your transformations hence unless you call an action over an rdd, it won't execute any transformations you code.
See common actions here.

Also, this does not seem like a use case where you'd like to use spark.
If your actual requirement is just to update a document as per a value then you should look into indexing in mongo and just update a document through a mongo driver in java directly.

Body:
I just started apache-spark with java. There is many documents saved in a collection I want to find a document on the basis of some key and update it.
Simply I want to do find and update in apache-spark with java

This is the code to read a document form mongo

Map<String, String> readOverrides = new HashMap<String, String>();
readOverrides.put("collection", "bb_playing22");
ReadConfig readConfig = ReadConfig.create(createJavaSparkContext()).withOptions(readOverrides);
JavaMongoRDD<Document> customRdd = MongoSpark.load(createJavaSparkContext(), readConfig);
        JavaRDD<Document> rdd = customRdd.filter(((t1) -> {
            return t1.getLong("playing22_id") == 3; //To change body of generated lambdas, choose Tools | Templates.
        }));

but not able to update this document


问:
I can't display temperature on my website
I'm new to Javascript and I followed a tutorial that is pretty easy to display open weather data on my website with javascript.
https://codepen.io/mattfroese/pen/WaeYQV
https://bytemaster.io/fetch-weather-openweathermap-api-javascript

It's very odd but it works on codepen and not my website...

Maybe you can help me ? Here is the code...

const key = '';
if(key=='') document.getElementById('temp').innerHTML = ('Remember to add your api key!');

function weatherBallon( cityID ) {
 fetch('http://api.openweathermap.org/data/2.5/weather?lat=47.204530&lon=-1.563377&appid=OPENWEATHER_APP_ID')
 .then(function(resp) { return resp.json() }) // Convert data to json
 .then(function(data) {
  drawWeather(data);
 })
 .catch(function() {
  // catch any errors
 });
}
function drawWeather( d ) {
  var celcius = Math.round(parseFloat(d.main.temp)-273.15);
 var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
  var description = d.weather[0].description;

 document.getElementById('description').innerHTML = description;
 document.getElementById('temp').innerHTML = celcius + '°';
 document.getElementById('location').innerHTML = d.name;

  if( description.indexOf('rain') > 0 ) {
   document.body.className = 'rainy';
  } else if( description.indexOf('cloud') > 0 ) {
   document.body.className = 'cloudy';
  } else if( description.indexOf('sunny') > 0 ) {
   document.body.className = 'sunny';
  } else {
   document.body.className = 'clear';
  }
}
window.onload = function() {
 weatherBallon( 6167865 );
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>footer {
  position:fixed;
  bottom:0px;
  left:0;
  height: 77px;
  width: 100%;
  margin: auto;
  font: 30px "Elastik-B";

}

.footer ul {
    margin: 0;
    padding: 0;
    position:absolute;
    list-style-type: none;
    bottom:15px;
    right:5%;
}

.footer li {
   text-align:right;
   float: right;
   display: block;
   padding: 15px;
}</code>```

...

```

答:
You have not added your api key in first line

```<code>const key = " ";
</code>```

Please add api key and check if you are still getting an error message, try this

```<code><script lang="text/javascript">
const key = 'b2b1b01a9261a8b31e450dffc404f9e9';
if(key=='') document.getElementById('temp').innerHTML = ('Remember to add your api key!');

function weatherBallon( cityID ) {
    fetch('http://api.openweathermap.org/data/2.5/weather?lat=47.204530&lon=-1.563377&appid=b2b1b01a9261a8b31e450dffc404f9e9')
    .then(function(resp) { return resp.json() }) // Convert data to json
    .then(function(data) {
        drawWeather(data);
    })
    .catch(function() {
        // catch any errors
    });
}
function drawWeather( d ) {
  var celcius = Math.round(parseFloat(d.main.temp)-273.15);
    var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
  var description = d.weather[0].description;

    document.getElementById('description').innerHTML = description;
    document.getElementById('temp').innerHTML = celcius + '°';
    document.getElementById('location').innerHTML = d.name;

  if( description.indexOf('rain') > 0 ) {
    document.body.className = 'rainy';
  } else if( description.indexOf('cloud') > 0 ) {
    document.body.className = 'cloudy';
  } else if( description.indexOf('sunny') > 0 ) {
    document.body.className = 'sunny';
  } else {
    document.body.className = 'clear';
  }
}
window.onload = function() {
    weatherBallon( 6167865 );
}
  </script>
</code>```

Body:
I'm new to Javascript and I followed a tutorial that is pretty easy to display open weather data on my website with javascript.
https://codepen.io/mattfroese/pen/WaeYQV
https://bytemaster.io/fetch-weather-openweathermap-api-javascript

It's very odd but it works on codepen and not my website...

Maybe you can help me ? Here is the code...

const key = '';
if(key=='') document.getElementById('temp').innerHTML = ('Remember to add your api key!');

function weatherBallon( cityID ) {
 fetch('http://api.openweathermap.org/data/2.5/weather?lat=47.204530&lon=-1.563377&appid=OPENWEATHER_APP_ID')
 .then(function(resp) { return resp.json() }) // Convert data to json
 .then(function(data) {
  drawWeather(data);
 })
 .catch(function() {
  // catch any errors
 });
}
function drawWeather( d ) {
  var celcius = Math.round(parseFloat(d.main.temp)-273.15);
 var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
  var description = d.weather[0].description;

 document.getElementById('description').innerHTML = description;
 document.getElementById('temp').innerHTML = celcius + '°';
 document.getElementById('location').innerHTML = d.name;

  if( description.indexOf('rain') > 0 ) {
   document.body.className = 'rainy';
  } else if( description.indexOf('cloud') > 0 ) {
   document.body.className = 'cloudy';
  } else if( description.indexOf('sunny') > 0 ) {
   document.body.className = 'sunny';
  } else {
   document.body.className = 'clear';
  }
}
window.onload = function() {
 weatherBallon( 6167865 );
}

footer {
  position:fixed;
  bottom:0px;
  left:0;
  height: 77px;
  width: 100%;
  margin: auto;
  font: 30px "Elastik-B";

}

.footer ul {
    margin: 0;
    padding: 0;
    position:absolute;
    list-style-type: none;
    bottom:15px;
    right:5%;
}

.footer li {
   text-align:right;
   float: right;
   display: block;
   padding: 15px;
}

...

Body:
You have not added your api key in first line

const key = " ";

Please add api key and check if you are still getting an error message, try this

<script lang="text/javascript">
const key = 'b2b1b01a9261a8b31e450dffc404f9e9';
if(key=='') document.getElementById('temp').innerHTML = ('Remember to add your api key!');

function weatherBallon( cityID ) {
    fetch('http://api.openweathermap.org/data/2.5/weather?lat=47.204530&lon=-1.563377&appid=b2b1b01a9261a8b31e450dffc404f9e9')
    .then(function(resp) { return resp.json() }) // Convert data to json
    .then(function(data) {
        drawWeather(data);
    })
    .catch(function() {
        // catch any errors
    });
}
function drawWeather( d ) {
  var celcius = Math.round(parseFloat(d.main.temp)-273.15);
    var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
  var description = d.weather[0].description;

    document.getElementById('description').innerHTML = description;
    document.getElementById('temp').innerHTML = celcius + '°';
    document.getElementById('location').innerHTML = d.name;

  if( description.indexOf('rain') > 0 ) {
    document.body.className = 'rainy';
  } else if( description.indexOf('cloud') > 0 ) {
    document.body.className = 'cloudy';
  } else if( description.indexOf('sunny') > 0 ) {
    document.body.className = 'sunny';
  } else {
    document.body.className = 'clear';
  }
}
window.onload = function() {
    weatherBallon( 6167865 );
}
  </script>


问:
How to get the last folder's name where the file is stored (without using macro)
I need to extract - in a cell - the last folder name where the active excel file is stored.

E.g. C:/Documents/Users/Accounting/May 2019/Expenses.xls

I want to extract/output the text "May 2019" in a specific cell by using a formula (not a macro).

Thank you in advance.

答:
```<code>=ANNULLA.SPAZI(STRINGA.ESTRAI(SOSTITUISCI(CELLA("filename";A1);"\";RIPETI(" ";999));SOMMA(SE(CELLA("filename";A1)<>"";LUNGHEZZA(CELLA("filename";A1))-LUNGHEZZA(SOSTITUISCI(CELLA("filename";A1);"\";""));0))*999-998;999))
</code>```

Localized Italian version of @SolarMike code's.

Body:
=ANNULLA.SPAZI(STRINGA.ESTRAI(SOSTITUISCI(CELLA("filename";A1);"\";RIPETI(" ";999));SOMMA(SE(CELLA("filename";A1)<>"";LUNGHEZZA(CELLA("filename";A1))-LUNGHEZZA(SOSTITUISCI(CELLA("filename";A1);"\";""));0))*999-998;999))

Localized Italian version of @SolarMike code's.


问:
Check Credit Card Type (Mastercard vs Visa) using PayPal API
Are there any API that I can check if my customer are using paying using Mastercard or Visa card?

Just the card type is enough, no need the number.

As mentioned below, we don't have access to user credit card as they are stored in PayPal.

答:
Back in the day, you could use the Vault API for saving the credit card securely and use it for paypal payments. Since PayPal acquired BrainTree the product for handling credit cards directly is deprecated and replaced with BrainTree Direct.

If you are only handling PayPal payments directly there are no options to view the payment method.


问:
Why OnPaint event of two glcontrols not running synchronously - opentk c#
I have two glControls. Each have it's on paint event. But before completely running the functions of paint1 event, system calls paint2 event. I thought the functions inside each event will be called completely synchronously. Can I make that way. Means, paint2 event should be called after completing paint1 event?

```<code>private void Form3_Load(object sender, EventArgs e)
    {
       glControl1.Visible = true;
       glControl2.Visible = true;
       GL.Enable(EnableCap.DepthTest);
    }
    private void glControl1_Load(object sender, EventArgs e)
    {
        if (glControl2.Created &&
                                glControl2.Context.IsCurrent)
        { glControl2.Context.MakeCurrent(null); }

        if (glControl1.Context.IsCurrent == false)
        {
            glControl1.MakeCurrent();
        }
        obj_openTK.Init();
    }

    private void glControl2_Load(object sender, EventArgs e)
    {
        if (glControl1.Created &&
         glControl1.Context.IsCurrent)
        { glControl1.Context.MakeCurrent(null); }

        if (glControl2.Context.IsCurrent == false)
        { glControl2.MakeCurrent(); }

        obj_openTK.Init();
    }
    private void glControl1_Paint(object sender, PaintEventArgs e)
    {
            if (glControl2.Created &&
                     glControl2.Context.IsCurrent)
            { glControl2.Context.MakeCurrent(null); }

            if (glControl1.Context.IsCurrent == false)
            { glControl1.MakeCurrent(); }

            Render();
    }
     private void glControl2_Paint(object sender, PaintEventArgs e)
    {
          try{
            if (glControl1.Created &&
            glControl1.Context.IsCurrent)
            { glControl1.Context.MakeCurrent(null); }

            if (glControl2.Context.IsCurrent == false)
            { glControl2.MakeCurrent(); }
            Render2();
             }
            catch(Exception ex)
           {
            string exx = ex.ToString();
            string stacktrace = ex.StackTrace.ToString();
           }
        }
    private void Render()//for first image
    {
        GL.DeleteTextures(1, ref texture);
        texture = obj_openTK.LoadTexture(image);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        obj_openTK.DrawImage(texture,glControl1);
        GL.Flush();
        glControl1.SwapBuffers();
    }
    private void Render2()// for second image
    {
        GL.DeleteTextures(1, ref texture);
        texture = obj_openTK.LoadTexture(image2);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        obj_openTK.DrawImage(texture, glControl2);
        GL.Flush();
        glControl2.SwapBuffers();
    }
    ===============openTK class========================

class openTK
{
int positionLocation1;
int program;
int positionLocation;
int vertShader;
int fragShader;
int buffer;
float[] vertices = {
    // Left bottom triangle
    -1f, -1f, 0f,
    1f, -1f, 0f,
    1f, 1f, 0f,
    // Right top triangle
    1f, 1f, 0f,
   -1f, 1f, 0f,
   -1f, -1f, 0f
};

public int LoadTexture(Bitmap bitmap)
{
int tex = -1;
if (bitmap != null)
{
    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

    GL.GenTextures(1, out tex);
    GL.BindTexture(TextureTarget.Texture2D, tex);

    bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
   ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
    OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
    bitmap.UnlockBits(data);

    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
}
return tex;
}
public void DrawImage(int image, GLControl glControl)
{
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
GL.Disable(EnableCap.Lighting);
GL.Enable(EnableCap.Texture2D);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, image);
GL.Uniform1(positionLocation1, 0);

RunShaders();

GL.Disable(EnableCap.Texture2D);
GL.PopMatrix();

GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();

GL.MatrixMode(MatrixMode.Modelview);

ErrorCode ec = GL.GetError();
if (ec != 0)
    System.Console.WriteLine(ec.ToString());
Console.Read();
}
  private void RunShaders()
 {
 GL.UseProgram(program);
 GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / 3);
 ErrorCode ec = GL.GetError();
 if (ec != 0)
 System.Console.WriteLine(ec.ToString());
 Console.Read();
 }
 private void Init()
 {
 CreateShaders();
 CreateProgram();
 InitBuffers();
 }
 private void CreateProgram()
 {
 program = GL.CreateProgram();
 GL.AttachShader(program, vertShader);
 GL.AttachShader(program, fragShader);
 GL.LinkProgram(program);
 }
private void InitBuffers()
{
buffer = GL.GenBuffer();
positionLocation = GL.GetAttribLocation(program, "a_position");
positionLocation1 = GL.GetUniformLocation(program, "sTexture");
GL.EnableVertexAttribArray(positionLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(float)), vertices, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
}
private void CreateShaders()
{
/***********Vert Shader********************/
vertShader = GL.CreateShader(ShaderType.VertexShader);
GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                    varying vec2 vTexCoord;
                    void main() {
                    vTexCoord = (a_position.xy+1)/2 ;
                    gl_Position = vec4(a_position, 1);
                    }");
GL.CompileShader(vertShader);

/***********Frag Shader ****************/
fragShader = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(fragShader, @"precision highp float;
uniform sampler2D sTexture;varying vec2 vTexCoord;
             void main ()
             {
           vec4    color   = texture2D (sTexture, vTexCoord);
           gl_FragColor    = color;
             }");
GL.CompileShader(fragShader);
  }
}
</code>```

Now when running this code , paint1 throws below exception. It is because render2() is calling before completing render().

OpenTK.Graphics.GraphicsContextException: 'Failed to swap buffers for context 131072 current.

答:
A quick and simple way would be by adding a lock to your code...

```<code>private object locker = new object();

private void glControl1_Paint(object sender, PaintEventArgs e)
{
    lock(locker) {
       if (glControl2.Created &&
                 glControl2.Context.IsCurrent)
       { glControl2.Context.MakeCurrent(null); }

       if (glControl1.Context.IsCurrent == false)
       { glControl1.MakeCurrent(); }

       Render();
    }
}

private void glControl2_Paint(object sender, PaintEventArgs e)
{
    lock(locker) {
       if (glControl1.Created &&
          glControl1.Context.IsCurrent)
       { glControl1.Context.MakeCurrent(null); }

       if (glControl2.Context.IsCurrent == false)
       { glControl2.MakeCurrent(); }

       Render2();
    }

}
</code>```

When one block of code gets a lock on locker, then any other attempt to lock will be delayed until the first lock is cleared.

If you need to control further the order of the lock, you could use a queue to hold an identifier on which block of code is trying to get a lock, if it isn't the one you want first, delay that lock until the correct one locks first. This could cause issues however, if for some reason the expected "first" lock does not happen. Then the second will not, unless you add a wait timeout.

EDIT:

In your Render functions...

```<code>private void Render()
{
    GL.DeleteTextures(1, ref texture);
    texture = obj_openTK.LoadTexture(image);

    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
    obj_openTK.DrawImage(texture,glControl1);
    GL.Flush();
    glControl1.SwapBuffers();
}
private void Render2()
{
    GL.DeleteTextures(1, ref texture2);
    texture2 = obj_openTK.LoadTexture(image2);

    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

    obj_openTK.DrawImage(texture2, glControl2);
    GL.Flush();
    glControl2.SwapBuffers();
}
</code>```

I believe you are calling GL.Clear() too much. It really only needs to be called once per loop. Also, I do not think GL.Flush() is doing anything for you since you are double buffering.

Beyond that, I do not believe the problem lies in the code you have provided, but likely something with the construction or configuration of your glControl1 and glControl2.

Body:
I have two glControls. Each have it's on paint event. But before completely running the functions of paint1 event, system calls paint2 event. I thought the functions inside each event will be called completely synchronously. Can I make that way. Means, paint2 event should be called after completing paint1 event?

private void Form3_Load(object sender, EventArgs e)
    {
       glControl1.Visible = true;
       glControl2.Visible = true;
       GL.Enable(EnableCap.DepthTest);
    }
    private void glControl1_Load(object sender, EventArgs e)
    {
        if (glControl2.Created &&
                                glControl2.Context.IsCurrent)
        { glControl2.Context.MakeCurrent(null); }

        if (glControl1.Context.IsCurrent == false)
        {
            glControl1.MakeCurrent();
        }
        obj_openTK.Init();
    }

    private void glControl2_Load(object sender, EventArgs e)
    {
        if (glControl1.Created &&
         glControl1.Context.IsCurrent)
        { glControl1.Context.MakeCurrent(null); }

        if (glControl2.Context.IsCurrent == false)
        { glControl2.MakeCurrent(); }

        obj_openTK.Init();
    }
    private void glControl1_Paint(object sender, PaintEventArgs e)
    {
            if (glControl2.Created &&
                     glControl2.Context.IsCurrent)
            { glControl2.Context.MakeCurrent(null); }

            if (glControl1.Context.IsCurrent == false)
            { glControl1.MakeCurrent(); }

            Render();
    }
     private void glControl2_Paint(object sender, PaintEventArgs e)
    {
          try{
            if (glControl1.Created &&
            glControl1.Context.IsCurrent)
            { glControl1.Context.MakeCurrent(null); }

            if (glControl2.Context.IsCurrent == false)
            { glControl2.MakeCurrent(); }
            Render2();
             }
            catch(Exception ex)
           {
            string exx = ex.ToString();
            string stacktrace = ex.StackTrace.ToString();
           }
        }
    private void Render()//for first image
    {
        GL.DeleteTextures(1, ref texture);
        texture = obj_openTK.LoadTexture(image);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        obj_openTK.DrawImage(texture,glControl1);
        GL.Flush();
        glControl1.SwapBuffers();
    }
    private void Render2()// for second image
    {
        GL.DeleteTextures(1, ref texture);
        texture = obj_openTK.LoadTexture(image2);
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        obj_openTK.DrawImage(texture, glControl2);
        GL.Flush();
        glControl2.SwapBuffers();
    }
    ===============openTK class========================

class openTK
{
int positionLocation1;
int program;
int positionLocation;
int vertShader;
int fragShader;
int buffer;
float[] vertices = {
    // Left bottom triangle
    -1f, -1f, 0f,
    1f, -1f, 0f,
    1f, 1f, 0f,
    // Right top triangle
    1f, 1f, 0f,
   -1f, 1f, 0f,
   -1f, -1f, 0f
};

public int LoadTexture(Bitmap bitmap)
{
int tex = -1;
if (bitmap != null)
{
    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

    GL.GenTextures(1, out tex);
    GL.BindTexture(TextureTarget.Texture2D, tex);

    bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
   ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
    OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
    bitmap.UnlockBits(data);

    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
}
return tex;
}
public void DrawImage(int image, GLControl glControl)
{
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
GL.Disable(EnableCap.Lighting);
GL.Enable(EnableCap.Texture2D);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, image);
GL.Uniform1(positionLocation1, 0);

RunShaders();

GL.Disable(EnableCap.Texture2D);
GL.PopMatrix();

GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();

GL.MatrixMode(MatrixMode.Modelview);

ErrorCode ec = GL.GetError();
if (ec != 0)
    System.Console.WriteLine(ec.ToString());
Console.Read();
}
  private void RunShaders()
 {
 GL.UseProgram(program);
 GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / 3);
 ErrorCode ec = GL.GetError();
 if (ec != 0)
 System.Console.WriteLine(ec.ToString());
 Console.Read();
 }
 private void Init()
 {
 CreateShaders();
 CreateProgram();
 InitBuffers();
 }
 private void CreateProgram()
 {
 program = GL.CreateProgram();
 GL.AttachShader(program, vertShader);
 GL.AttachShader(program, fragShader);
 GL.LinkProgram(program);
 }
private void InitBuffers()
{
buffer = GL.GenBuffer();
positionLocation = GL.GetAttribLocation(program, "a_position");
positionLocation1 = GL.GetUniformLocation(program, "sTexture");
GL.EnableVertexAttribArray(positionLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(float)), vertices, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
}
private void CreateShaders()
{
/***********Vert Shader********************/
vertShader = GL.CreateShader(ShaderType.VertexShader);
GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                    varying vec2 vTexCoord;
                    void main() {
                    vTexCoord = (a_position.xy+1)/2 ;
                    gl_Position = vec4(a_position, 1);
                    }");
GL.CompileShader(vertShader);

/***********Frag Shader ****************/
fragShader = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(fragShader, @"precision highp float;
uniform sampler2D sTexture;varying vec2 vTexCoord;
             void main ()
             {
           vec4    color   = texture2D (sTexture, vTexCoord);
           gl_FragColor    = color;
             }");
GL.CompileShader(fragShader);
  }
}

Now when running this code , paint1 throws below exception. It is because render2() is calling before completing render().

OpenTK.Graphics.GraphicsContextException: 'Failed to swap buffers for context 131072 current.

Body:
A quick and simple way would be by adding a lock to your code...

private object locker = new object();

private void glControl1_Paint(object sender, PaintEventArgs e)
{
    lock(locker) {
       if (glControl2.Created &&
                 glControl2.Context.IsCurrent)
       { glControl2.Context.MakeCurrent(null); }

       if (glControl1.Context.IsCurrent == false)
       { glControl1.MakeCurrent(); }

       Render();
    }
}

private void glControl2_Paint(object sender, PaintEventArgs e)
{
    lock(locker) {
       if (glControl1.Created &&
          glControl1.Context.IsCurrent)
       { glControl1.Context.MakeCurrent(null); }

       if (glControl2.Context.IsCurrent == false)
       { glControl2.MakeCurrent(); }

       Render2();
    }

}

When one block of code gets a lock on locker, then any other attempt to lock will be delayed until the first lock is cleared.

If you need to control further the order of the lock, you could use a queue to hold an identifier on which block of code is trying to get a lock, if it isn't the one you want first, delay that lock until the correct one locks first. This could cause issues however, if for some reason the expected "first" lock does not happen. Then the second will not, unless you add a wait timeout.

EDIT:

In your Render functions...

private void Render()
{
    GL.DeleteTextures(1, ref texture);
    texture = obj_openTK.LoadTexture(image);

    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
    obj_openTK.DrawImage(texture,glControl1);
    GL.Flush();
    glControl1.SwapBuffers();
}
private void Render2()
{
    GL.DeleteTextures(1, ref texture2);
    texture2 = obj_openTK.LoadTexture(image2);

    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

    obj_openTK.DrawImage(texture2, glControl2);
    GL.Flush();
    glControl2.SwapBuffers();
}

I believe you are calling GL.Clear() too much. It really only needs to be called once per loop. Also, I do not think GL.Flush() is doing anything for you since you are double buffering.

Beyond that, I do not believe the problem lies in the code you have provided, but likely something with the construction or configuration of your glControl1 and glControl2.


问:
From bouding boxes to masks
I have a csv dataframe as follow:

```<code>    filename  width  height  class  xmin  ymin  xmax  ymax
0     1.jpg   2048    1251    1      706   513   743   562
1    10.jpg   1600     980    1      715   157   733   181
2    11.jpg   2828    1828    1      460  1530   482  1557
3    12.jpg   1276    1754    1      846   517   878   563
....
19   10.jpg   1600     980    1      428    83   483   145
</code>```

I would like to get the masks for every image. I've succeded to get them if there is only one box for each image, however some images have multiple bouding boxes (example 10.jpg). How can I be able to add that bounding box to the mask ?

So far my code is as follow ( works good if image has 1 row ):

```<code>for idimage in annotations['filename']:
    img = cv2.imread('images/'+idimage)

    x1 = annotations[annotations['filename'] == idimage]['xmin'][0]
    y1 = annotations[annotations['filename'] == idimage]['ymin'][0]
    x2 = annotations[annotations['filename'] == idimage]['xmax'][0]
    y2 = annotations[annotations['filename'] == idimage]['ymax'][0]

    mask = np.zeros((img.shape[0],img.shape[1])).astype('uint8')
    mask[y1:y2, x1:x2] = 1

    mask = cv2.imwrite('mask/'+idimage,mask)
</code>```

Thank you !

答:
Actually, this is wrong:

I've succeded to get them if there is only one box for each image

Your code works only for the first row, because you request index 0. All the other rows fails because the dataframes remember their original index.

In this case, groupby does the trick.

```<code>for fn, subdf in annotations.groupby('filename'):
    img = cv2.imread('images/'+fn)
    mask = np.zeros((img.shape[0],img.shape[1])).astype('uint8')
    for _, row in subdf.iterrows():
        mask[row['ymin']:row['ymax'], row['xmin']:row['xmax']] = 1

    cv2.imwrite('mask/'+fn, mask)
</code>```

Here groupby allows to iterate over a series of subdataframes with the same 'filename'.

Then in a nested loop iterrows is used to iterate over each row of each subdataframe in order to extract the value and build the mask.

As you see, the mask is buildt each iteration of the outer loop, leaving the inner loop to "paint" different rectangles of the mask, one rectangle for each row of the subdataframe.

EDIT

A similar but slightly faster solution for the inner loop, instead of iterrows is:

```<code>for x1, y1, x2, y2 in zip(subdf['xmin'], subdf['ymin'], subdf['xmax'], subdf['ymax']):
    mask[y1:y2, x1:x2] = 1
</code>```

If you have a large amount of rows may be useful.

Title: From bouding boxes to masks

Body:
I have a csv dataframe as follow:

    filename  width  height  class  xmin  ymin  xmax  ymax
0     1.jpg   2048    1251    1      706   513   743   562
1    10.jpg   1600     980    1      715   157   733   181
2    11.jpg   2828    1828    1      460  1530   482  1557
3    12.jpg   1276    1754    1      846   517   878   563
....
19   10.jpg   1600     980    1      428    83   483   145

I would like to get the masks for every image. I've succeded to get them if there is only one box for each image, however some images have multiple bouding boxes (example 10.jpg). How can I be able to add that bounding box to the mask ?

So far my code is as follow ( works good if image has 1 row ):

for idimage in annotations['filename']:
    img = cv2.imread('images/'+idimage)

    x1 = annotations[annotations['filename'] == idimage]['xmin'][0]
    y1 = annotations[annotations['filename'] == idimage]['ymin'][0]
    x2 = annotations[annotations['filename'] == idimage]['xmax'][0]
    y2 = annotations[annotations['filename'] == idimage]['ymax'][0]

    mask = np.zeros((img.shape[0],img.shape[1])).astype('uint8')
    mask[y1:y2, x1:x2] = 1

    mask = cv2.imwrite('mask/'+idimage,mask)

Thank you !

Body:
Actually, this is wrong:

I've succeded to get them if there is only one box for each image

Your code works only for the first row, because you request index 0. All the other rows fails because the dataframes remember their original index.

In this case, groupby does the trick.

for fn, subdf in annotations.groupby('filename'):
    img = cv2.imread('images/'+fn)
    mask = np.zeros((img.shape[0],img.shape[1])).astype('uint8')
    for _, row in subdf.iterrows():
        mask[row['ymin']:row['ymax'], row['xmin']:row['xmax']] = 1

    cv2.imwrite('mask/'+fn, mask)

Here groupby allows to iterate over a series of subdataframes with the same 'filename'.

Then in a nested loop iterrows is used to iterate over each row of each subdataframe in order to extract the value and build the mask.

As you see, the mask is buildt each iteration of the outer loop, leaving the inner loop to "paint" different rectangles of the mask, one rectangle for each row of the subdataframe.

EDIT

A similar but slightly faster solution for the inner loop, instead of iterrows is:

for x1, y1, x2, y2 in zip(subdf['xmin'], subdf['ymin'], subdf['xmax'], subdf['ymax']):
    mask[y1:y2, x1:x2] = 1

If you have a large amount of rows may be useful.


问:
Clipping / cropping lines and fills in matplotlib on seaborn distplot kde-function
Let's say I use seaborn to plot a distribution, it's median and standard deviation like this:

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

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

# Plot
sns.distplot(data)
plt.axvline(median, c='r')
plt.axvline(low, c='k')
plt.axvline(hi, c='k')
```

How would I go about "cropping" or "clipping" the lines, so they only appear below the kde-function of the distplot? The result should be something like this (quickly done with gimp):

Bonus question: How would I do the same with a plt.fill_between(), so that only the area under the curve is filled? I think I'm missing something easy here. I've already clipped fill_between calls to other elements before, but I don't know how to get coordinates of the function and how to do it with lines.

Is there an easy and concise way to do what I want?

答:
One way to doing this is to find the data that corresponds to the smooth line that kdeplot adds to the graph and use its x and y coordinates.

The following code assumes that there is only one line in the plot --- with more than one line we have to find which line corresponds to the kdeplot line.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.interpolate import interp1d

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

ax = sns.distplot(data)
# get the line that sns uses for kdeplot; at this point in the code
# there is only one line; if there are more we need to exract the correct
# one.
line = ax.lines[0].get_data()
# To get y for x=low, x=high and x=median we can interpolate the line data
ipf = interp1d(x=line[0], y=line[1])

ax.plot([low, low], [0, ipf(low)])
ax.plot([hi, hi], [0, ipf(hi)])
ax.plot([median, median], [0, ipf(median)]);
```

<p><img src="https://i.stack.imgur.com/VvaMY.png" alt="Line to kdeplot"></p>

<p>We can use the line data as input to <code>fill_between</code>.</p>

<pre class="lang-py prettyprint-override"><code>plt.fill_between(line[0], np.zeros(len(line[0])), line[1]);
</code>```

Hope this helps.

Body:
Let's say I use seaborn to plot a distribution, it's median and standard deviation like this:

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

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

# Plot
sns.distplot(data)
plt.axvline(median, c='r')
plt.axvline(low, c='k')
plt.axvline(hi, c='k')

How would I go about "cropping" or "clipping" the lines, so they only appear below the kde-function of the distplot? The result should be something like this (quickly done with gimp):

Bonus question: How would I do the same with a plt.fill_between(), so that only the area under the curve is filled? I think I'm missing something easy here. I've already clipped fill_between calls to other elements before, but I don't know how to get coordinates of the function and how to do it with lines.

Is there an easy and concise way to do what I want?

Body:
One way to doing this is to find the data that corresponds to the smooth line that kdeplot adds to the graph and use its x and y coordinates.

The following code assumes that there is only one line in the plot --- with more than one line we have to find which line corresponds to the kdeplot line.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.interpolate import interp1d

# Get data
data = np.random.randn(6000)

# Compute statistics
median = np.median(data)
sigma = np.std(data)

low = median - sigma
hi = median + sigma

ax = sns.distplot(data)
# get the line that sns uses for kdeplot; at this point in the code
# there is only one line; if there are more we need to exract the correct
# one.
line = ax.lines[0].get_data()
# To get y for x=low, x=high and x=median we can interpolate the line data
ipf = interp1d(x=line[0], y=line[1])

ax.plot([low, low], [0, ipf(low)])
ax.plot([hi, hi], [0, ipf(hi)])
ax.plot([median, median], [0, ipf(median)]);

We can use the line data as input to fill_between.

plt.fill_between(line[0], np.zeros(len(line[0])), line[1]);

Hope this helps.


问:
Can anyone please explain me the what are Django modelform_factory and modelformset_factory?
Kindly explain me the what are Django modelform_factory and modelformset_factory, and how do they correlate to the Django models, forms and modelforms?
I'm a beginner to Django and came across these terms. Looked up on the internet but wasn't able to find any good source of information on these.
Thank you.

答: modelform_factory is a method to create forms in views , without defining form in forms.py file.</p>


问:
Can we spawn more containers from existing one in a pod?
I am having Kubernetes pod on a machine and want to have empty pod where on run time pod should be able to add/remove the containers but seems like pod always starts with something called init_container, so can this init_container spawn more containers?</p>

答:
This isn't possible.  At an API level, the containers in a PodSpec cannot be updated once the pod has been created.

For this sort of setup the pattern I've found more useful is to set up a job queue like RabbitMQ, and then set up some number of workers that can read from that queue and do individual jobs.  In Kubernetes land, the workers can be a simple Deployment and you can then control the number of workers with kubectl scale.


问:
Why are some Specflow feature files generated with a 1 in the name
When generating feature.cs files with either the Visual Studio "Regenerate Feature Files" option or "Run Custom Tool" on the file itself, a file with a "1" is generated, but only for some files.

I'd like to know what makes these files special.

Then if I generate files with the Specflow generateall command prompt, the same files that generated with a "1" are generated next to the feature file, not "under" it. These tests cannot be found in Test Explorer. As you can see in the image below, some tests generate OK.

Please note I deleted all feature.cs files between generation. It is not adding the 1 because a .feature.cs file already exists.

答:
I thought I would post my solution on how I removed the "1" from the generated filename, in case somebody come here looking (as I did).

Delete the feature.cs file

Open the .csproj for your SpecFlow project in a editor

Find the name containing the "1" and remove the "1"

Save the .csproj file, reload project in VS and build solution

Right click on your feature file and Run Custom Tool

Your feature.cs file should now be generated without a 1 in the name

This worked for me.


问:
In Python3 with nltk how can you return true if a certain word is a verb,noun.etc
I need for my function to return true if the first word in an input is a verb.
I tried this but it did not work(aka didn't return anything despite it being a verb), can someone show me an example of what im doing wrong. Also an example of what the correct way to do this is, Thank you!</p>

```<code>def All():
    what_person_said = input()
    what_person_said_wt = nltk.word_tokenize(what_person_said)
    result = nltk.pos_tag(what_person_said_wt[0])
    if result == 'VB':
        print ("First word is a verb")
        return True
</code>```

答:
Use

```<code>nltk.word_tokenize(word)
</code>```

(Of course you need import nltk

```<code>from nltk.corpus import word_tokenize
</code>```

)

```<code>nltk.pos_tag()
</code>```

Returns 'VB' or 'VBP' etc.

Body:
I need for my function to return true if the first word in an input is a verb.
I tried this but it did not work(aka didn't return anything despite it being a verb), can someone show me an example of what im doing wrong. Also an example of what the correct way to do this is, Thank you!

def All():
    what_person_said = input()
    what_person_said_wt = nltk.word_tokenize(what_person_said)
    result = nltk.pos_tag(what_person_said_wt[0])
    if result == 'VB':
        print ("First word is a verb")
        return True

Body:
Use

nltk.word_tokenize(word)

(Of course you need import nltk

from nltk.corpus import word_tokenize

)

nltk.pos_tag()

Returns 'VB' or 'VBP' etc.


问:
How can I include a header file that contains `>` in its name?
This is quite a contrived problem, I admit, but here it is.

Suppose you have a file with the > character in its name. This is possible on most Unix systems afaik:

```<code>$ touch 'weird>name'
$ ls -l
-rw-r--r--  1 user  user   0 28 Mag 11:05 weird>name
</code>```

Now, suppose this file contains C/C++ code and you want to include it as an header:

```<code>#include <weird>name>

int main() {
  return weird_function();
}
</code>```

Clang gives me the following error:

```<code>test.cpp:1:10: fatal error: 'weird' file not found
#include <weird>name>
</code>```

Of course, since the preprocessor parses the directive up to the first > and looks for the weird file. But, I wonder if some escaping mechanism exists to allow me to include the right file.

So, in C and/or C++, is there a way to include an header file which has the > character in its name?

Edit: Many suggested me why not to use #include "weird>name". I admit that my mind slipped over the quotes syntax while writing the question, but it remains valid because the two syntaxes may ask the compiler to search in different paths (theoretically at least). So is there any escaping mechanism to let me include weird>name using the #include <> syntax?

答:
Try below syntax:</p>

```<code>#include "weird>name"
</code>```

Body:
This is quite a contrived problem, I admit, but here it is.

Suppose you have a file with the > character in its name. This is possible on most Unix systems afaik:

$ touch 'weird>name'
$ ls -l
-rw-r--r--  1 user  user   0 28 Mag 11:05 weird>name

Now, suppose this file contains C/C++ code and you want to include it as an header:

#include <weird>name>

int main() {
  return weird_function();
}

Clang gives me the following error:

test.cpp:1:10: fatal error: 'weird' file not found
#include <weird>name>

Of course, since the preprocessor parses the directive up to the first > and looks for the weird file. But, I wonder if some escaping mechanism exists to allow me to include the right file.

So, in C and/or C++, is there a way to include an header file which has the > character in its name?

Edit: Many suggested me why not to use #include "weird>name". I admit that my mind slipped over the quotes syntax while writing the question, but it remains valid because the two syntaxes may ask the compiler to search in different paths (theoretically at least). So is there any escaping mechanism to let me include weird>name using the #include <> syntax?

Body:
Try below syntax:

#include "weird>name"


问:
GoogleSignInResult isSuccess failed
I want to use the Google Login for my App, but I always get the message Status{statusCode=unknown status code: 12500, resolution=null and the login failed. Has anyone an idea what the problem is?

Here is my Activity:

```<code>public class GruppenActivity extends AppCompatActivity implements
    GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener {

    private static final String TAG = "SignInActivity";
    private static final int RC_SIGN_IN = 9001;

    private GoogleApiClient mGoogleApiClient;
    private TextView mStatusTextView;
    private ProgressDialog mProgressDialog;

    private LernAppDB db;
    private SQLiteDatabase sqlDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gruppen);

        // Views
        mStatusTextView = (TextView) findViewById(R.id.status);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

        db = new LernAppDB(this);
        sqlDatabase = db.getReadableDatabase();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.server_client_id))
            .requestServerAuthCode(getString(R.string.server_client_id))
            .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this , this )
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

        SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setScopes(gso.getScopeArray());

    }

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {

            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            String personName = acct.getDisplayName();
            String personEmail = acct.getEmail();
            ZentraleDB zentraleDB = new ZentraleDB();
            ZentraleDB.benutzerAnlegen(sqlDatabase,personEmail,"hans","wilhelm",personName,"tesr");
            mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
            updateUI(true);
        } else {
            updateUI(false);
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    // [START_EXCLUDE]
                    updateUI(false);
                    // [END_EXCLUDE]
                }
            });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    updateUI(false);
                }
            });
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void updateUI(boolean signedIn) {
        if (signedIn) {
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {
            mStatusTextView.setText(R.string.signed_out);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }
}
</code>```

答:
Few things to check:

1. Check your correct SHA certificate fingerprints in Firebase Console.

2. Check below warning in Google API Console.

If you see that error, You need to choose Support email in OAuth consent screen tab like an example below.

After chosen a support email, the warning disappeared. and it started working.

Title: GoogleSignInResult isSuccess failed

Body:
I want to use the Google Login for my App, but I always get the message Status{statusCode=unknown status code: 12500, resolution=null and the login failed. Has anyone an idea what the problem is?

Here is my Activity:

public class GruppenActivity extends AppCompatActivity implements
    GoogleApiClient.OnConnectionFailedListener,
    View.OnClickListener {

    private static final String TAG = "SignInActivity";
    private static final int RC_SIGN_IN = 9001;

    private GoogleApiClient mGoogleApiClient;
    private TextView mStatusTextView;
    private ProgressDialog mProgressDialog;

    private LernAppDB db;
    private SQLiteDatabase sqlDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gruppen);

        // Views
        mStatusTextView = (TextView) findViewById(R.id.status);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

        db = new LernAppDB(this);
        sqlDatabase = db.getReadableDatabase();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestIdToken(getString(R.string.server_client_id))
            .requestServerAuthCode(getString(R.string.server_client_id))
            .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this , this )
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

        SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setScopes(gso.getScopeArray());

    }

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {

            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            String personName = acct.getDisplayName();
            String personEmail = acct.getEmail();
            ZentraleDB zentraleDB = new ZentraleDB();
            ZentraleDB.benutzerAnlegen(sqlDatabase,personEmail,"hans","wilhelm",personName,"tesr");
            mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
            updateUI(true);
        } else {
            updateUI(false);
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    // [START_EXCLUDE]
                    updateUI(false);
                    // [END_EXCLUDE]
                }
            });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    updateUI(false);
                }
            });
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void updateUI(boolean signedIn) {
        if (signedIn) {
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {
            mStatusTextView.setText(R.string.signed_out);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }
}