问:
How do I use a certain version (or higher) of a perl module in my perl script?
I'm using Term::ANSIColor in my Perl script to do colorization of terminal output, and I am using the colorstrip function, which was only added in Term::ANSIColor version 2.01, according to the changelog. So, is there a way to make my script automatically die with an appropriate error message if it doesn't find at least that version of Term::ANSIcolor?

答:
Just:

```<code>use Term::ANSIColor 2.01;
</code>```

See perldoc -f use:

use Module VERSION LIST

If the VERSION argument is present between Module and LIST, then the use will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable $Module::VERSION .

Body:
Just:

use Term::ANSIColor 2.01;

See perldoc -f use:

use Module VERSION LIST

If the VERSION argument is present between Module and LIST, then the use will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable $Module::VERSION .


来源: stackexchange

问:
Where are jupyter nbextension settings saved, physically? And where are changes to jupyter notebook keyboard shortcuts saved, physically?
I want to sync my settings for jupyter notebooks across systems with a dotfiles Github repo, but I'm not sure where they are stored. Couldn't find the solution anywhere else.

答:
Figured this out myself. Turns out you can find out by entering

```<code>jupyter nbextensions list
</code>```

and at the top there should be a line that looks like config dir:/Users/<user>/.jupyter/nbconfig.

The settings for your changed key mappings and your nbextension plugins are all contained in the json file nbconfig/notebook.json. Just sync this across systems and your settings will go with you!

ContentLicense: CC BY-SA 3.0

Body:
Figured this out myself. Turns out you can find out by entering

jupyter nbextensions list

and at the top there should be a line that looks like config dir:/Users/<user>/.jupyter/nbconfig.

The settings for your changed key mappings and your nbextension plugins are all contained in the json file nbconfig/notebook.json. Just sync this across systems and your settings will go with you!


问:
Coq: Inequality test
There's a simple construct for conditional branching w/ an equality test in Coq:

```<code>Check ltac:(tryif unify 1 (S 0) then idtac "success" else idtac "fail"). (*success...*)
</code>```

Is there a similar way to test < and/or <=?

答:
Maybe you can use the leb and ltb functions from the standard library (they have notations <=? and <?).

```<code>Require Import Arith.

Check ltac:(match (eval cbv in (2 <? 5)) with
            | true =>  idtac "success"
            | false => idtac "fail" end).
</code>```

Of course, this will fail in cases where the evaluation of the function gets stuck on a variable, e.g. if you have x in the context it will work to see that 3 < 5 and 1 < S (S x), but not for S x < S (S x).

Title: Coq: Inequality test

Body:
There's a simple construct for conditional branching w/ an equality test in Coq:

Check ltac:(tryif unify 1 (S 0) then idtac "success" else idtac "fail"). (*success...*)

Is there a similar way to test < and/or <=?

Body:
Maybe you can use the leb and ltb functions from the standard library (they have notations <=? and <?).

Require Import Arith.

Check ltac:(match (eval cbv in (2 <? 5)) with
            | true =>  idtac "success"
            | false => idtac "fail" end).

Of course, this will fail in cases where the evaluation of the function gets stuck on a variable, e.g. if you have x in the context it will work to see that 3 < 5 and 1 < S (S x), but not for S x < S (S x).


问:
How decode windowsCP1251 percent encoded String ? Swift 4 ios 11
How to decode String from percent encoded windowsCP1251?

replacingPercentEscapes(using: String.Encoding.windowsCP1251) now is obsolete

removingPercentEncoding uses utf8

答:
A little example which is expected to work with multi-byte string encodings.

```<code>extension UInt8 {
    //returns 0...15 when '0'...'9', 'A'...'F', 'a'...'f', otherwise returns nil
    var hexValue: UInt8? {
        if UInt8(ascii: "0") <= self && self <= UInt8(ascii: "9") {
            return self - UInt8(ascii: "0")
        } else if UInt8(ascii: "A") <= self && self <= UInt8(ascii: "F") {
            return self - UInt8(ascii: "A") + 10
        } else if UInt8(ascii: "a") <= self && self <= UInt8(ascii: "f") {
            return self - UInt8(ascii: "a") + 10
        } else {
            return nil
        }
    }
}

extension String {
    func removingPercentEncoding(using encoding: String.Encoding) -> String? {
        guard let percentEncodedData = self.data(using: encoding) else {return nil}
        var byteIterator = percentEncodedData.makeIterator()
        var percentDecodedData = Data()
        while let b0 = byteIterator.next() {
            guard b0 == UInt8(ascii: "%"), let b1 = byteIterator.next() else {
                //Non percent character
                percentDecodedData.append(b0)
                continue
            }
            guard let h1 = b1.hexValue, let b2 = byteIterator.next() else {
                //Keep it as is, when invalid hex-sequece appeared
                percentDecodedData.append(b0)
                percentDecodedData.append(b1)
                continue
            }
            guard let h2 = b2.hexValue else {
                //Keep it as is, when invalid hex-sequece appeared
                percentDecodedData.append(b0)
                percentDecodedData.append(b1)
                percentDecodedData.append(b2)
                continue
            }
            percentDecodedData.append((h1<<4) + h2)
        }
        return String(data: percentDecodedData, encoding: encoding)
    }
}
</code>```

In my opinion, you should think non-UTF8 percent encoding now is obsolete, and should fix the part which is generating the percent encoded string with CP1251.

Body:
A little example which is expected to work with multi-byte string encodings.

extension UInt8 {
    //returns 0...15 when '0'...'9', 'A'...'F', 'a'...'f', otherwise returns nil
    var hexValue: UInt8? {
        if UInt8(ascii: "0") <= self && self <= UInt8(ascii: "9") {
            return self - UInt8(ascii: "0")
        } else if UInt8(ascii: "A") <= self && self <= UInt8(ascii: "F") {
            return self - UInt8(ascii: "A") + 10
        } else if UInt8(ascii: "a") <= self && self <= UInt8(ascii: "f") {
            return self - UInt8(ascii: "a") + 10
        } else {
            return nil
        }
    }
}

extension String {
    func removingPercentEncoding(using encoding: String.Encoding) -> String? {
        guard let percentEncodedData = self.data(using: encoding) else {return nil}
        var byteIterator = percentEncodedData.makeIterator()
        var percentDecodedData = Data()
        while let b0 = byteIterator.next() {
            guard b0 == UInt8(ascii: "%"), let b1 = byteIterator.next() else {
                //Non percent character
                percentDecodedData.append(b0)
                continue
            }
            guard let h1 = b1.hexValue, let b2 = byteIterator.next() else {
                //Keep it as is, when invalid hex-sequece appeared
                percentDecodedData.append(b0)
                percentDecodedData.append(b1)
                continue
            }
            guard let h2 = b2.hexValue else {
                //Keep it as is, when invalid hex-sequece appeared
                percentDecodedData.append(b0)
                percentDecodedData.append(b1)
                percentDecodedData.append(b2)
                continue
            }
            percentDecodedData.append((h1<<4) + h2)
        }
        return String(data: percentDecodedData, encoding: encoding)
    }
}

In my opinion, you should think non-UTF8 percent encoding now is obsolete, and should fix the part which is generating the percent encoded string with CP1251.


问:
"Sources directory is already netbeans project" error when opening a project from existing sources
I've installed NetBeans 6.9.1 and installed few updates for it.

Then I've created a new project from existing sources. After a few changes I've closed it. And now I am having an error, when trying to open a new project from existing sources (the same files):

Sources directory is already netbeans project (maybe only in memory).

After Googling it, I noticed it happened not only with me. But I didn't find the correct solution. I've tried to restart the IDE, I've tried to restart the PC, I've tried to reinstall NetBeans. Nothing helped.

答:
I faced the same issue:

Sources directory is already NetBeans project (maybe only in memory).

The solution is:

Netbeans creates a folder in your project named "nbproject". Once you
  delete that, restart the IDE and you're good to go.


问:
Multiple images not inserted into mysql database
I am unable to insert multiple images into  database. When I am inserting the images, only one image is inserted. not all inserted. I have shown here the form with php insert code.I have not found where the problem is. Plz help.

```<code>$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class=\"pip\">" +
            "<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
            "<br/><span class=\"remove\">Remove image</span>" +
            "</span>").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});

input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Upload your images</h3>
  <input type="file" id="files" name="files[]" multiple /><br>
  <input type="submit" name="submit" value="Submit">
</div>
</code>```

This is php code:

```<code><?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);
                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                    echo "error". mysqli_error($connection);
                } else {
                    $_SESSION['s']="Images successfully saved";
                    header('location:posting_ad_image.php');
                }
            }
        }
    }
 }
?>
</code>```

I am able to upload only the last image that is uploaded last. All images are not inserted into phpmyadmin database.

答:
As already noted your loop was hitting the redirect on the first iteration and then sending you off before all the images could be saved and logged. The use of prepared statements can be done in such a way that you do the preparation and binding of variables just once but execute many times until the statement is closed.

```<code><?php

    if( isset( $_POST['submit'],$_FILES['files'] ) ) {

        $uploaded=array();

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        /* prepare the sql statement before the loop */
        $sql = 'INSERT INTO `image` SET `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $statement = $connection->prepare( $sql );
        if( $statement ){

            /* if the statement was prepared successfully, bind the variables that will be used later */
            $statement->bind_param('sss', $n_array, $type_array, $size_array );

            /* iterate through the images, store the image and log to db */
            foreach( $tmp_name_arrays as $index => $val ){

                $n_array = $n_arrays[ $index ];
                $tmp_name_array = $tmp_name_arrays[ $index ];
                $type_array = $type_arrays[ $index ];
                $size_array = $size_arrays[ $index ];

                if( is_uploaded_file( $tmp_name_array ) ){
                    $bytes = move_uploaded_file( $tmp_name_array, "ad/data/img/".$n_array );
                    if( $bytes ){
                        $status = $statement->execute();
                        $uploaded[]=$status && $bytes ? $n_array : false;
                    }
                }
            }
            /* close the statement and db connection */
            $statement->close();
            $connection->close();

            /* remove empty entries from array - if any */
            $uploaded=array_filter( $uploaded );

            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>
</code>```

Ok - The following was done as a full, end-to-end test and works ok ~ you will need to edit the $dir variable to suit

```<code><?php

    $dbhost =   'localhost';
    $dbuser =   'root';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $connection =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    $dir='c:/temp/fileuploads/1/';

    if( isset( $_POST['submit'], $_FILES['files'] ) ) {

        $uploaded=array();

        $sql = 'insert into `image` set `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $stmt = $connection->prepare( $sql );

        if( $stmt ){

            $stmt->bind_param( 'sss', $name, $type, $size );

            foreach( $_FILES['files']['name'] as $i => $name ) {
                if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {

                    $name = $_FILES['files']['name'][$i];
                    $size = $_FILES['files']['size'][$i];
                    $type = $_FILES['files']['type'][$i];
                    $tmp  = $_FILES['files']['tmp_name'][$i];

                    if( is_uploaded_file( $tmp ) ){
                        $bytes = move_uploaded_file( $tmp, $dir.$name );
                        if( $bytes ){
                            $status = $stmt->execute();
                            $uploaded[]=$status && $bytes ? $name : false;
                        }
                    }
                }
            }
            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>
<!doctype html>
<html>
    <head><title>Multiple file upload</title></head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            <input type='file' name='files[]' multiple />
            <input type='submit' name='submit' value='Upload & save' />
        </form>
    </body>
</html>
</code>```

Snippet from db after running and uploading a few images at once

```<code>mysql> describe image;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| img_name | longblob    | YES  |     | NULL    |       |
| img_type | varchar(50) | YES  |     | NULL    |       |
| img_size | int(11)     | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

mysql> select * from image;
+-------------------------------------+------------+----------+
| img_name                            | img_type   | img_size |
+-------------------------------------+------------+----------+
| tumblr_ook8swcsSt1tp499co1_1280.jpg | image/jpeg |    81124 |
| tumblr_ook8ukfiTY1tp499co1_1280.jpg | image/jpeg |   201061 |
| tumblr_ook8veeLgq1tp499co1_1280.jpg | image/jpeg |    63477 |
| tumblr_oomaozErOP1tp499co1_1280.jpg | image/jpeg |   283062 |
| tumblr_oomapxb8NJ1tp499co1_1280.jpg | image/jpeg |   577475 |
| tumblr_oomaqzKzlw1tp499co1_1280.jpg | image/jpeg |   382917 |
+-------------------------------------+------------+----------+
</code>```

Body:
I am unable to insert multiple images into  database. When I am inserting the images, only one image is inserted. not all inserted. I have shown here the form with php insert code.I have not found where the problem is. Plz help.

$(document).ready(function() {
  if (window.File && window.FileList && window.FileReader) {
    $("#files").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("" +
            "" +
            "
Remove image" +
            "").insertAfter("#files");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
  } else {
    alert("Your browser doesn't support to File API")
  }
});

input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}

Upload your images

  <input type="file" id="files" name="files[]" multiple />

  <input type="submit" name="submit" value="Submit">

This is php code:

<?php
   if(isset($_POST['submit']))
      {
      if(isset($_FILES['files']))
         {

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        foreach ($tmp_name_arrays as $index => $val)
        {
            $n_array = $n_arrays[$index];
            $tmp_name_array = $tmp_name_arrays[$index];
            $type_array = $type_arrays[$index];
            $size_array = $size_arrays[$index];

            if(move_uploaded_file($tmp_name_array, "ad/data/img/".$n_array))
            {
                $sql = 'INSERT INTO `image`
                        SET `img_name` = ?, `img_type` = ?, `img_size` = ?';

                // Prepare the SQL statement for execution.
                $statement = $connection->prepare($sql);
                $bound = $statement->bind_param('sss', $n_array, $type_array, $size_array);

                // Execute the prepared statement.
                $executed2 = $statement->execute();

                if(!$executed2){
                    echo "error". mysqli_error($connection);
                } else {
                    $_SESSION['s']="Images successfully saved";
                    header('location:posting_ad_image.php');
                }
            }
        }
    }
 }
?>

I am able to upload only the last image that is uploaded last. All images are not inserted into phpmyadmin database.

Body:
As already noted your loop was hitting the redirect on the first iteration and then sending you off before all the images could be saved and logged. The use of prepared statements can be done in such a way that you do the preparation and binding of variables just once but execute many times until the statement is closed.

<?php

    if( isset( $_POST['submit'],$_FILES['files'] ) ) {

        $uploaded=array();

        $n_arrays = $_FILES['files']['name'];
        $tmp_name_arrays = $_FILES['files']['tmp_name'];
        $type_arrays = $_FILES['files']['type'];
        $size_arrays = $_FILES['files']['size'];

        /* prepare the sql statement before the loop */
        $sql = 'INSERT INTO `image` SET `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $statement = $connection->prepare( $sql );
        if( $statement ){

            /* if the statement was prepared successfully, bind the variables that will be used later */
            $statement->bind_param('sss', $n_array, $type_array, $size_array );

            /* iterate through the images, store the image and log to db */
            foreach( $tmp_name_arrays as $index => $val ){

                $n_array = $n_arrays[ $index ];
                $tmp_name_array = $tmp_name_arrays[ $index ];
                $type_array = $type_arrays[ $index ];
                $size_array = $size_arrays[ $index ];

                if( is_uploaded_file( $tmp_name_array ) ){
                    $bytes = move_uploaded_file( $tmp_name_array, "ad/data/img/".$n_array );
                    if( $bytes ){
                        $status = $statement->execute();
                        $uploaded[]=$status && $bytes ? $n_array : false;
                    }
                }
            }
            /* close the statement and db connection */
            $statement->close();
            $connection->close();

            /* remove empty entries from array - if any */
            $uploaded=array_filter( $uploaded );

            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>

Ok - The following was done as a full, end-to-end test and works ok ~ you will need to edit the $dir variable to suit

<?php

    $dbhost =   'localhost';
    $dbuser =   'root';
    $dbpwd  =   'xxx';
    $dbname =   'xxx';
    $connection =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    $dir='c:/temp/fileuploads/1/';

    if( isset( $_POST['submit'], $_FILES['files'] ) ) {

        $uploaded=array();

        $sql = 'insert into `image` set `img_name` = ?, `img_type` = ?, `img_size` = ?';
        $stmt = $connection->prepare( $sql );

        if( $stmt ){

            $stmt->bind_param( 'sss', $name, $type, $size );

            foreach( $_FILES['files']['name'] as $i => $name ) {
                if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {

                    $name = $_FILES['files']['name'][$i];
                    $size = $_FILES['files']['size'][$i];
                    $type = $_FILES['files']['type'][$i];
                    $tmp  = $_FILES['files']['tmp_name'][$i];

                    if( is_uploaded_file( $tmp ) ){
                        $bytes = move_uploaded_file( $tmp, $dir.$name );
                        if( $bytes ){
                            $status = $stmt->execute();
                            $uploaded[]=$status && $bytes ? $name : false;
                        }
                    }
                }
            }
            if( !empty( $uploaded ) ){
                $_SESSION['s']=sprintf("%d Images successfully saved", count( $uploaded )-1 );
                header('Location: posting_ad_image.php');
            }
        }
    }
?>
<!doctype html>
<html>
    <head><title>Multiple file upload</title></head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            <input type='file' name='files[]' multiple />
            <input type='submit' name='submit' value='Upload & save' />
        </form>
    </body>
</html>

Snippet from db after running and uploading a few images at once

mysql> describe image;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| img_name | longblob    | YES  |     | NULL    |       |
| img_type | varchar(50) | YES  |     | NULL    |       |
| img_size | int(11)     | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

mysql> select * from image;
+-------------------------------------+------------+----------+
| img_name                            | img_type   | img_size |
+-------------------------------------+------------+----------+
| tumblr_ook8swcsSt1tp499co1_1280.jpg | image/jpeg |    81124 |
| tumblr_ook8ukfiTY1tp499co1_1280.jpg | image/jpeg |   201061 |
| tumblr_ook8veeLgq1tp499co1_1280.jpg | image/jpeg |    63477 |
| tumblr_oomaozErOP1tp499co1_1280.jpg | image/jpeg |   283062 |
| tumblr_oomapxb8NJ1tp499co1_1280.jpg | image/jpeg |   577475 |
| tumblr_oomaqzKzlw1tp499co1_1280.jpg | image/jpeg |   382917 |
+-------------------------------------+------------+----------+


问:
PHP url recognition
How can you check if text typed in from a user is an url?

Lets say I want to check if the text is a url and then check if the string has "youtube.com" in it.  Afterwards, I want to get the portion of the link which is of interest for me between the substrings "watch?v=" and any "&" parameters if they do exist.

答:
Its strongly recommended not to use parse_url() for url validation.
here is a nice solution.</p>

ContentLicense: CC BY-SA 2.5

Title: PHP url recognition


问:
"Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected"
I have two table in my database which are user and the attendance table. What I want to do now is I want to show the attendance data from database according to the user in their attendance view which is linked with their profile. This is my attendance function in the userController.

```<code> public function attendance($id)
    {
        $user = UserProfile::findOrFail($id);
        $this->authorize('modifyUser', $user);

        return view ('user.attendance', ['user'=>$user]);
    }
</code>```

This is my route to attendance view.

```<code>Route::get('/attendance/', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);
</code>```

This is my attendance view.

```<code>@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1><i class="fa fa-university"></i> Attendance</h1>
            </div>

            <div class="row">
                <table class="table table-bordered">
                    <tr>
                        <th>No</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>Present</th>
                    </tr>

                    <?php $no=1; ?>

                    <tr>
                        <td>{{ $no++ }}</td>
                        <td>{{$user->attendance->date}}</td>
                        <td>{{$user->attendance->time}}</td>
                        <td>{{$user->attendance->present}}</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
@stop
</code>```

This is the error that i got.
Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected".
I am new to laravel.

答:
You're getting this error because attendance() method expects an ID and you don't pass it. Change the route to:

```<code>Route::get('attendance/{id}', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);
</code>```

And pass an ID when creating a link to the attendance() method:

```<code>{{ route('user.attendance', ['id' => 1]) }}
</code>```

Or:

```<code>{{ url('attendance/1') }}
</code>```

If you want to get ID of currently logged in user, do not pass ID. Use auth()-user() instead:

```<code>public function attendance()
{
    $this->authorize('modifyUser', auth()->user());

    return view ('user.attendance');
}
</code>```

Body:
I have two table in my database which are user and the attendance table. What I want to do now is I want to show the attendance data from database according to the user in their attendance view which is linked with their profile. This is my attendance function in the userController.

 public function attendance($id)
    {
        $user = UserProfile::findOrFail($id);
        $this->authorize('modifyUser', $user);

        return view ('user.attendance', ['user'=>$user]);
    }

This is my route to attendance view.

Route::get('/attendance/', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);

This is my attendance view.

@extends('layouts.app')
@section('content')

 Attendance

                        No
                        Date
                        Time
                        Present

                    <?php $no=1; ?>

                        {{ $no++ }}
                        {{$user->attendance->date}}
                        {{$user->attendance->time}}
                        {{$user->attendance->present}}

@stop

This is the error that i got.
Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected".
I am new to laravel.

Body:
You're getting this error because attendance() method expects an ID and you don't pass it. Change the route to:

Route::get('attendance/{id}', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);

And pass an ID when creating a link to the attendance() method:

{{ route('user.attendance', ['id' => 1]) }}

Or:

{{ url('attendance/1') }}

If you want to get ID of currently logged in user, do not pass ID. Use auth()-user() instead:

public function attendance()
{
    $this->authorize('modifyUser', auth()->user());

    return view ('user.attendance');
}


问:
Database wiped after testing in Laravel
I'm new at Testing, so I was following a tutorial. The Database setting I set into like this:

```<code>'sqlite' => [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ],
</code>```

and in the phpunit.xml I made configuration like this:

```<code><php>
        <env name="APP_ENV" value="testing"/>
        <env name="DATABASE_CONNECTION" value="sqlite"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</code>```

I'm not sure what's going on, the database seed that I created using factory is always missing and the database tables either, left only with a migration table.

so what happened and how can I fix it?

答:
I was going to post it as a comment but due to lack of reputation I was not able to do so.

Things you can try to solve your current problem:-

Check your .env file. The database configuration must be appropriate to join the connection.

Check the laravel.log file in order to view the error generated during your testing.

Check your migration file and seeder file.

As you said in the question that neither data is seeded nor tables are found, clearly hints regarding error in database configuration or migration file.

Hope this helps.

Edit:- you can try a workaround for this. In your config/databae.php below mysql add:-

```<code> 'mysql_testing' => [
        'driver'    => 'mysql',
        'host'      => env('TESTING_DB_HOST', 'localhost'),
        'database'  => env('TESTING_DB_DATABASE', 'forge'),
        'username'  => env('TESTING_DB_USERNAME', 'forge'),
        'password'  => env('TESTING_DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
</code>```

And now you must entry the details in your .env file:-

```<code>TESTING_DB_HOST=localhost
TESTING_DB_DATABASE=homestead_testing
TESTING_DB_USERNAME=homestead
TESTING_DB_PASSWORD=secret
</code>```

Note:- While migration use the following migration command only during the testing purpose.

php artisan migrate --database=mysql_testing

Its for mysql testing database but you can likewise do for sqlite also.

Title: Database wiped after testing in Laravel

Body:
I'm new at Testing, so I was following a tutorial. The Database setting I set into like this:

'sqlite' => [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ],

and in the phpunit.xml I made configuration like this:

<php>
        <env name="APP_ENV" value="testing"/>
        <env name="DATABASE_CONNECTION" value="sqlite"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>

I'm not sure what's going on, the database seed that I created using factory is always missing and the database tables either, left only with a migration table.

so what happened and how can I fix it?

Body:
I was going to post it as a comment but due to lack of reputation I was not able to do so.

Things you can try to solve your current problem:-

Check your .env file. The database configuration must be appropriate to join the connection.

Check the laravel.log file in order to view the error generated during your testing.

Check your migration file and seeder file.

As you said in the question that neither data is seeded nor tables are found, clearly hints regarding error in database configuration or migration file.

Hope this helps.

Edit:- you can try a workaround for this. In your config/databae.php below mysql add:-

 'mysql_testing' => [
        'driver'    => 'mysql',
        'host'      => env('TESTING_DB_HOST', 'localhost'),
        'database'  => env('TESTING_DB_DATABASE', 'forge'),
        'username'  => env('TESTING_DB_USERNAME', 'forge'),
        'password'  => env('TESTING_DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

And now you must entry the details in your .env file:-

TESTING_DB_HOST=localhost
TESTING_DB_DATABASE=homestead_testing
TESTING_DB_USERNAME=homestead
TESTING_DB_PASSWORD=secret

Note:- While migration use the following migration command only during the testing purpose.

php artisan migrate --database=mysql_testing

Its for mysql testing database but you can likewise do for sqlite also.


问:
Cant connect to jupyter localhost for python
I am trying to solve this problem for days when i try this is the error that i am getting :
This site can’t be reached

localhost refused to connect.
Search Google for localhost 8888
ERR_CONNECTION_REFUSED
please help i have try everything

答: Make sure you have launched jupyter notebook from the command line within the terminal. and then it should automatically bring up jupyter notebooks within whatever is your default browser. If not try inputting http://localhost:8889/tree into your search bar. Please let me know if you need any more clarification or help!</p>


问:
Mobile app - Store and version relatively static json files on the backend
I have a mobile app that reads data from a few json files. The app does not modify the data in any way. The data is mostly static but there might be changes (addition/deletion/updates) every few days (5-6 days). These files are around 300-400KB in size.

I want to figure out a good way to store this data in the backend so I do not have to push app updates every time I have to update the static data. I am thinking of versioning the json files on the backend so the client can check if it has the latest version and then download the new file if there's an update.

On the client, I just read the static json into memory. Will that be an issue if the size grows bigger? Should I look into an alternative approach like storing the JSON in a realm DB?

Is there a better approach to sync such static data between the server and the client?

答: You're on the right path about wanting to "check the version" of the json file, since 400kb is not an insignificant size to download every time. There are multiple ways to do this, the simplest may be via exposing an endpoint from your backend that contains the Last Modified date of the json file, and storing a Last Updated date somewhere in your app via SharedPreferences, and only fetching the json file when these values don't match.</p>


问:
Use sed or awk to remove lines not adjacent to pattern in bash

I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC
</code>```

I tried using awk to help reveal the issue:

```<code>awk '{/fasta/?f++:f=0} f==2' R3.fasta
</code>```

This returns:

```<code>sample3.fasta
sample10.fasta
</code>```

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

```<code>sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC
</code>```

Where the lines not flaking the ">" symbol have been removed

答:
With sed</p>

```<code>sed ':A;/fasta$/!d;N;/\n>/!{s/.*\n//;bA};N' infile

sed '
:A              # label for jump
/fasta$/!d      # if the line end with fasta not delete
N               # add the next line in the pattern space
/\n>/!{         # if this new line don'\''t start with >
s/.*\n//        # delete it
bA}             # and jump to A
N               # else get the next line and print
' infile
</code>```

Body:
I need to delete any line that is not surrounding a ">" symbol.

Here is some sample data:

sample1.fasta
>R00003
ATCATACTACTACG
sample2.fasta
sample3.fasta
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample9.fasta
sample10.fasta
>R00003
AGCATCTCAGTC

I tried using awk to help reveal the issue:

awk '{/fasta/?f++:f=0} f==2' R3.fasta

This returns:

sample3.fasta
sample10.fasta

This is diagnostic in that it shows where duplicates are present. However, I want to remove the lines that are not flanking the ">" symbol on either side. This does not remove them and only displays the second.

The result I expect is:

sample1.fasta
>R00003
ATCATACTACTACG
sample4.fasta
>R00003
ATACTACGTA
sample7.fasta
>R00003
ATGCATCAT
sample8.fasta
>R00003
AATCATCGACCT
sample10.fasta
>R0003
AGCATCTCAGTC

Where the lines not flaking the ">" symbol have been removed

Body:
With sed

sed ':A;/fasta$/!d;N;/\n>/!{s/.*\n//;bA};N' infile

sed '
:A              # label for jump
/fasta$/!d      # if the line end with fasta not delete
N               # add the next line in the pattern space
/\n>/!{         # if this new line don'\''t start with >
s/.*\n//        # delete it
bA}             # and jump to A
N               # else get the next line and print
' infile


问:
Understanding Pass-By-Value-Result
Consider the following program

```<code>int i;
int a[2];
void foo(int x, int y)
{
    x++;
    i++;
    y++;
}

main()
{
    a[0] = 1;
    a[1] = 1;
    i = 0;
    foo(a[i], a[i]);
    print(a[0]);
    print(a[1]);
}
</code>```

I'm trying very hard to understand pass-by-value-result. However couldn't get the hang of it. I know it's similar to pass-by-reference. But in what way? How does the results differ in the above case? When does it actually use the "reference" of the values?

答:
Probably in your posted code, you wanted "foo(a[i], a[i]);" instead of "p(a[i], a[i]);".

Anyway, your a[0] and a[1] will stay set at 1, because foo() gets arguments by value, and there is no way for foo() to change its arguments in a manner visible to the outside.

Passing by value and passing by reference are similar only because both execute a "passing". Passing by value involves a duplication of the data: foo() receives a copy of a[0] and a copy of a[1]; and foo() calls them x and y. Then foo() increments both, but x and y are copies only visible to foo(), so nothing happens in reality because x and y are no more used after the increment.

Inside foo() there is an increment of the variable i, which is global. This time instead, the variable gets really modified, and the change is visible to everybody.

Passing by reference is different in the sense that foo() would receive an address (the reference) of a variable, and foo() would be able to read but also write "in" that reference, thus modifying the object living there.

Think about this example. I am the main() and you are the foo(). I have a sheet of paper with something written in it, say the title of a song. I can let you know the name of the song by taking another sheet, copying onto it the name, and giving the new sheet to you. This is passing by value.

Different would be if I said to you: "the sheet is on the table" (the table is the location of the data, the "reference"). You go there, look at the sheet, so you know the title of the song. But you could also modify my sheet that lies on the table. This is passing by reference: I tell you where the data is. Of course, to be precise, the way I say to you where the sheet is, is accomplished by taking another sheet and writing on it "the sheet with the title is on the table", then I give you the new sheet. You, foo(), receive a sheet (passed by value), and you can also destroy or modify it, I will never notice. But before modifying this new sheet which will be useless soon or later, use it to look on the table and don't modify MY sheet with the name of the song on it! :-)

Title: Understanding Pass-By-Value-Result

Body:
Consider the following program

int i;
int a[2];
void foo(int x, int y)
{
    x++;
    i++;
    y++;
}

main()
{
    a[0] = 1;
    a[1] = 1;
    i = 0;
    foo(a[i], a[i]);
    print(a[0]);
    print(a[1]);
}

I'm trying very hard to understand pass-by-value-result. However couldn't get the hang of it. I know it's similar to pass-by-reference. But in what way? How does the results differ in the above case? When does it actually use the "reference" of the values?


问:
How to avoid creating unnecessary lists?
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

```<code>def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)
</code>```

As per the example above:

```<code>    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]
</code>```

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.

答:
Generator expressions

You are correct in not wanting to create multiple lists. Your list comprehension's create an entire new list, wasting memory, and you are looping over each list!

@VPfB's idea of using gererators is a good solution if you have other places in your code to reuse the generators. If you don't have a need to reuse generators use, generator expressions.

Generator expressions are lazy, like generators, so when chained together, as here, the loop will evaluate once at the end, when writelines is called.

```<code>def insight_pull(file):
    with open(file) as in_f:
        dirty = (line.split('    ') for line in in_f)    # Combine with next
        clean = (i[1] for i in dirty)
        cleaner = (pair for pair in zip(clean,clean))    # Redundantly silly
        cleanest = (i[0].split() + i[1].split() for i in cleaner)

        # Don't build a single (possibily huge) string with join
        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)
</code>```

Leaving the above as it directly matches your question, You can go further:

```<code>def insight_pull(file):
    with open(file) as in_f:
        clean = (line.split('    ')[0] for line in in_f)
        cleaner = zip(clean,clean)
        cleanest = (i[0].split() + i[1].split() for i in cleaner)

        with open("Output_File.txt", "w") as out_f:
            for line in cleanest:
                out_f.write(line + '\n')
</code>```

Body:
I keep coming across situations where I pull some information from a file or wherever, then have to massage the data to the final desired form through several steps. For example:

def insight_pull(file):
    with open(file) as in_f:
        lines = in_f.readlines()

        dirty = [line.split('    ') for line in lines]
        clean = [i[1] for i in dirty]
        cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]
        cleanest = [i[0].split() + i[1].split() for i in cleaner]

        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)

As per the example above:

    # Pull raw data from file splitting on '   '.
    dirty = [line.split('    ') for line in lines]

    # Select every 2nd element from each nested list.
    clean = [i[1] for i in dirty]

    # Couple every 2nd element with it's predecessor into a new list.
    cleaner = [[clean[i],clean[i + 1]] for i in range(0, len(clean),2)]

    # Split each entry in cleaner into the final formatted list.
    cleanest = [i[0].split() + i[1].split() for i in cleaner]

Seeing as I can't put all of the edits into one line or loop (since each edit depends on the edit before it), is there a better way to structure code like this?

Apologies if the question is a bit vague. Any input is much appreciated.

Body:
Generator expressions

You are correct in not wanting to create multiple lists. Your list comprehension's create an entire new list, wasting memory, and you are looping over each list!

@VPfB's idea of using gererators is a good solution if you have other places in your code to reuse the generators. If you don't have a need to reuse generators use, generator expressions.

Generator expressions are lazy, like generators, so when chained together, as here, the loop will evaluate once at the end, when writelines is called.

def insight_pull(file):
    with open(file) as in_f:
        dirty = (line.split('    ') for line in in_f)    # Combine with next
        clean = (i[1] for i in dirty)
        cleaner = (pair for pair in zip(clean,clean))    # Redundantly silly
        cleanest = (i[0].split() + i[1].split() for i in cleaner)

        # Don't build a single (possibily huge) string with join
        with open("Output_File.txt", "w") as out_f:
            out_f.writelines(' '.join(i) + '\n' for i in cleanest)

Leaving the above as it directly matches your question, You can go further:

def insight_pull(file):
    with open(file) as in_f:
        clean = (line.split('    ')[0] for line in in_f)
        cleaner = zip(clean,clean)
        cleanest = (i[0].split() + i[1].split() for i in cleaner)

        with open("Output_File.txt", "w") as out_f:
            for line in cleanest:
                out_f.write(line + '\n')


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
Unless I'm misunderstanding your question, this should do the trick:

```<code>s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
for i in range(len(s)):
    if s.count(s[i]) > 1:
        return i
</code>```

This should give you the index of the first occurrence of the first element that appears multiple times in the list

If this is not what you're after, please leave a comment and I'll edit the code.

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
Unless I'm misunderstanding your question, this should do the trick:

s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
for i in range(len(s)):
    if s.count(s[i]) > 1:
        return i

This should give you the index of the first occurrence of the first element that appears multiple times in the list

If this is not what you're after, please leave a comment and I'll edit the code.


问:
Retrieving selected items from DIV - Javascript
I am able to fetch data from database and append to my panel as in my code. But the problem is on page load for instance,

答:
I see your Function changes values of sum and total_points variables, but I cant see where you use them. Also I dont see any point of doing:

```<code>   $(".line-total").each(function(){
   sum = sum + quantity*price;
   })

   $(".pts-total").each(function(){
   total_points = total_points + quantity*points;
   })
</code>```

Because when you execute it - Function(), it just changes values of sum and total_points many times. Same like:

```<code>var foo = 1;
(function() {
  foo = 2;
  foo = 3;
  foo = 4;
})();
</code>```

So it just returns foo with value of 4 and foo = 2; and foo = 3; doesn't seem to be used. So if your total_points sets value of sub-total from your table, it makes sense that it might return same values as many times you call Function

Body:
I see your Function changes values of sum and total_points variables, but I cant see where you use them. Also I dont see any point of doing:

   $(".line-total").each(function(){
   sum = sum + quantity*price;
   })

   $(".pts-total").each(function(){
   total_points = total_points + quantity*points;
   })

Because when you execute it - Function(), it just changes values of sum and total_points many times. Same like:

var foo = 1;
(function() {
  foo = 2;
  foo = 3;
  foo = 4;
})();

So it just returns foo with value of 4 and foo = 2; and foo = 3; doesn't seem to be used. So if your total_points sets value of sub-total from your table, it makes sense that it might return same values as many times you call Function


问:
disable xampp redirect http to https
I created VirtualHost at my xampp in localhost for wordpress and add this code in httpd-vhosts.conf :

```<code><VirtualHost *:80>
ServerAdmin webmaster@mysitefolder
DocumentRoot "E:/xampp/htdocs/mysitefolder"
ServerName mysitefolder
ErrorLog "logs/mysitefolder-error.log"
CustomLog "logs/mysitefolder-access.log" common
</VirtualHost>
</code>```

but when enter http://mysitefolder in browser it's aout redirect to https://mysitefolder and not load my site. how can disable https and only using http ?thank you

答: I don't have enough reputation to comment but if you are using Chrome and a .dev  local server domain, have a look at this post. Chrome have purchased the .dev gTLD and now force the redirect to https://. If so, consider using .test or some other domain. A quick way to test it would be to try another browser.

Title: disable xampp redirect http to https

Body:
I created VirtualHost at my xampp in localhost for wordpress and add this code in httpd-vhosts.conf :

<VirtualHost *:80>
ServerAdmin webmaster@mysitefolder
DocumentRoot "E:/xampp/htdocs/mysitefolder"
ServerName mysitefolder
ErrorLog "logs/mysitefolder-error.log"
CustomLog "logs/mysitefolder-access.log" common
</VirtualHost>

but when enter http://mysitefolder in browser it's aout redirect to https://mysitefolder and not load my site. how can disable https and only using http ?thank you


问:
How to solve infix expression for calculator app
I am creating calculator application which takes infix expression as input and on click of '=' button app will solve expression and give result or error in case of invalid expression.

So far I have managed to convert infix to post fix using stack and solve expression but its limitation is it takes only one number as operand.

Example:

1+2(3*3)-4^2  //working

11+2(13*3)-4^20  //not working

1.2+2.4(10.5*.5)-4^2 //not working

input is the string expression and while calculation we have to follow BODMAS rule and operators of equal precedence must be evaluated from left to right.

Can any one provide me insight into how to solve this problem? What algorithms should I use? What will be the most efficient way to handle different edge cases? Link to a working example.

答:
I included a space after the number, while converting I was waiting for a space to determine whether the number is complete or not. By this way I was able to solve that.
You can check this code if you want. </p>


问:
Gradle build error using react native
I get this error when trying to run an app on an android emulator(Android Studio) from a console window:

$ react-native run-android
Scanning folders for symlinks in C:\Users\Brian\desktop\codervets\arrive-alive\aa_app\node_modules (27726ms)
Starting JS server...
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Starting a Gradle Daemon (subsequent builds will be faster)
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.

FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring project ':app'.

The SDK directory 'c:\Users\eelia001\AppData\local\android\sdk1' does not exist.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 4m 51s
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

And yet my sdk directory in android studio has the following directory:
C:\Users\Brian\AppData\Local\Android\Sdk

Has anyone else ran into this issue? If so, how do I fix it?

答: So I'm not sure why it was setup the way it was, but the way to fix it is to go to Advanced System Settings → Environment variables. Thank you to @Rich Churcher for the link to a proper tutorial (it's outdated but the steps worked).</p>

Title: Gradle build error using react native


问:
Getting a data attribute with jQuery?
I'm trying to get the data-shareurl from the link below for use in jQuery but for some reason when I put the variable into an alert it is always undefined. Can anyone tell me what I've got wrong? Thanks.
I've made a fiddle here

Html

```<code><a title="" class="fancybox" data-shareurl="www.google.com" href="http://fancyapps.com/fancybox/demo/1_b.jpg">
<img src="http://fancyapps.com/fancybox/demo/1_b.jpg" title="" /></a>
</code>```

jQuery

```<code> var shareurl = $(this).attr('data-shareurl'); //Get this url
 $(".fancybox").fancybox({

   beforeShow: function() {
     this.title = '<div class="addthis addthis_toolbox addthis_default_style "><a href="' + this.href + '" addthis:url="' + this.href + '" addthis:title="' + this.title + '" class="addthis_button_preferred_1"></a></div>';

     alert(shareurl); //see the variable

   },

   afterShow: function() {
     addthis.toolbox(
       $(".addthis").get()
     );
   },
   helpers: {
     title: {
       type: 'inside'
     }
   }

 });
</code>```

答:
You are using this as a selector. I assume that this code is outside the function $('.fancybox')...

Why not use the id or class as a selector.

```<code>var shareurl = $('.fancybox').attr('data-shareurl'); //Get this url
</code>```

Title: Getting a data attribute with jQuery?

Body:
I'm trying to get the data-shareurl from the link below for use in jQuery but for some reason when I put the variable into an alert it is always undefined. Can anyone tell me what I've got wrong? Thanks.
I've made a fiddle here

Html

jQuery

 var shareurl = $(this).attr('data-shareurl'); //Get this url
 $(".fancybox").fancybox({

   beforeShow: function() {
     this.title = '

';

     alert(shareurl); //see the variable

   },

   afterShow: function() {
     addthis.toolbox(
       $(".addthis").get()
     );
   },
   helpers: {
     title: {
       type: 'inside'
     }
   }

 });

Body:
You are using this as a selector. I assume that this code is outside the function $('.fancybox')...

Why not use the id or class as a selector.

var shareurl = $('.fancybox').attr('data-shareurl'); //Get this url


问:
Comparing Object attribute to string won't work
I am trying to search a sorted list of objects and compare user input to the name value of those objects but it will say that the name being compared does not exist within one of the objects in the list.

I have so far tried using

```<code>for network in foundNetworks:
    if network.name == userInputName:
    print("found!")
    break
</code>```

and

```<code>if any(network.name == networkName for network in foundNetworks):
    break
else:
    print("Invalid network name!")
</code>```

The code I am using for sorting and creating networks:

```<code>    class Network():
        # init function must be like this
        def __init__(self, name, security, signalStrength):
            self.name = str(name)
            self.security = str(security)
            self.signalStrength = int(signalStrength)

            # passwords, credit card info etc.
            loot = set()

    # assume multiple new networks are created with varying names which are not the same
    newNetwork = Network(networkName, securityType, networkStrength)
    foundNetworks.append(newNetwork)

    # sort network based on signal strength
    foundNetworks = sorted(foundNetworks, key=lambda network: network.signalStrength, reverse=True)
</code>```

Update

Here is how I actually get user input and verify it exists.

```<code>import time
import linecache
from random import randint

def exampleCheck():
    class Network():
        # init function must be like this
        def __init__(self, name, security, signalStrength):
            self.name = str(name)
            self.security = str(security)
            self.signalStrength = int(signalStrength)

    foundNetworks = []
    securityTypes = ["Joe-Level-Encryption", "AES", "WPA2", "TKIP", "None", "Basic Encryption"]

    for i in range(10):
        while True:
            # uses linecache to randomly pick a name from networks.txt
            networkName = linecache.getline("networks.txt", randint(1, 19))
            networkName = networkName.replace('\n','')

            # ensure network name has not already been found before
            if any(network for network in foundNetworks if network.name == networkName):
                continue
            else:
                break

        # set random network strength and security type
        securityType = securityTypes[randint(0, 5)]
        networkStrength = randint(89, 1005)

        # create a new network and store it in found networks
        newNetwork = Network(networkName, securityType, networkStrength)
        foundNetworks.append(newNetwork)

    # sort network based on signal strength
    foundNetworks = sorted(foundNetworks, key=lambda network: network.signalStrength, reverse=True)

    # display found networks
    for network in foundNetworks:
        print(network.name)

    while True:
        networkName = input("\nNETWORK TO TARGET >> ")
        if any(network.name == networkName for network in foundNetworks):
            print("Found!")
            break
        else:
            print("Invalid network name!")

def main():
    exampleCheck()

if __name__ == "__main__":
    main()
</code>```

Output

```<code>fbiSurveillance
cant get me
SBEGA 42932
ppsadminlogin
notTorenting
notFakeW1f1
ppsWifi
mi network
unhakavle
coporateDominion

NETWORK TO TARGET >> mi network
Invalid network name!

NETWORK TO TARGET >>
</code>```

Expected Output

```<code>fbiSurveillance
cant get me
SBEGA 42932
ppsadminlogin
notTorenting
notFakeW1f1
ppsWifi
mi network
unhakavle
coporateDominion

NETWORK TO TARGET >> mi network
Found!

NETWORK TO TARGET >>
</code>```

答:
The networks.txt file contains trailing whitespace for several of the network names, e.g. (quotes added for emphasis):

```<code>"fbiSurveillance                       "
"SBEGA 42932    "
"mi network                        "
"unhakavle                       "
</code>```

The code takes the trouble to remove the newline character at the end of each line, but it would be better to strip off all trailing whitespace. You can use str.rstrip() for that:

```<code>networkName = networkName.rstrip()
</code>```

This will remove the extra spaces and the newline character, and it should fix the problem.

Body:
I am trying to search a sorted list of objects and compare user input to the name value of those objects but it will say that the name being compared does not exist within one of the objects in the list.

I have so far tried using

for network in foundNetworks:
    if network.name == userInputName:
    print("found!")
    break

and

if any(network.name == networkName for network in foundNetworks):
    break
else:
    print("Invalid network name!")

The code I am using for sorting and creating networks:

    class Network():
        # init function must be like this
        def __init__(self, name, security, signalStrength):
            self.name = str(name)
            self.security = str(security)
            self.signalStrength = int(signalStrength)

            # passwords, credit card info etc.
            loot = set()

    # assume multiple new networks are created with varying names which are not the same
    newNetwork = Network(networkName, securityType, networkStrength)
    foundNetworks.append(newNetwork)

    # sort network based on signal strength
    foundNetworks = sorted(foundNetworks, key=lambda network: network.signalStrength, reverse=True)

Update

Here is how I actually get user input and verify it exists.

import time
import linecache
from random import randint

def exampleCheck():
    class Network():
        # init function must be like this
        def __init__(self, name, security, signalStrength):
            self.name = str(name)
            self.security = str(security)
            self.signalStrength = int(signalStrength)

    foundNetworks = []
    securityTypes = ["Joe-Level-Encryption", "AES", "WPA2", "TKIP", "None", "Basic Encryption"]

    for i in range(10):
        while True:
            # uses linecache to randomly pick a name from networks.txt
            networkName = linecache.getline("networks.txt", randint(1, 19))
            networkName = networkName.replace('\n','')

            # ensure network name has not already been found before
            if any(network for network in foundNetworks if network.name == networkName):
                continue
            else:
                break

        # set random network strength and security type
        securityType = securityTypes[randint(0, 5)]
        networkStrength = randint(89, 1005)

        # create a new network and store it in found networks
        newNetwork = Network(networkName, securityType, networkStrength)
        foundNetworks.append(newNetwork)

    # sort network based on signal strength
    foundNetworks = sorted(foundNetworks, key=lambda network: network.signalStrength, reverse=True)

    # display found networks
    for network in foundNetworks:
        print(network.name)

    while True:
        networkName = input("\nNETWORK TO TARGET >> ")
        if any(network.name == networkName for network in foundNetworks):
            print("Found!")
            break
        else:
            print("Invalid network name!")

def main():
    exampleCheck()

if __name__ == "__main__":
    main()

Output

fbiSurveillance
cant get me
SBEGA 42932
ppsadminlogin
notTorenting
notFakeW1f1
ppsWifi
mi network
unhakavle
coporateDominion

NETWORK TO TARGET >> mi network
Invalid network name!

NETWORK TO TARGET >>

Expected Output

fbiSurveillance
cant get me
SBEGA 42932
ppsadminlogin
notTorenting
notFakeW1f1
ppsWifi
mi network
unhakavle
coporateDominion

NETWORK TO TARGET >> mi network
Found!

NETWORK TO TARGET >>

Body:
The networks.txt file contains trailing whitespace for several of the network names, e.g. (quotes added for emphasis):

"fbiSurveillance                       "
"SBEGA 42932    "
"mi network                        "
"unhakavle                       "

The code takes the trouble to remove the newline character at the end of each line, but it would be better to strip off all trailing whitespace. You can use str.rstrip() for that:

networkName = networkName.rstrip()

This will remove the extra spaces and the newline character, and it should fix the problem.


问:
How to launch an .exe file by clicking a JButton in GUI?
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

```<code>JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file
</code>```

Thanks in advance

答:
Here is an alternative answer without creating a new process through Runtime.getRuntime().exec(...) - and you can maintain your System.in/out channels, too. However,
if you are new to the world of java programming and trying to learn the ropes, I would suggest following camickr's advice and not messing with the ClassLoader as described below.

I am assuming the class you need to run is self contained (uses no inner classes) and not already in your classpath or jarfile so you could just create an instance and call its main().
If there are multiple class files involved, just repeat the method for loading them.

So, in the ActionListener that your JButton addActionListener()-ed to ...

```<code>public void actionPerformed (ActionEvent e) {
    String classNameToRun = e.getActionCommand(); // Or however you want to get it
    try {
        new MyClassLoader().getInstance(classNameToRun).main (null);
    } catch (ClassNotFoundException ce) {
        JOptionPane.showMessageDialog (null, "Sorry, Cannot load class "+classNameToRun,
                            "Your title", JOptionPane.ERROR_MESSAGE);
}}
</code>```

You will need a new class MyClassLoader already in your classpath. Here is a pseudocode:

```<code>import java.io.*;
import java.security.*;

public class MyClassLoader extends ClassLoader {

        protected       String classDirectory = "dirOfClassFiles" + File.separator,
                                packageName = "packageNameOfClass.";

        /**
         * Given a classname, get contents of the class file and return it as a byte array.
         */

        private byte[] getBytes (String className) throws IOException {
                byte[] classBytes = null;
                File file = new File (classDirectory + className + ".class");

                // Find out length of the file and assign memory
                // Deal with FileNotFoundException if it is not there
                long len = file.length();
                classBytes = new byte[(int) len];

                // Open the file
                FileInputStream fin = new FileInputStream (file);

                // Read it into the array; if we don't get all, there's an error.
                // System.out.println ("Reading " + len + " bytes");
                int bCount = fin.read (classBytes);
                if (bCount != len)
                        throw new IOException ("Found "+bCount+" bytes, expecting "+len );

                // Don't forget to close the file!
                fin.close();
                // And finally return the file contents as an array
                return classBytes;
        }

        public Class loadClass (String className, boolean resolve)
                                                throws IOException, ClassNotFoundException,
                                                IllegalAccessException, InstantiationException {
                Class myClass = findLoadedClass (packageName + className);
                if (myClass != null)
                        return myClass;

                byte[] rawBytes = getBytes (className);
                myClass = defineClass (packageName + className,
                                                rawBytes, 0, rawBytes.length);
                // System.out.println ("Defined class " +packageName + className);
                if (myClass == null)
                        return myClass;
                if (resolve)
                        resolveClass (myClass);

                return myClass;
        }

        public Object getInstance (String className) throws ClassNotFoundException {
                try {
                        return loadClass (className, true).newInstance();
                } catch (InstantiationException inExp) {        inExp.printStackTrace();
                } catch (IllegalAccessException ilExp) {        ilExp.printStackTrace();
                } catch (IOException ioExp) {                   ioExp.printStackTrace();
                }
                return null;
        }
}
</code>```

Notes:
This works well when the class you are trying to load is residing on your local machine and you are running java from the command line. I was never successful trying to get an applet to download a classfile from some servlet and load it - security will not allow that. In that case, the workaround is just to run another applet in another window, but that's another thread. The above classloading solves the problem of having to jar up every single classfile that you might be needing - just to start the GUI. Good luck, - M.S.

Body:
I've created a JFrame with 3 Jbuttons. I'd like the button to launch different .exe file located in the same folder. Is this possible? If yes, what should i write for the actionListener? On the other hand, instead of launching an exe file, is it possible to launch a main class using a JButton? If yes, what should i write for the actionListener?

Note: The .exe file is created from a java main program.

JButton button1 = new JButton("Program1"); //The JButton name.
frame.add(button1); //Add the button to the JFrame.
button1.addActionListener().... // how to launch the .exe file

Thanks in advance

Body:
Here is an alternative answer without creating a new process through Runtime.getRuntime().exec(...) - and you can maintain your System.in/out channels, too. However,
if you are new to the world of java programming and trying to learn the ropes, I would suggest following camickr's advice and not messing with the ClassLoader as described below.

I am assuming the class you need to run is self contained (uses no inner classes) and not already in your classpath or jarfile so you could just create an instance and call its main().
If there are multiple class files involved, just repeat the method for loading them.

So, in the ActionListener that your JButton addActionListener()-ed to ...

public void actionPerformed (ActionEvent e) {
    String classNameToRun = e.getActionCommand(); // Or however you want to get it
    try {
        new MyClassLoader().getInstance(classNameToRun).main (null);
    } catch (ClassNotFoundException ce) {
        JOptionPane.showMessageDialog (null, "Sorry, Cannot load class "+classNameToRun,
                            "Your title", JOptionPane.ERROR_MESSAGE);
}}

You will need a new class MyClassLoader already in your classpath. Here is a pseudocode:

import java.io.*;
import java.security.*;

public class MyClassLoader extends ClassLoader {

        protected       String classDirectory = "dirOfClassFiles" + File.separator,
                                packageName = "packageNameOfClass.";

        /**
         * Given a classname, get contents of the class file and return it as a byte array.
         */

        private byte[] getBytes (String className) throws IOException {
                byte[] classBytes = null;
                File file = new File (classDirectory + className + ".class");

                // Find out length of the file and assign memory
                // Deal with FileNotFoundException if it is not there
                long len = file.length();
                classBytes = new byte[(int) len];

                // Open the file
                FileInputStream fin = new FileInputStream (file);

                // Read it into the array; if we don't get all, there's an error.
                // System.out.println ("Reading " + len + " bytes");
                int bCount = fin.read (classBytes);
                if (bCount != len)
                        throw new IOException ("Found "+bCount+" bytes, expecting "+len );

                // Don't forget to close the file!
                fin.close();
                // And finally return the file contents as an array
                return classBytes;
        }

        public Class loadClass (String className, boolean resolve)
                                                throws IOException, ClassNotFoundException,
                                                IllegalAccessException, InstantiationException {
                Class myClass = findLoadedClass (packageName + className);
                if (myClass != null)
                        return myClass;

                byte[] rawBytes = getBytes (className);
                myClass = defineClass (packageName + className,
                                                rawBytes, 0, rawBytes.length);
                // System.out.println ("Defined class " +packageName + className);
                if (myClass == null)
                        return myClass;
                if (resolve)
                        resolveClass (myClass);

                return myClass;
        }

        public Object getInstance (String className) throws ClassNotFoundException {
                try {
                        return loadClass (className, true).newInstance();
                } catch (InstantiationException inExp) {        inExp.printStackTrace();
                } catch (IllegalAccessException ilExp) {        ilExp.printStackTrace();
                } catch (IOException ioExp) {                   ioExp.printStackTrace();
                }
                return null;
        }
}

Notes:
This works well when the class you are trying to load is residing on your local machine and you are running java from the command line. I was never successful trying to get an applet to download a classfile from some servlet and load it - security will not allow that. In that case, the workaround is just to run another applet in another window, but that's another thread. The above classloading solves the problem of having to jar up every single classfile that you might be needing - just to start the GUI. Good luck, - M.S.


问:
How to only match once?
My regex pattern looks something like

•$389 PER MONTH FOR 36 months $4,314 DUE AT SIGNING SUGGESTED DEALER
  CONTRIBUTION OF $1,385 Offer not valid in Puerto Rico. Lease financing
  available on new 2017 BMW 330i xDrive Sports Wagon models from
  participating BMW Centers through BMW Financial Services through
  January 02, 2018, to eligible, qualified customers with excellent
  credit history who meet BMW Financial Services' credit requirements.
  Monthly lease payments of $389 per month for 36 months is based on an
  adjusted capitalized cost of $38,210 (MSRP of $45,595, including
  destination and handling fee of $995, less $3,000 customer down, $0
  security deposit and suggested dealer contribution of $1,385 and
  $3,000 Holiday Lease Credit). Actual MSRP may vary. Dealer
  contribution may vary and could affect your actual monthly lease
  payment. Cash due at signing includes $3,000 down payment, $389 first
  month's payment, $925 acquisition fee and $0 security deposit. Lessee
  responsible for insurance during the lease term, excess wear and tear
  as defined in the lease contract, $0.25/mile over 30,000 miles and a
  disposition fee of $350 at lease end. Not all customers will qualify
  for security deposit waiver. Tax, title, license and registration fees
  are additional fees due at signing. Advertised payment does not
  include applicable taxes. Purchase option at lease end, excluding tax,
  title and government fees, is $27,813. Offer valid through January 02,
  2018 and may be combined with other offers unless otherwise stated.
  Models pictured may be shown with metallic paint and/or additional
  accessories. Visit your authorized BMW Center for important details.
  ©2017 BMW of North America, LLC. The BMW name, model names and logo
  are registered trademarks.

I want to match the number before months, which in this case is

36

However its coming out twice. is there a way to make it only match once?

I'm using \d+\s*(?=( months+?))

Thank you for your help!

答:
Maybe you could find the first 36 before months from the start of the string and then capture it in a group:

^.*?(\d+)(?=\smonths)

Match the start of the string ^

Match any character 0 or more times non greedy .*?

Capture 1 or more digits in a group (\d+)

Positive lookahead if what follows is a whitespace and months (?=\smonths)

Title: How to only match once?


问:
tensorflow dropout - requires weight normalization after changing to keep probability of 1?
Id like to use dropout to improve my model's final prediction accuracy.

To my understanding :

1) Using drop out we randomly assign neurons to zero.

2) Thereby in the next layer the neuron's values are dependent only on a subset of the previous layers neurons.

3) Therefore during training the neurons's weights are trained to be stronger than they should be ( inversely proportional to drop out rate ) to compensate for the 'droped' neurons in the previous layer.

4) After training when we want to use all of the neurons without dropout we need to compensate by multiplying the neurons in each layer by (1-dropout rate).

Am I correct? And if so does tf.nn.dropout() take care of this or do I need to do it manually?

Thanks in advance :)

答: When you do perform dropout, random neurons are chosen in that layer and their weights are made 0. When the model is trained, you get two outputs, the architecture of your model and a h5 file that consists of weights. After the training is done, you save these files in your storage and can load anytime for prediction. You do not have to multiply add weight to any neuron manually. TF takes care of it.</p>


问:
ActionView::Template::Error: (translation missing: en.account.groups.reserve_and_funds)
I got following error while displaying view even I have cleared cache after installing plugin

ActionView::Template::Error (translation missing: en.account.groups.reserve_and_funds):
    157:
    158:
    159:
    160: <% t('account.groups.reserve_and_funds') %>
    161: <% rf_ledger_ids = get_ledger_by_group(AccountGroup::AG_HASH['reserve_and_surplus']) %>
    162: <% rf_opening_balance = ledger_opening_balance(rf_ledger_ids) %>
    163: <% val_hash = get_hash_dccd(SystemConstant::DEBITRULE, SystemConstant::CREDITRULE, rf_ledger_ids, @from_date, @to_date)  %>
  app/views/spree/account/balance_sheets/_bal_sheet_cal.html.erb:160:in _bbb75c09b5307b72b5249abc63b438b8'
  app/views/spree/account/balance_sheets/_bal_sheet.html.erb:1:in_29ca1ef0f0b261e351539b4f61476d2b'
  app/views/spree/account/balance_sheets/_detail_view.html.erb:1:in _a41aea51270c31de5e0cae0119590ea2'
  app/views/spree/account/balance_sheets/index.js.erb:2:in_f5d021945ac0653007f63c2825ddeb1b'
  app/controllers/spree/account/balance_sheets_controller.rb:27:in `index'

答:
define in hierarchy as below in en.yml file</p>

```<code>en: &en
  account:
    groups:
      reserve_and_funds: 'Reserve and funds'
</code>```

Body:
define in hierarchy as below in en.yml file

en: &en
  account:
    groups:
      reserve_and_funds: 'Reserve and funds'


问:
CSS Grid - auto column height
The cart form is stretching vertically and the thumbs are positioning in the bottom left corner, when I'd like them to sit directly under the cart form like so:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto 1fr auto;
}

.product-page--main-content>* {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 3;
  height: 400px;
}

.product-page--description {
  grid-row: span 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="product-page--main-content">
  <div class="product-page--title-n-vendor">Title</div>
  <div class="product-page--cart-form-block">Cart form</div>
  <div class="product-page--thumbs">Thumbs</div>
  <div class="product-page--images">Images</div>
  <div class="product-page--description">Description</div>
</div></code>```

Codepen: https://codepen.io/paulmason/pen/rYXyYW

答:
I'm not sure this is what you're asking but this seems to fit: change

```<code>grid-template-rows: auto 1fr auto;
</code>```

to

```<code>grid-template-rows: 3;
</code>```

Title: CSS Grid - auto column height

Body:
The cart form is stretching vertically and the thumbs are positioning in the bottom left corner, when I'd like them to sit directly under the cart form like so:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto 1fr auto;
}

.product-page--main-content>* {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 3;
  height: 400px;
}

.product-page--description {
  grid-row: span 3;
}

Title

Cart form

Thumbs

Images

Description

Codepen: https://codepen.io/paulmason/pen/rYXyYW

Body:
I'm not sure this is what you're asking but this seems to fit: change

grid-template-rows: auto 1fr auto;

to

grid-template-rows: 3;


问:
How to determine if a JSON response will bind to a model
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

```<code>{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}
</code>```

and then after another 10 or so seconds another JSON webhook comes in.

```<code>{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}
</code>```

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

答:
I'd recommend using the Newtonsoft.json package, which you can install via nuget if you aren't already using it. You can easily accept all JSON requests as a JContainer then check for a field and if that field exists you can deserialize your JSON into the appropriate model.

If you have 4 different models then it would be expected that you'd have 4 semi-unique JSON strings with a different structure that could be identified by checking for a specific field, object or array.

```<code>   public HttpResponseMessage WebhookCallback(JContainer jsonData)
    {
        // Check to make sure we're getting an object not an array.
        if(jsonData.Type == JTokenType.Object)
        {
            var jObject = jsonData as JObject;

            // If this is an event type object parse it depending on the value of the info field.
            if(jObject["event"] != null)
            {

                if (jObject["info"] != null && jObject["info"].ToString() == "REFRESH.INTERIM_PROGRESS")
                {
                    InterimProgress interimProgress = Newtonsoft.Json.JsonConvert.DeserializeObject<InterimProgress>(jObject["data"].ToString());
                }

                if (jObject["info"] != null && jObject["info"].ToString() == "REFRESH.END_PROGRESS")
                {
                    EndProgress interimProgress = Newtonsoft.Json.JsonConvert.DeserializeObject<EndProgress>(jObject["data"].ToString());
                }
            }
            else if (jObject["providerAccount"] != null)
            {
                ProviderAccount providerAccount = jObject.ToObject<ProviderAccount>();
            }
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }
</code>```

If you don't want to deserialize into a JContainer first you could always try to match on a unique key, then deserialize into the correct object.

Body:
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}

and then after another 10 or so seconds another JSON webhook comes in.

{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

Body:
I'd recommend using the Newtonsoft.json package, which you can install via nuget if you aren't already using it. You can easily accept all JSON requests as a JContainer then check for a field and if that field exists you can deserialize your JSON into the appropriate model.

If you have 4 different models then it would be expected that you'd have 4 semi-unique JSON strings with a different structure that could be identified by checking for a specific field, object or array.

   public HttpResponseMessage WebhookCallback(JContainer jsonData)
    {
        // Check to make sure we're getting an object not an array.
        if(jsonData.Type == JTokenType.Object)
        {
            var jObject = jsonData as JObject;

            // If this is an event type object parse it depending on the value of the info field.
            if(jObject["event"] != null)
            {

                if (jObject["info"] != null && jObject["info"].ToString() == "REFRESH.INTERIM_PROGRESS")
                {
                    InterimProgress interimProgress = Newtonsoft.Json.JsonConvert.DeserializeObject<InterimProgress>(jObject["data"].ToString());
                }

                if (jObject["info"] != null && jObject["info"].ToString() == "REFRESH.END_PROGRESS")
                {
                    EndProgress interimProgress = Newtonsoft.Json.JsonConvert.DeserializeObject<EndProgress>(jObject["data"].ToString());
                }
            }
            else if (jObject["providerAccount"] != null)
            {
                ProviderAccount providerAccount = jObject.ToObject<ProviderAccount>();
            }
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }

If you don't want to deserialize into a JContainer first you could always try to match on a unique key, then deserialize into the correct object.


问:
Why the difference between int a[5] = {0} and int a[5]={1} (Missing Feature)
When we initialize an array like this int a[5] = {0}, the compiler makes all 5 elements 0. That is really good, compact-initialization and useful feature.

But I wonder why the compiler doesn't initialize int a[5]={1} similarly? Why does it not make all 5 elements 1? Why the Standard doesn't mandate it? Would it not been an awesome feature? Isn't it missing?

Also, if the number of elements in the initializer is less than the size of the array, then the compile could initialize the remaining elements with the last element in the initializer. Means, int a[5]={1,2,3} is equivalent to int a[5]={1,2,3,3,3}. And similarly, int a[10]={1,2,3,0} is equivalent to int a[10]={1,2,3,0,0,0,0,0,0,0};.

Would it all not be an awesome feature if the Standard mandates it? Or is there any good reasons for this missing feature?

And there is something called designated initializer in C99, which is used like:

Designated initializers can be
  combined with regular initializers, as
  in the following example:

int a[10] = {2, 4, [8]=9, 10}

In this
  example, a[0] is initialized to 2,
  a1 is initialized to 4, a[2] to a[7]
  are initialized to 0, and a[9] is
  initialized to 10.

Quite interesting. But even this feature is not in C++.

答:
Yes, they could have done that, but they didn't, and it's far too late now to change such behavior. The decisions behind C and C++ were made with thought given to performance and minimalism at almost every step, so I imagine that, if nothing else, comes into play here as well.

Such a feature just doesn't strike me as all that awesome. It's a very simple piece of syntactic sugar, and I rarely find the need to initialize an array like that to anything other than 0 anyway.


问:
Class 'Url' not found in Yii2
I'm creating a login and logout page on a custom template in yii2. I got an error because of routing.

Please tell how to import Url or manage url.

答:
Add Url class in top of the page.

```<code>use yii\helpers\Url;
</code>```

Refer Url::to()

Title: Class 'Url' not found in Yii2

Body:
Add Url class in top of the page.

use yii\helpers\Url;

Refer Url::to()


问:
Is it required to use IdentityDbContext for JWT authentication under .NET Core 2.0 and EF?
I'm playing around with the login procedures under .NET Core and I noticed that when I follow the guides and use IdentityDbContext with IdentityUser I get a bunch of tables automagically in the database (e.g. AspNetUsers, AspNetUserClaims etc.).

While it's nice, I wonder if it's very wrong to use the less magical DbContext instead and create my own schema for user and role management. I prefer to "kill my own food" in order to understand how the security works and I dislike using tools and frameworks that I don't understand the bolts and nuts of. ("It just works like that" leads often to problems when it stops working as supposed to.)

Is the Identity part in IdentityDbContext, IdentityUser etc. just a convenience thingy or are those supposed to be used?

The tech stack I'll be targeting is .NET Core 2.0 and JWT authentication. Of course, the model is supposed to be managed in the DB by EF.

Please forgive if the question is stupidly asked. I'm a rookie on the security and might be barking up the wrong tree.

答:
It is not required to use these classes. They are a tested convenience implementation to fit most common use cases but you can replace or customise aspects of the Identity stack.

The identity stack has the following components:

Managers: UserManager, RoleManager and similar classes are used from within the Application to perform the necessary "business" operations with the data. Although you can replace them with custom implementations, it is hardly ever necessary.

Stores: UserStore, RoleStore and similar are used to perform core data operations on the types they manage. You can provide custom implementations to replace the storage mechanism used. The provided stores use entity framework to perform data operations on the managed types. You can replace these to implement other store types. if you were to store user data as documents in ElasticSearch, this would be the interfaces to implement.

Store data types: IdentityUser, IdentityRole etc are the default entity types that hold information about the user/role/claim/.. These types can be subclassed to extend them or you can use different classes if you wish. For example, if you were to store in ElasticSearch, you could reuse these types to avoid creating custom ones to hold user data. The default stores (entity framework) are built to handle subclasses should you wish to store custom information with them. But you do not have to and can use any classes you like as long as you implement a custom store that knows how to use them and there is at least an Id and a UserName property on them.

For more information about customisation options, refer to the Custom storage providers for ASP.NET Core Identity documentation page.


问:
What is the best data structure to extract elements in descending order in O(1) time
I insert elements as we do a certain operation and try to get the elements in the order of insertion(which is considered the element's age). priority_queues could be used but since they are implemented as heaps, the operation to visit the top element is O(1), but to get the next element in the next iteration I have to do a pop() along with the call to top(). pop() is log(n). I am thinking if I should just use a regular queue to add elements whenever I would add it into the priority_queue and keep poping from the queue to get elements in the order of their addition time. My confusion is that since we have a multi-threaded application, could there be elements out of order and so would be safe to visit all elements to make sure. This would make it O(n). Can somebody help me in my choice of the data structure to use?

Should I just go ahead with a priority_queue and get elements in O(log n) everytime? Or use a stack and assume the guarantee of the order of elements and get elements in O(1) everytime? Or use a totally different data structure?

Please keep in mind that this is implemented in VC++ and have access to boost.

Would like views on this. Thanks!

答: Since, what you are looking for is a simple FIFO, I suggest you to use some thread safe queue, And I am sure boost has already implemented some thread safe queue like message queue.</p>