问:
How to pass laravel CSRF token value to vue
I have this form where the user should only type text inside a text area:

```<code>            <form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}
                <div class="form-group">
                    <textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post"></textarea>
                </div>
                <input type="submit" value="Post" class="form-control btn btn-info">

                {{ csrf_field() }}

            </form>
</code>```

Then, I have this script code where I am using vue.js with ajax in order to pass that text into a controller and eventually save it into the database:

```<code>//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
        },
        http    :   {
            headers: {
                'X-CSRF-Token': $('meta[name=_token]').attr('content')
            }
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                    }
                });
            }
        },
    });
</code>```

However, this doesn't work so far, since there's this token mismatch exception. I don't know how to make it work. How to pass this token value to the controller. I have tried the following:

1) inside the form, I have added a vue name to the token:

```<code><input type="hidden" name="_token" value="YzXAnwBñC7qPK9kg7MGGIUzznEOCi2dTnG9h9çpB" v-model="token">
</code>```

2) I have tried to pass this token value into the vue:

```<code>//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
            token   : '',
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                        '_token':   this.token,
                    }
                });
            }
        },
    });
</code>```

... but in the console, vue doesn't even catch it :(

This leads me to the following error:

TokenMismatchException in VerifyCsrfToken.php line 68:

How do I fix it? Any ideas?

答:
Simply, I would suggest to put this in your PHP file:

```<code><script>
    window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>
</code>```

This way you're able to easily import your csrfToken from the JS part (Vue in this case).

Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.

Source: I got the trick from this post.

Body:
I have this form where the user should only type text inside a text area:

            <form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}

                    <textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post"></textarea>

                <input type="submit" value="Post" class="form-control btn btn-info">

                {{ csrf_field() }}

            </form>

Then, I have this script code where I am using vue.js with ajax in order to pass that text into a controller and eventually save it into the database:

//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
        },
        http    :   {
            headers: {
                'X-CSRF-Token': $('meta[name=_token]').attr('content')
            }
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                    }
                });
            }
        },
    });

However, this doesn't work so far, since there's this token mismatch exception. I don't know how to make it work. How to pass this token value to the controller. I have tried the following:

1) inside the form, I have added a vue name to the token:

<input type="hidden" name="_token" value="YzXAnwBñC7qPK9kg7MGGIUzznEOCi2dTnG9h9çpB" v-model="token">

2) I have tried to pass this token value into the vue:

//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
            token   : '',
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                        '_token':   this.token,
                    }
                });
            }
        },
    });

... but in the console, vue doesn't even catch it :(

This leads me to the following error:

TokenMismatchException in VerifyCsrfToken.php line 68:

How do I fix it? Any ideas?

Body:
Simply, I would suggest to put this in your PHP file:

<script>
    window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>

This way you're able to easily import your csrfToken from the JS part (Vue in this case).

Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.

Source: I got the trick from this post.


来源: stackexchange

问:
Where to open file in a Perl module

Below is a toy version of a module I'm writing. This example faithfully demonstrates the problem I having.

I have a file bed_in.txt

2L      0       4953
2L      16204   16284
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635
2L      19894   21366
2L      21582   21583
2L      47501   52365
2L      4698700 4709369
```

<p>that I want to use to filter values in an array.</p>

<p>I want to check whether the second column of <code>bed_in.txt</code> matches any value in</p>

<pre class="lang-none prettyprint-override"><code>my @lines = qw/ 16204 40 200 149 19445 178 /;
</code>```

push this to an array if so.

My final output for this data should be the two elements in @lines that are also in the second column of bed_in.txt

2L      0       4953
2L      16204   16284 # 16204 == 16204
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635 # 19445 == 19445
```

<p>But where should I open my file?</p>

<p>Should this happen in the script that calls my module <code>run_fileOpen.pl</code>, or in the module itself? </p>

<p>In either case, I am not getting the correct output, and my module appears to be called for only the first element of <code>@lines</code></p>

<h3>parseFile.pm</h3>

<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl

package parseFile;
use strict;
use warnings;

use FindBin qw/ $Bin /;
use lib File::Spec->catdir($FindBin::Bin, '..', 'bin/');

use Data::Printer;

open my $bed, '<', 'bed_in.txt';

sub check_lines {
  my ($line, $filter_ref) = @_;
  my @filter_reasons = @{ $filter_ref };

  my $lines_to_filter_ref = filter_lines($line, $bed, \@filter_reasons);

  return($lines_to_filter_ref);
}

sub filter_lines {
  my ($line, $bed_file, $lines_to_filter) = @_;

  my @filter = @{ $lines_to_filter };

  while(<$bed_file>){
    chomp;
    my $start = (split)[1];
    # print "line: $line  start: $start\n";
    if ($line == $start ) {

      push @filter, "Filter as equal: $start, $line [$_]";
    }
  }
  # p(@filter);
  return(\@filter);
}

1;
</code>```

run_parseFile.pl

#!/usr/bin/perl

use strict;
use warnings;

use parseFile;

my @lines = qw/ 16204 40 200 149 19445 178 /;

foreach(@lines){
  my @filter_reasons = 'reason 1';
  my $lines2filter = parseFile::check_lines($_, \@filter_reasons);
  @filter_reasons = @{ $lines2filter };
  print "$_\n" foreach @filter_reasons;
}
```

<h3>Output</h3>

<pre class="lang-none prettyprint-override"><code>reason 1
Filter as equal: 16204, 16204 [2L   16204   16284]
reason 1
reason 1
reason 1
reason 1
reason 1
</code>```

When I add a print statement to the while loop in filter_lines I can see that only the first element is being run:

line: 16204  start: 0
line: 16204  start: 16204
line: 16204  start: 16612
line: 16204  start: 17086
line: 16204  start: 18757
line: 16204  start: 19040
line: 16204  start: 19445
line: 16204  start: 19894
line: 16204  start: 21582
line: 16204  start: 47501
line: 16204  start: 4698700
```

Is this an appropriate way to deal with opening my bed_in.txt file, or should I open it in the run_parseFile.pl script? Or is there something else entirely wrong with my code?

答: A module should open and close files in the same subroutine unless the name of the sub has "open" in it, in which case, it should return a file handle as one of its return values. And there should be a corresponding "close" sub to match every "open" sub.</p>

ContentLicense: CC BY-SA 3.0

Title: Where to open file in a Perl module

Body:
Below is a toy version of a module I'm writing. This example faithfully demonstrates the problem I having.

I have a file bed_in.txt

2L      0       4953
2L      16204   16284
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635
2L      19894   21366
2L      21582   21583
2L      47501   52365
2L      4698700 4709369

that I want to use to filter values in an array.

I want to check whether the second column of bed_in.txt matches any value in

my @lines = qw/ 16204 40 200 149 19445 178 /;

push this to an array if so.

My final output for this data should be the two elements in @lines that are also in the second column of bed_in.txt

2L      0       4953
2L      16204   16284 # 16204 == 16204
2L      16612   16805
2L      17086   18561
2L      18757   18758
2L      19040   19120
2L      19445   19635 # 19445 == 19445

But where should I open my file?

Should this happen in the script that calls my module run_fileOpen.pl, or in the module itself?

In either case, I am not getting the correct output, and my module appears to be called for only the first element of @lines

parseFile.pm

#!/usr/bin/perl

package parseFile;
use strict;
use warnings;

use FindBin qw/ $Bin /;
use lib File::Spec->catdir($FindBin::Bin, '..', 'bin/');

use Data::Printer;

open my $bed, '<', 'bed_in.txt';

sub check_lines {
  my ($line, $filter_ref) = @_;
  my @filter_reasons = @{ $filter_ref };

  my $lines_to_filter_ref = filter_lines($line, $bed, \@filter_reasons);

  return($lines_to_filter_ref);
}

sub filter_lines {
  my ($line, $bed_file, $lines_to_filter) = @_;

  my @filter = @{ $lines_to_filter };

  while(<$bed_file>){
    chomp;
    my $start = (split)[1];
    # print "line: $line  start: $start\n";
    if ($line == $start ) {

      push @filter, "Filter as equal: $start, $line [$_]";
    }
  }
  # p(@filter);
  return(\@filter);
}

1;

run_parseFile.pl

#!/usr/bin/perl

use strict;
use warnings;

use parseFile;

my @lines = qw/ 16204 40 200 149 19445 178 /;

foreach(@lines){
  my @filter_reasons = 'reason 1';
  my $lines2filter = parseFile::check_lines($_, \@filter_reasons);
  @filter_reasons = @{ $lines2filter };
  print "$_\n" foreach @filter_reasons;
}

Output

reason 1
Filter as equal: 16204, 16204 [2L   16204   16284]
reason 1
reason 1
reason 1
reason 1
reason 1

When I add a print statement to the while loop in filter_lines I can see that only the first element is being run:

line: 16204  start: 0
line: 16204  start: 16204
line: 16204  start: 16612
line: 16204  start: 17086
line: 16204  start: 18757
line: 16204  start: 19040
line: 16204  start: 19445
line: 16204  start: 19894
line: 16204  start: 21582
line: 16204  start: 47501
line: 16204  start: 4698700

Is this an appropriate way to deal with opening my bed_in.txt file, or should I open it in the run_parseFile.pl script? Or is there something else entirely wrong with my code?


问:
Preventing spam direct POST request customer registrations in Magento
I've begun to have some issues with spam POST requests on a Magento site where a bot is making spam users (this is even with the action attribute being removed, captcha, etc) as these bots I believe are just making direct POST requests to the standard Magento account url.

Here's 3 examples of valid POST requests I've seen in the log:

```<code>x.x.x.x - - [06/Nov/2017:13:54:47 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36"

x.x.x.x - - [05/Nov/2017:11:34:42 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

x.x.x.x - - [05/Nov/2017:19:33:15 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
</code>```

I've anonymized the IP addresses at the beginning, as well as the url. However, notice that the 2nd url is /customer/account/create/ while the first url is /customer/account/createpost/

Here's 3 examples of spam POST requests:

```<code>112.96.164.18 - - [05/Nov/2017:11:43:43 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.164.18 - - [05/Nov/2017:12:03:17 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.100.2 - - [05/Nov/2017:13:53:45 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"
</code>```

As far as I can tell on every single spam request, both the first and second url are /customer/account/createpost/

What is the 2nd url in this, compared to the first? Is one where the request was sent and the other where it came from?

/customer/account/createpost/ should probably never be the origin, since that's where the form is actually sent, and visiting it directly redirect /customer/account/create/

My main question is, how do I reliably block the second set of POST requests?

答:
Your first question, yes the two URLs in the logs are the URL being requested, and, if the browser provided it, the referring URL for that request. Conventionally they're in that order; the other information are things like HTTP return code, the User-Agent string, etc..

If your current spam requests are so predictable, then you might want to just block them on the basis of their user agent and/or originating IP range, as both of those look consistent in your examples. For example using user-agent:

```<code># in .htaccess
RewriteCond %{USER_AGENT} ^Mozilla/5.0.+WOW64.+Gecko/20100101$
RewriteRule  ^.*  -  [G,L]
</code>```

Obviously that won't be foolproof but can be useful.

Or, selectively blocking that spammer from that specific script, unless they come from the right place, by relying on that referrer field (which the client provides) is the other route & the other solution. My preference is to throw out clowns altogether if possible, unless there are valid reasons for letting them into your site at all.

Body:
I've begun to have some issues with spam POST requests on a Magento site where a bot is making spam users (this is even with the action attribute being removed, captcha, etc) as these bots I believe are just making direct POST requests to the standard Magento account url.

Here's 3 examples of valid POST requests I've seen in the log:

x.x.x.x - - [06/Nov/2017:13:54:47 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36"

x.x.x.x - - [05/Nov/2017:11:34:42 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

x.x.x.x - - [05/Nov/2017:19:33:15 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/create/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"

I've anonymized the IP addresses at the beginning, as well as the url. However, notice that the 2nd url is /customer/account/create/ while the first url is /customer/account/createpost/

Here's 3 examples of spam POST requests:

112.96.164.18 - - [05/Nov/2017:11:43:43 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.164.18 - - [05/Nov/2017:12:03:17 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

112.96.100.2 - - [05/Nov/2017:13:53:45 -0500] "POST /customer/account/createpost/ HTTP/1.1" 302 - "https://www.example.com/customer/account/createpost/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"

As far as I can tell on every single spam request, both the first and second url are /customer/account/createpost/

What is the 2nd url in this, compared to the first? Is one where the request was sent and the other where it came from?

/customer/account/createpost/ should probably never be the origin, since that's where the form is actually sent, and visiting it directly redirect /customer/account/create/

My main question is, how do I reliably block the second set of POST requests?

Body:
Your first question, yes the two URLs in the logs are the URL being requested, and, if the browser provided it, the referring URL for that request. Conventionally they're in that order; the other information are things like HTTP return code, the User-Agent string, etc..

If your current spam requests are so predictable, then you might want to just block them on the basis of their user agent and/or originating IP range, as both of those look consistent in your examples. For example using user-agent:

# in .htaccess
RewriteCond %{USER_AGENT} ^Mozilla/5.0.+WOW64.+Gecko/20100101$
RewriteRule  ^.*  -  [G,L]

Obviously that won't be foolproof but can be useful.

Or, selectively blocking that spammer from that specific script, unless they come from the right place, by relying on that referrer field (which the client provides) is the other route & the other solution. My preference is to throw out clowns altogether if possible, unless there are valid reasons for letting them into your site at all.


问:
ASP.Net: Work on XML data from a database
I have an issue on which methods or technology i can work on, so as to visualize on a web application a simple information from a database.
The data is only xml, like this :
It's one data for 1 element

It's a very heavy element ans it's not under my control and i can't modify the datafield, but the only things i want is to save the value from the XML Elements "FormId" and "TimeLastModified", so as to display this on my web application.
I would like to work on code-behind with ASP.Net.
A kind person on this website told me about System.Xml.XmlDocument, but i want to connect this to the database with SqlConnection and save these value on string, so as to use it later.
Is it possible ?

EDIT : the database saves id, name and Content of templates and forms from a design software. Every Elements are saved on xml data in the Content field.
The designer who works on that app can make modification on the templates, but there are links between templates and forms, and a simple modification can modify one or many forms.
My job is to display on a web application each templates modify (with the "TimeLastModified" xml element), and the forms which are associated to (with the "FormId" xml element).

table Template structure

table Template datas

答:
If you are using Visual Studio 2017, you can do this:

And you will get classes to read and write your XML:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyXML
{
    // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Root
    {

        private RootStorageObject storageObjectField;

        /// <remarks/>
        public RootStorageObject StorageObject
        {
            get
            {
                return this.storageObjectField;
            }
            set
            {
                this.storageObjectField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RootStorageObject
    {

        private RootStorageObjectProperty[] propertiesField;

        private string nameField;

        private string idField;

        private string typeField;

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)]
        public RootStorageObjectProperty[] Properties
        {
            get
            {
                return this.propertiesField;
            }
            set
            {
                this.propertiesField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Id
        {
            get
            {
                return this.idField;
            }
            set
            {
                this.idField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RootStorageObjectProperty
    {

        private string nameField;

        private string valueField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

}
</code>```

Then you can Serialize or Deserialize your object to XML

```<code>   /// <summary>
   /// The serialize.
   /// </summary>
   /// <param name="value">
   /// The value.
   /// </param>
   /// <param name="xmlWriterSettings">
   /// The xml writer settings.
   /// </param>
   /// <typeparam name="T">
   /// The object of the type T.
   /// </typeparam>
   /// <returns>
   /// The value in <see cref="string"/> that correspond the xml.
   /// </returns>
   /// <exception cref="ArgumentException">
   /// The value cannot be null.
   /// </exception>
   public static string Serialize<T>(T value, XmlWriterSettings xmlWriterSettings = null)
   {
       if (value == null)
       {
           throw new ArgumentException("value");
       }

       var serializer = new XmlSerializer(typeof(T));

       var settings = xmlWriterSettings ?? new XmlWriterSettings
       {
           Encoding = new UnicodeEncoding(false, false),
           Indent = false,
           OmitXmlDeclaration = false
       };

       using (var textWriter = new StringWriter())
       {
           using (var xmlWriter = XmlWriter.Create(textWriter, settings))
           {
               serializer.Serialize(xmlWriter, value);
           }

           return textWriter.ToString();
       }
   }

/// <summary>
/// The deserialize.
/// </summary>
/// <param name="xml">
/// The xml.
/// </param>
/// <param name="xmlReaderSettings">
/// The xml Reader Settings.
/// </param>
/// <typeparam name="T">
/// The object of the type T.
/// </typeparam>
/// <returns>
/// The object of the type <see cref="T"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// The xml value cannot be null.
/// </exception>
public static T Deserialize<T>(string xml, XmlReaderSettings xmlReaderSettings = null)
{
    if (string.IsNullOrEmpty(xml))
    {
        throw new ArgumentException("xml");
    }

    var serializer = new XmlSerializer(typeof(T));

    var settings = xmlReaderSettings ?? new XmlReaderSettings();

    // No settings need modifying here
    using (var textReader = new StringReader(xml))
    {
        using (var xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }
}
</code>```

source: http://www.saramgsilva.com/index.php/2014/c-generic-xml-serialize-deserialize/

Body:
If you are using Visual Studio 2017, you can do this:

And you will get classes to read and write your XML:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyXML
{
    // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Root
    {

        private RootStorageObject storageObjectField;

        /// <remarks/>
        public RootStorageObject StorageObject
        {
            get
            {
                return this.storageObjectField;
            }
            set
            {
                this.storageObjectField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RootStorageObject
    {

        private RootStorageObjectProperty[] propertiesField;

        private string nameField;

        private string idField;

        private string typeField;

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)]
        public RootStorageObjectProperty[] Properties
        {
            get
            {
                return this.propertiesField;
            }
            set
            {
                this.propertiesField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Id
        {
            get
            {
                return this.idField;
            }
            set
            {
                this.idField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Type
        {
            get
            {
                return this.typeField;
            }
            set
            {
                this.typeField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RootStorageObjectProperty
    {

        private string nameField;

        private string valueField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

}

Then you can Serialize or Deserialize your object to XML

   /// <summary>
   /// The serialize.
   /// </summary>
   /// <param name="value">
   /// The value.
   /// </param>
   /// <param name="xmlWriterSettings">
   /// The xml writer settings.
   /// </param>
   /// <typeparam name="T">
   /// The object of the type T.
   /// </typeparam>
   /// <returns>
   /// The value in <see cref="string"/> that correspond the xml.
   /// </returns>
   /// <exception cref="ArgumentException">
   /// The value cannot be null.
   /// </exception>
   public static string Serialize<T>(T value, XmlWriterSettings xmlWriterSettings = null)
   {
       if (value == null)
       {
           throw new ArgumentException("value");
       }

       var serializer = new XmlSerializer(typeof(T));

       var settings = xmlWriterSettings ?? new XmlWriterSettings
       {
           Encoding = new UnicodeEncoding(false, false),
           Indent = false,
           OmitXmlDeclaration = false
       };

       using (var textWriter = new StringWriter())
       {
           using (var xmlWriter = XmlWriter.Create(textWriter, settings))
           {
               serializer.Serialize(xmlWriter, value);
           }

           return textWriter.ToString();
       }
   }

/// <summary>
/// The deserialize.
/// </summary>
/// <param name="xml">
/// The xml.
/// </param>
/// <param name="xmlReaderSettings">
/// The xml Reader Settings.
/// </param>
/// <typeparam name="T">
/// The object of the type T.
/// </typeparam>
/// <returns>
/// The object of the type <see cref="T"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// The xml value cannot be null.
/// </exception>
public static T Deserialize<T>(string xml, XmlReaderSettings xmlReaderSettings = null)
{
    if (string.IsNullOrEmpty(xml))
    {
        throw new ArgumentException("xml");
    }

    var serializer = new XmlSerializer(typeof(T));

    var settings = xmlReaderSettings ?? new XmlReaderSettings();

    // No settings need modifying here
    using (var textReader = new StringReader(xml))
    {
        using (var xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }
}

source: http://www.saramgsilva.com/index.php/2014/c-generic-xml-serialize-deserialize/


问:
How to get the signature of a C++ bind(...) expression
I am trying to write a metafunction named signature_of which, given the type of a function (pointer), functor, or lambda, returns its signature.

Here's what I have so far:

```<code>#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/function_types/is_member_function_pointer.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/parameter_types.hpp>

#include <type_traits>

template <typename F>
struct signature_of_member
{
    typedef typename boost::function_types::result_type<F>::type result_type;
    typedef typename boost::function_types::parameter_types<F>::type parameter_types;
    typedef typename boost::mpl::pop_front<parameter_types>::type base;
    typedef typename boost::mpl::push_front<base, result_type>::type L;
    typedef typename boost::function_types::function_type<L>::type type;
};

template <typename F, bool is_class>
struct signature_of_impl
{
    typedef typename boost::function_types::function_type<F>::type type;
};

template <typename F>
struct signature_of_impl<F, true>
{
    typedef typename signature_of_member<decltype(&F::operator())>::type type;
};

template <typename F>
struct signature_of
{
    typedef typename signature_of_impl<F, std::is_class<F>::value>::type type;
};
</code>```

It's pretty straightforward, with most of the real work being done by the boost::function_types library.
The general idea is:

use std::is_class to discriminate
between built-in functions (including
lambdas) and functors

for built-in function types, use boost::function_types::function_type to get its signature

for functors, get the type of their operator(), get its signature, and doctor it to remove the "this" parameter

This works for built-in functions:

```<code>int f(int);
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)
</code>```

for lambdas:

```<code>auto f = [](int) { return 0; }
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)
</code>```

and for functors:

```<code>struct A
{
    int operator()(int);
};
typedef signature_of<A>::type Sig;  // Sig is int(int)
</code>```

However, it doesn't work for bind() expressions (which are a special case of functors). If I try this:

```<code>#include <functional>
int g(int);
typedef signature_of<decltype(std::bind(g, 0))>::type Sig;
</code>```

I get a compiler error:

```<code>In file included from test.cpp:3:0:
signature_of.hpp: In instantiation of 'signature_of_impl<
        _Bind<int (*(int))(int)>, true
    >':
signature_of.hpp:45:74:   instantiated from 'signature_of<
        _Bind<int (*(int))(int)>
    >'
test.cpp:21:52:   instantiated from here
signature_of.hpp:39:74: error: type of '& _Bind<
        int (*)(int)({int} ...)
    >::operator()' is unknown
</code>```

The problem is that the operator() of the functor returned by bind() is a template, and so its type cannot be determined.

Is it possible to get the signature of a bind() expression another way?

答:
You've got more problems than the fact that a binder's operator() is templated, it also has an arbitrary count of parameters.  Remember that you're supposed to be able to invoke the result of bind with any number of extra arguments.  For example:

```<code>int f(int);

auto bound = boost::bind(f, _2);
</code>```

bound may now be called with any number of arguments of 2 or more, only the second is actually forwarded on to the function.

So basically, as another answer said, this object has no signature.  It's signature is defined only by how it is used.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to write a metafunction named signature_of which, given the type of a function (pointer), functor, or lambda, returns its signature.

Here's what I have so far:

#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/function_types/is_member_function_pointer.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/result_type.hpp>
#include <boost/function_types/parameter_types.hpp>

#include <type_traits>

template <typename F>
struct signature_of_member
{
    typedef typename boost::function_types::result_type<F>::type result_type;
    typedef typename boost::function_types::parameter_types<F>::type parameter_types;
    typedef typename boost::mpl::pop_front<parameter_types>::type base;
    typedef typename boost::mpl::push_front<base, result_type>::type L;
    typedef typename boost::function_types::function_type<L>::type type;
};

template <typename F, bool is_class>
struct signature_of_impl
{
    typedef typename boost::function_types::function_type<F>::type type;
};

template <typename F>
struct signature_of_impl<F, true>
{
    typedef typename signature_of_member<decltype(&F::operator())>::type type;
};

template <typename F>
struct signature_of
{
    typedef typename signature_of_impl<F, std::is_class<F>::value>::type type;
};

It's pretty straightforward, with most of the real work being done by the boost::function_types library.
The general idea is:

use std::is_class to discriminate
between built-in functions (including
lambdas) and functors

for built-in function types, use boost::function_types::function_type to get its signature

for functors, get the type of their operator(), get its signature, and doctor it to remove the "this" parameter

This works for built-in functions:

int f(int);
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)

for lambdas:

auto f = [](int) { return 0; }
typedef signature_of<decltype(f)>::type Sig;  // Sig is int(int)

and for functors:

struct A
{
    int operator()(int);
};
typedef signature_of::type Sig;  // Sig is int(int)

However, it doesn't work for bind() expressions (which are a special case of functors). If I try this:

#include <functional>
int g(int);
typedef signature_of<decltype(std::bind(g, 0))>::type Sig;

I get a compiler error:

In file included from test.cpp:3:0:
signature_of.hpp: In instantiation of 'signature_of_impl<
        _Bind<int (*(int))(int)>, true
    >':
signature_of.hpp:45:74:   instantiated from 'signature_of<
        _Bind<int (*(int))(int)>
    >'
test.cpp:21:52:   instantiated from here
signature_of.hpp:39:74: error: type of '& _Bind<
        int (*)(int)({int} ...)
    >::operator()' is unknown

The problem is that the operator() of the functor returned by bind() is a template, and so its type cannot be determined.

Is it possible to get the signature of a bind() expression another way?

Body:
You've got more problems than the fact that a binder's operator() is templated, it also has an arbitrary count of parameters.  Remember that you're supposed to be able to invoke the result of bind with any number of extra arguments.  For example:

int f(int);

auto bound = boost::bind(f, _2);

bound may now be called with any number of arguments of 2 or more, only the second is actually forwarded on to the function.

So basically, as another answer said, this object has no signature.  It's signature is defined only by how it is used.


问:
reading from SQL doesn't put value in string list
I am trying to add data from sql in string list but it keeps saynig that my string list = null.

code on the button:

```<code>    protected void Button2_Click(object sender, EventArgs e)
        {
            // go back to the menu
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            // code to display the books by sanctuary
            ListBox1.Items.Clear();
            List<String> s = DBConnectivity.LoadBooksBySanctuary2(3/*int.Parse(DDSanctuary.SelectedValue)*/);

            foreach (var detail in s)
            {
               ListBox1.Items.Add(detail);
            }

        }
</code>```

code to read from SQL and put into string list. I know my connection works fine because I can add pets

```<code> public static List<String> LoadPetsBySanctuary2(int sID)
        {
            List<String> saName = new List<String>();
            SqlConnection myConnection = GetConnection();
            // string myQuery = "SELECT  Name, categId, cName FROM Book, Category WHERE Book.CategID=Category.ID AND Book.authorId = " + sID;

            string myQuery = "SELECT  Name  FROM pet WHERE sanID = " + saName;

            SqlCommand myCommand = new SqlCommand(myQuery, myConnection);

            try
            {
                myConnection.Open();
                SqlDataReader myReader = myCommand.ExecuteReader();

                while (myReader.Read())
                {
                 //   saName.Add(myReader["Name"].ToString());

                    saName.Add(myReader["Name"].ToString());

                }
                return saName;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);
                return null;
            }
            finally
            {
                myConnection.Close();
            }
        }
</code>```

答:
If the list is coming back as null, then you're hitting the catch(Exception ex) block. That is the only place that returns null. Hint: stop swallowing exceptions.  The exception will tell you what the problem is.

Also: use parameters - never ever append input like this.

You probably meant to use sId instead of saName.

May I humbly suggest some "Dapper" here:

```<code>public static List<String> LoadPetsBySanctuary2(int sID)
{
    return GetConnection().Query<string>(
        "SELECT  Name  FROM pet WHERE sanID = @sID",
        new { sID }).AsList();
}
</code>```

note: it isn't clear whether GetConnection passes ownership of a connection or not; if it does, you should use using:

```<code>public static List<String> LoadPetsBySanctuary2(int sID)
{
    using(var myConnection = GetConnection())
    {
        return myConnection.Query<string>(
            "SELECT  Name  FROM pet WHERE sanID = @sID",
            new { sID }).AsList();
    }
}
</code>```

Body:
I am trying to add data from sql in string list but it keeps saynig that my string list = null.

code on the button:

    protected void Button2_Click(object sender, EventArgs e)
        {
            // go back to the menu
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            // code to display the books by sanctuary
            ListBox1.Items.Clear();
            List<String> s = DBConnectivity.LoadBooksBySanctuary2(3/*int.Parse(DDSanctuary.SelectedValue)*/);

            foreach (var detail in s)
            {
               ListBox1.Items.Add(detail);
            }

        }

code to read from SQL and put into string list. I know my connection works fine because I can add pets

 public static List<String> LoadPetsBySanctuary2(int sID)
        {
            List<String> saName = new List<String>();
            SqlConnection myConnection = GetConnection();
            // string myQuery = "SELECT  Name, categId, cName FROM Book, Category WHERE Book.CategID=Category.ID AND Book.authorId = " + sID;

            string myQuery = "SELECT  Name  FROM pet WHERE sanID = " + saName;

            SqlCommand myCommand = new SqlCommand(myQuery, myConnection);

            try
            {
                myConnection.Open();
                SqlDataReader myReader = myCommand.ExecuteReader();

                while (myReader.Read())
                {
                 //   saName.Add(myReader["Name"].ToString());

                    saName.Add(myReader["Name"].ToString());

                }
                return saName;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in DBHandler", ex);
                return null;
            }
            finally
            {
                myConnection.Close();
            }
        }

Body:
If the list is coming back as null, then you're hitting the catch(Exception ex) block. That is the only place that returns null. Hint: stop swallowing exceptions.  The exception will tell you what the problem is.

Also: use parameters - never ever append input like this.

You probably meant to use sId instead of saName.

May I humbly suggest some "Dapper" here:

public static List<String> LoadPetsBySanctuary2(int sID)
{
    return GetConnection().Query<string>(
        "SELECT  Name  FROM pet WHERE sanID = @sID",
        new { sID }).AsList();
}

note: it isn't clear whether GetConnection passes ownership of a connection or not; if it does, you should use using:

public static List<String> LoadPetsBySanctuary2(int sID)
{
    using(var myConnection = GetConnection())
    {
        return myConnection.Query<string>(
            "SELECT  Name  FROM pet WHERE sanID = @sID",
            new { sID }).AsList();
    }
}


问:
apply a function in the j section of a data.table that only works on one value of vector at a time
A possible duplicate is here but it does not help me. My case is different perhaps.

Consider a sample data.table.

```<code>set.seed(21)
DT <- data.table(col1=sample(x=1:10,size = 5),col2=sample(x=10:20,size=5))
DT
   col1 col2
1:    8   20
2:    3   11
3:    6   19
4:    2   17
5:   10   15
</code>```

And consider a function check I want to apply to each row:

```<code>check <- function(x,y) if ((y-x)>10) "A" else "B"
</code>```

Now if I run this assignment by reference calling the function check in the j section of DT, it fails miserably,

```<code>DT[,state:=check(col1,col2)]
</code>```

And throws this warning

```<code>Warning message:
In if ((y - x) > 10) "A" else "B" :
  the condition has length > 1 and only the first element will be used
</code>```

Obviously, I guessed that data.table processes the whole vector at once and the function needs one value so I thought the last value is the current value in the vector so I made this change, which seems another stupid move :-)

```<code>DT[,state:=check(last(col1),last(col2))]

DT

   col1 col2 state
1:    8   20     B
2:    3   11     B
3:    6   19     B
4:    2   17     B
5:   10   15     B
</code>```

I see the check() function was computed for the last value and overwrote all previous values every time. What I want is this output:

```<code> DT

   col1 col2 state
1:    8   20     A
2:    3   11     A
3:    6   19     A
4:    2   17     A
5:   10   15     B
</code>```

So how do I make a function call work in a data.table for each row independently?

ACTUAL FUNCTION:
After I received a suggestion from akrun to use ifelse, which works fine for a simple condition like check() but I have a slightly more complicated function here. So please replace check by allowed_state

```<code>allowed_state <- function(old=NULL,new=NULL){
legalst<-data.table(from=c(1,1,9,9,7,8,7,10,10,11,11,10,11,8,7),to=c(11,7,10,7,8,7,9,9,7,1,7,1,7,9,10)) # all legal state transitions for a user
if(new %in% legalst[from==old,to]) "Legal" else "Illegal state change"
</code>```

}

答:
If I have understood correctly, the OP wants to mark those state changes which are legal or illegal according to a given table legalst of legal state changes.

This can solved using an update on join:

```<code>set.seed(21)
DT <- data.table(col1 = sample(x = c(1, 7:11), size = 5),
                 col2 = sample(x = c(1, 7:11), size = 5))
legalst <- data.table(from = c(1,1,9,9,7,8,7,10,10,11,11,10,11,8,7),
                      to = c(11,7,10,7,8,7,9,9,7,1,7,1,7,9,10))

DT[legalst, on = .(col1 = from, col2 = to), state := "Legal"][
  is.na(state), state := "Illegal state change"][]
</code>```

```<code>   col1 col2                state
1:   10   11 Illegal state change
2:    7    1 Illegal state change
3:    8   10 Illegal state change
4:    1    8 Illegal state change
5:   11    7                Legal
</code>```

Body:
A possible duplicate is here but it does not help me. My case is different perhaps.

Consider a sample data.table.

set.seed(21)
DT <- data.table(col1=sample(x=1:10,size = 5),col2=sample(x=10:20,size=5))
DT
   col1 col2
1:    8   20
2:    3   11
3:    6   19
4:    2   17
5:   10   15

And consider a function check I want to apply to each row:

check <- function(x,y) if ((y-x)>10) "A" else "B"

Now if I run this assignment by reference calling the function check in the j section of DT, it fails miserably,

DT[,state:=check(col1,col2)]

And throws this warning

Warning message:
In if ((y - x) > 10) "A" else "B" :
  the condition has length > 1 and only the first element will be used

Obviously, I guessed that data.table processes the whole vector at once and the function needs one value so I thought the last value is the current value in the vector so I made this change, which seems another stupid move :-)

DT[,state:=check(last(col1),last(col2))]

DT

   col1 col2 state
1:    8   20     B
2:    3   11     B
3:    6   19     B
4:    2   17     B
5:   10   15     B

I see the check() function was computed for the last value and overwrote all previous values every time. What I want is this output:

 DT

   col1 col2 state
1:    8   20     A
2:    3   11     A
3:    6   19     A
4:    2   17     A
5:   10   15     B

So how do I make a function call work in a data.table for each row independently?

ACTUAL FUNCTION:
After I received a suggestion from akrun to use ifelse, which works fine for a simple condition like check() but I have a slightly more complicated function here. So please replace check by allowed_state

allowed_state <- function(old=NULL,new=NULL){
legalst<-data.table(from=c(1,1,9,9,7,8,7,10,10,11,11,10,11,8,7),to=c(11,7,10,7,8,7,9,9,7,1,7,1,7,9,10)) # all legal state transitions for a user
if(new %in% legalst[from==old,to]) "Legal" else "Illegal state change"

}

Body:
If I have understood correctly, the OP wants to mark those state changes which are legal or illegal according to a given table legalst of legal state changes.

This can solved using an update on join:

set.seed(21)
DT <- data.table(col1 = sample(x = c(1, 7:11), size = 5),
                 col2 = sample(x = c(1, 7:11), size = 5))
legalst <- data.table(from = c(1,1,9,9,7,8,7,10,10,11,11,10,11,8,7),
                      to = c(11,7,10,7,8,7,9,9,7,1,7,1,7,9,10))

DT[legalst, on = .(col1 = from, col2 = to), state := "Legal"][
  is.na(state), state := "Illegal state change"][]

   col1 col2                state
1:   10   11 Illegal state change
2:    7    1 Illegal state change
3:    8   10 Illegal state change
4:    1    8 Illegal state change
5:   11    7                Legal


问:
ScrollingViewBehavior for ListView
I have two activities using AppBarLayout with a Toolbar and TabLayout from support library 22.

The layout of both is pretty similar: A Toolbar at the top, below it TabLayout, below it a ViewPager containing 3 Fragments.

The first activity's Fragment has a RecyclerView,
the second activity's Fragment is using a ListView instead.

The scrollable Toolbar example from https://github.com/chrisbanes/cheesesquare is working fine on the first activity using the RecyclerView, but on with the ListView.

I've tried created a custom ListViewScrollBehavior that extends AppBarLayout.ScrollingViewBehavior, but so far no luck.
The TouchEvents are passed to the custom class only for horizontal scrolling, but not when scrolling the ListView (vertically).

Any way to use a CoordinatorLayout with ListView?

答:
ListView ScrollingViewBehavior supports only >= 21.

Otherwise you should to write code as below way:

```<code>private int mPreviousVisibleItem;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    listView.setNestedScrollingEnabled(true);
} else {
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem > mPreviousVisibleItem) {
                appBarLayout.setExpanded(false, true);
            } else if (firstVisibleItem < mPreviousVisibleItem) {
                appBarLayout.setExpanded(true, true);
            }
            mPreviousVisibleItem = firstVisibleItem;
        }
    });
}
</code>```

Title: ScrollingViewBehavior for ListView

Body:
ListView ScrollingViewBehavior supports only >= 21.

Otherwise you should to write code as below way:

private int mPreviousVisibleItem;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    listView.setNestedScrollingEnabled(true);
} else {
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem > mPreviousVisibleItem) {
                appBarLayout.setExpanded(false, true);
            } else if (firstVisibleItem < mPreviousVisibleItem) {
                appBarLayout.setExpanded(true, true);
            }
            mPreviousVisibleItem = firstVisibleItem;
        }
    });
}


问:
return array from trait function in laravel
i have a problem , an
error when  return array or  variable from function..
here is my code:

in Traits\UserTrait.php

```<code> public function login()
             {
               $errors   = new MessageBag; // initiate MessageBag
               $username = Input::get('email');
               $password = Input::get('password');
              return compact('username', 'password','email');
             }
</code>```

and
in UserController.php

```<code>       public function __construct(user $model)
        {
         $this->model=$model;

        }
       public function login()
        {
            $this->model->login();
          if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $user = User::where('email',$request['email'])->first();
            if($user && $user->email_active != 1)
            {
                $errors = new MessageBag(['email' => [__('auth.emailVerify')]]);
                return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
            }
}
}
</code>```

actually in user model, i put  use UserTrait;

答:
You might be calling a method that returns something, but you are not actually doing anything with the return at all. (Returning from a method doesn't magically import variables into the callers scope)

```<code>$this->model->login(); // never assigning the result to anything
</code>```

Ofcourse you are getting undefined $username because in UserController@login there is no variable named $username.

This would at least get that username key and assign it to a variable:

```<code>$data = $this->model->login();
$username = $data['username'];
</code>```

Body:
i have a problem , an
error when  return array or  variable from function..
here is my code:

in Traits\UserTrait.php

 public function login()
             {
               $errors   = new MessageBag; // initiate MessageBag
               $username = Input::get('email');
               $password = Input::get('password');
              return compact('username', 'password','email');
             }

and
in UserController.php

       public function __construct(user $model)
        {
         $this->model=$model;

        }
       public function login()
        {
            $this->model->login();
          if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $user = User::where('email',$request['email'])->first();
            if($user && $user->email_active != 1)
            {
                $errors = new MessageBag(['email' => [__('auth.emailVerify')]]);
                return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
            }
}
}

actually in user model, i put  use UserTrait;

Body:
You might be calling a method that returns something, but you are not actually doing anything with the return at all. (Returning from a method doesn't magically import variables into the callers scope)

$this->model->login(); // never assigning the result to anything

Ofcourse you are getting undefined $username because in UserController@login there is no variable named $username.

This would at least get that username key and assign it to a variable:

$data = $this->model->login();
$username = $data['username'];


问:
NPM: After "npm link" module is not found
I'm developing two modules for NodeJS, first one named aligator and second one aligator-methods. Second one depends on first one to work. I'm developing these two modules at the same time and I want to global link aligator so I can use it like it is on npm registry and I just installed it globally. To do this NPM documentation says that I need to use npm link but it's not working.

File package.json of module aligator:

```<code>{
  "name": "aligator",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "private": true,
  "directories": {
    "doc": "docs",
    "example": "examples",
    "test": "spec"
  },
  "scripts": {
    "test": "gulp jasmine"
  },
  "license": "MIT",
  "devDependencies": {
    "gulp": "^3.6.2",
    "gulp-jasmine": "^0.2.0",
    "gulp-jshint": "^1.6.1",
    "gulp-rename": "^1.2.0",
    "jasmine-node": "^1.14.3"
  },
  "dependencies": {
    "bluebird": "^1.2.4",
    "lodash": "^2.4.1",
    "mathjs": "^0.22.0"
  }
}
</code>```

File package.json of module aligator-methods:

```<code>{
 "name": "aligator-methods",
 "version": "0.0.1",
 "description": "",
 "main": "index.js",
 "private": true,
 "directories": {
   "doc": "docs",
   "example": "examples",
   "test": "jasmine"
 },
 "scripts": {
   "test": "gulp jasmine"
 },
 "author": "",
 "license": "MIT",
 "devDependencies": {
   "gulp": "^3.6.2",
   "gulp-jasmine": "^0.2.0",
   "gulp-jshint": "^1.6.1",
   "gulp-rename": "^1.2.0",
   "jasmine-node": "^1.14.3"
 },
 "dependencies": {
   "lodash": "^2.4.1",
   "mathjs": "^0.22.0",
   "aligator": "^0.0.1"
 }
}
</code>```

First of all I linked the module globally:

```<code>$ cd ~/aligator
$ npm link
/usr/local/lib/node_modules/aligator -> /Users/roc/aligator
</code>```

This if I'm not mistaken has created a global reference of my module aligator and now I can use this module from everywhere I want in the computer.

Then I went to the other module and tried to install the dependency but it gave me this output:

```<code>$ cd ~/aligator-methods
$ npm install
npm ERR! 404 404 Not Found: aligator
npm ERR! 404
npm ERR! 404 'aligator' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'aligator-methods'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Darwin 13.2.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/roc/aligator-methods
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.16
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/roc/aligator-methods/npm-debug.log
npm ERR! not ok code 0
</code>```

I even tried to link it directly with:

```<code>$ cd ~/aligator-methods
$ npm link aligator
/Users/roc/aligator-methods/node_modules/aligator -> /usr/local/lib/node_modules/aligator -> /Users/roc/aligator
</code>```

But it didn't work either.

Any thoughts on what it is that could be happening? I read somewhere that maybe it had something to do with my installation of node and npm because it was made by Homebrew and so sometimes I need to use sudo, it seemed unlikely but I tried what they proposed and It didn't work either.

答:
Fix for my version of this issue; in npm v5.3.0, I removed node_modules from repo I was linking into another project.

I found out that after npm v3 they try to put all node_modules dependencies into one node_modules directory (one in your project) to flatten the structure as much as possible (http://codetunnel.io/npm-5-changes-to-npm-link/).

ContentLicense: CC BY-SA 4.0

Body:
I'm developing two modules for NodeJS, first one named aligator and second one aligator-methods. Second one depends on first one to work. I'm developing these two modules at the same time and I want to global link aligator so I can use it like it is on npm registry and I just installed it globally. To do this NPM documentation says that I need to use npm link but it's not working.

File package.json of module aligator:

{
  "name": "aligator",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "private": true,
  "directories": {
    "doc": "docs",
    "example": "examples",
    "test": "spec"
  },
  "scripts": {
    "test": "gulp jasmine"
  },
  "license": "MIT",
  "devDependencies": {
    "gulp": "^3.6.2",
    "gulp-jasmine": "^0.2.0",
    "gulp-jshint": "^1.6.1",
    "gulp-rename": "^1.2.0",
    "jasmine-node": "^1.14.3"
  },
  "dependencies": {
    "bluebird": "^1.2.4",
    "lodash": "^2.4.1",
    "mathjs": "^0.22.0"
  }
}

File package.json of module aligator-methods:

{
 "name": "aligator-methods",
 "version": "0.0.1",
 "description": "",
 "main": "index.js",
 "private": true,
 "directories": {
   "doc": "docs",
   "example": "examples",
   "test": "jasmine"
 },
 "scripts": {
   "test": "gulp jasmine"
 },
 "author": "",
 "license": "MIT",
 "devDependencies": {
   "gulp": "^3.6.2",
   "gulp-jasmine": "^0.2.0",
   "gulp-jshint": "^1.6.1",
   "gulp-rename": "^1.2.0",
   "jasmine-node": "^1.14.3"
 },
 "dependencies": {
   "lodash": "^2.4.1",
   "mathjs": "^0.22.0",
   "aligator": "^0.0.1"
 }
}

First of all I linked the module globally:

$ cd ~/aligator
$ npm link
/usr/local/lib/node_modules/aligator -> /Users/roc/aligator

This if I'm not mistaken has created a global reference of my module aligator and now I can use this module from everywhere I want in the computer.

Then I went to the other module and tried to install the dependency but it gave me this output:

$ cd ~/aligator-methods
$ npm install
npm ERR! 404 404 Not Found: aligator
npm ERR! 404
npm ERR! 404 'aligator' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'aligator-methods'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Darwin 13.2.0
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/roc/aligator-methods
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.16
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/roc/aligator-methods/npm-debug.log
npm ERR! not ok code 0

I even tried to link it directly with:

$ cd ~/aligator-methods
$ npm link aligator
/Users/roc/aligator-methods/node_modules/aligator -> /usr/local/lib/node_modules/aligator -> /Users/roc/aligator

But it didn't work either.

Any thoughts on what it is that could be happening? I read somewhere that maybe it had something to do with my installation of node and npm because it was made by Homebrew and so sometimes I need to use sudo, it seemed unlikely but I tried what they proposed and It didn't work either.


问:
How to get the smallest list?
So I got four Lists:

```<code>1, 2, 3, 4
1, 2, 3
1, 2
1, 2, 3, 4, 5
</code>```

What is the easiest way of getting the one with smallest size in elements (list.size())?

答:
I think the optimal solution would be as follows

```<code> public static ArrayList<Integer> getSmallestList(ArrayList<Integer>... input) {
            ArrayList<Integer> returnValue = null;
            if (input.length > 0) {
                returnValue = input[0];

                for (ArrayList<Integer> inputIterator : input) {
                    if (inputIterator.size() < returnValue.size()) {
                        returnValue = inputIterator;
                    }
                }
            }
            else
            {
                System.out.println("No input provided");
            }
            return returnValue;
        }
</code>```

The ... parameter allows the method to be called with any amount of variables you like.

Title: How to get the smallest list?

Body:
So I got four Lists:

1, 2, 3, 4
1, 2, 3
1, 2
1, 2, 3, 4, 5

What is the easiest way of getting the one with smallest size in elements (list.size())?

Body:
I think the optimal solution would be as follows

 public static ArrayList<Integer> getSmallestList(ArrayList<Integer>... input) {
            ArrayList<Integer> returnValue = null;
            if (input.length > 0) {
                returnValue = input[0];

                for (ArrayList<Integer> inputIterator : input) {
                    if (inputIterator.size() < returnValue.size()) {
                        returnValue = inputIterator;
                    }
                }
            }
            else
            {
                System.out.println("No input provided");
            }
            return returnValue;
        }

The ... parameter allows the method to be called with any amount of variables you like.


问:
Page loads too slow because of Wistia embedded videos
My website is having lots of Wistia videos, embedded in an iframe, whenever I load my page for the first time, It's taking a lot of time which makes my website slow, Is there any way I can load the video whenever I click on that particular videos.

This is small code snippet

```<code><ul>
 <li>
    <a href="#" class="toggle">Operations</a>
    <ul class="inner ulmargin">
    <iframe src=" https://fast.wistia.net/embed/iframe/b8?seo=false" allowtransparency="true" frameborder="0" scrolling="no" class="wistia_embed" id="wistia_4d8229898d"  name="wistia_embed" allowfullscreen mozallowfullscreen webkitallowfullscreen oallowfullscreen msallowfullscreen width="280" height="200"></iframe>
   </ul>
 </li>
<ul>
</code>```

Above is just an example of one video, I have lots of videos inside that UL command.
Any advice and suggestions will be greatly appreciated.

答:
Take a look here, here i have many videos. But it loads fast, copy my code and paste in a html file and run

```

Body:
My website is having lots of Wistia videos, embedded in an iframe, whenever I load my page for the first time, It's taking a lot of time which makes my website slow, Is there any way I can load the video whenever I click on that particular videos.

This is small code snippet

    Operations

Above is just an example of one video, I have lots of videos inside that UL command.
Any advice and suggestions will be greatly appreciated.

Body:
Take a look here, here i have many videos. But it loads fast, copy my code and paste in a html file and run

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
html {
    background-color: #f3f3f3;
}
.wrapper {
    max-width: 680px;
    margin: 60px auto;
    padding: 0 20px;
}

.youtube {
    background-color: #000;
    margin-bottom: 30px;
    position: relative;
    padding-top: 56.25%;
    overflow: hidden;
    cursor: pointer;
}
.youtube img {
    width: 100%;
    top: -16.82%;
    left: 0;
    opacity: 0.7;
}
.youtube .play-button {
    width: 90px;
    height: 60px;
    background-color: #333;
    box-shadow: 0 0 30px rgba( 0,0,0,0.6 );
    z-index: 1;
    opacity: 0.8;
    border-radius: 6px;
}
.youtube .play-button:before {
    content: "";
    border-style: solid;
    border-width: 15px 0 15px 26.0px;
    border-color: transparent transparent transparent #fff;
}
.youtube img,
.youtube .play-button {
    cursor: pointer;
}
.youtube img,
.youtube iframe,
.youtube .play-button,
.youtube .play-button:before {
    position: absolute;
}
.youtube .play-button,
.youtube .play-button:before {
    top: 50%;
    left: 50%;
    transform: translate3d( -50%, -50%, 0 );
}
.youtube iframe {
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
}
</style>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/><div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<div class="wrapper">
    <div class="youtube" data-embed="AqcjdkPMPJA">
        <div class="play-button"></div>
    </div>
</div><br/>
<script>
( function() {

var youtube = document.querySelectorAll( ".youtube" );

for (var i = 0; i < youtube.length; i++) {

var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/sddefault.jpg";

var image = new Image();
image.src = source;
image.addEventListener( "load", function() {
youtube[ i ].appendChild( image );
}( i ) );

youtube[i].addEventListener( "click", function() {

var iframe = document.createElement( "iframe" );

        iframe.setAttribute( "frameborder", "0" );
        iframe.setAttribute( "allowfullscreen", "" );
        iframe.setAttribute( "src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1" );

        this.innerHTML = "";
        this.appendChild( iframe );
} );
};

} )();
</script>


问:
Understanding overload resolution ranking involving user defined conversion
I am trying to understand overload resolution.

First let's consider this first case:

```<code>struct int1{
   int val;
   operator int&()&{
      return val;
      }
   operator const int &() const&{
      return val;
      }
    };

void f(int &){}       //f#1
void f(const int&){}  //f#2

void test1(){
  int1 x;
  f(x);
   //Conversion sequence for f#1:
   //   - int_wrapper& --> int1::operator int&
   //   => Ranking: user defined conversion rank
   //Converison sequence for f#2:
   //   - int1& --> int1::operator int & --> const int&
   //   - int1& --> const int1 &         --> int1::operator const int&
   //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
   //            => user defined conversion rank
   //
   //=> No best viable overload, 2 user defined conversion rank
}
</code>```

Unlike my wrong analysis, compilers agrees: the call to f is not ambiguous. Why?

Now consider this second case, which is very similar, I just replace the int& by int &&:

```<code>struct int2{
   int val;
   operator int&&()&&{
      return std::move(val);
      }
   operator const int &() const&{
      return val;
      }
    };

void g(int &&){}     // g#1
void g(const int&){} // g#2

void test2(){
  int2 x;
  g(std::move(x));
  //Conversions sequence for g#1
  //   - int2&& --> int2::operator int&&
  //   => Ranking: user defined conversion rank
  //Conversion sequence for g#2
  //   - int2&& --> const int2&           --> int2::operator const int&
  //   - int2&& --> int2::operator int&&  --> const int&
  //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
  //            => user defined conversion rank
  //
  //=> No best viable overload, 2 user defined conversion rank
  }
</code>```

My analysis (which is certainly wrong in this case too) concludes similarly that the call to g is ambiguous. Unfortunatly, in this second case, compilers do not agree:

Clang (3.4.1 to 5.0), MSVC 19 2017 RTW, Zapcc 190308 (Clang derivate), ellcc (0.1.33, 0.1.34)(Clang derivate) => call to g is ambiguous;

GCC (4.8.1 to 7.2), icc (16 to 18) => call to g is not ambiguous.

What is the right analysis and which compiler is right?

Could you precise why the rule below does not apply, or when is it applied?

[over.best.ics]/10:

If several different sequences of conversions exist that each convert the argument to the parameter type, the
  implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence
  designated the
  ambiguous conversion sequence
  . For the purpose of ranking implicit conversion sequences as
  described in 16.3.3.2, the ambiguous conversion sequence is treated as a user-defined conversion sequence
  that is indistinguishable from any other user-defined conversion sequence

答:
Both of these examples are more complicated representations of simpler underlying concepts:

```<code>void f(int& );        // #1
void f(int const& );  // #2
void g(int&& );       // #3
void g(int const& );  // #4

int i;
f(i); // calls #1
g(0); // calls #3
</code>```

For the first call, we favor the the less cv-qualified type, so int& is better than int const&.  For the second call, we favor binding to rvalue reference over binding to lvalue reference, so int&& is better than int const&.

In the specific example, these preferences manifest themselves over the choice of conversion function used by way of the implicit object parameter. For the first example, because we're binding the implicit object parameter to int1& for converting to int&, but int1 const& for converting to int const&. Likewise, in the second example, we're binding the implicit object parameter to int2&& for converting to int&&, but int2 const& for converting to int const&.

I'd call this a clang bug.

Body:
I am trying to understand overload resolution.

First let's consider this first case:

struct int1{
   int val;
   operator int&()&{
      return val;
      }
   operator const int &() const&{
      return val;
      }
    };

void f(int &){}       //f#1
void f(const int&){}  //f#2

void test1(){
  int1 x;
  f(x);
   //Conversion sequence for f#1:
   //   - int_wrapper& --> int1::operator int&
   //   => Ranking: user defined conversion rank
   //Converison sequence for f#2:
   //   - int1& --> int1::operator int & --> const int&
   //   - int1& --> const int1 &         --> int1::operator const int&
   //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
   //            => user defined conversion rank
   //
   //=> No best viable overload, 2 user defined conversion rank
}

Unlike my wrong analysis, compilers agrees: the call to f is not ambiguous. Why?

Now consider this second case, which is very similar, I just replace the int& by int &&:

struct int2{
   int val;
   operator int&&()&&{
      return std::move(val);
      }
   operator const int &() const&{
      return val;
      }
    };

void g(int &&){}     // g#1
void g(const int&){} // g#2

void test2(){
  int2 x;
  g(std::move(x));
  //Conversions sequence for g#1
  //   - int2&& --> int2::operator int&&
  //   => Ranking: user defined conversion rank
  //Conversion sequence for g#2
  //   - int2&& --> const int2&           --> int2::operator const int&
  //   - int2&& --> int2::operator int&&  --> const int&
  //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
  //            => user defined conversion rank
  //
  //=> No best viable overload, 2 user defined conversion rank
  }

My analysis (which is certainly wrong in this case too) concludes similarly that the call to g is ambiguous. Unfortunatly, in this second case, compilers do not agree:

Clang (3.4.1 to 5.0), MSVC 19 2017 RTW, Zapcc 190308 (Clang derivate), ellcc (0.1.33, 0.1.34)(Clang derivate) => call to g is ambiguous;

GCC (4.8.1 to 7.2), icc (16 to 18) => call to g is not ambiguous.

What is the right analysis and which compiler is right?

Could you precise why the rule below does not apply, or when is it applied?

[over.best.ics]/10:

If several different sequences of conversions exist that each convert the argument to the parameter type, the
  implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence
  designated the
  ambiguous conversion sequence
  . For the purpose of ranking implicit conversion sequences as
  described in 16.3.3.2, the ambiguous conversion sequence is treated as a user-defined conversion sequence
  that is indistinguishable from any other user-defined conversion sequence

Body:
Both of these examples are more complicated representations of simpler underlying concepts:

void f(int& );        // #1
void f(int const& );  // #2
void g(int&& );       // #3
void g(int const& );  // #4

int i;
f(i); // calls #1
g(0); // calls #3

For the first call, we favor the the less cv-qualified type, so int& is better than int const&.  For the second call, we favor binding to rvalue reference over binding to lvalue reference, so int&& is better than int const&.

In the specific example, these preferences manifest themselves over the choice of conversion function used by way of the implicit object parameter. For the first example, because we're binding the implicit object parameter to int1& for converting to int&, but int1 const& for converting to int const&. Likewise, in the second example, we're binding the implicit object parameter to int2&& for converting to int&&, but int2 const& for converting to int const&.

I'd call this a clang bug.


问:
Import error: cannot import name 'opentype'
I'm trying to follow the instructions for utilizing Firebase in my py code running on Raspberry Pi 2 B+. While running on python 3, bad stuff happens.

I have included the pyrebase in my script but when I run it using python3 I get following instead (see below please). I have been working on various other languages but I just picked python and Raspberry Pi for a project that I had in mind.

This post will have both my code and the terminal output that I get when I run the code

My Code:

```<code>#import Libraries
import RPi.GPIO as GPIO
import time
import pyrebase
import os

#Firebase Configuration
config = {
          "apiKey": "apiKey",
          "authDomain": "rpitest-xxxxx.firebaseapp.com",
          "databaseURL": "rpitest-xxxxx.firebaseio.com",
          "storageBucket": "rpitest-xxxxx.appspot.com"
}

firebase = pyrebase.initialize_app(config)

#GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO.OUT)

#Firebase Database Intialization
db = firebase.database()

#While loop to run until user kills program
while(True):
    #Get value of LED
    led = db.child("led").get()

    #Sort through children of LED(we only have one)
    for user in led.each():
    #Check value of child(which is 'state')
      if(user.val() == "OFF"):
          #If value is off, turn LED off
          GPIO.output(22, False)
      else:
          #If value is not off(implies it's on), turn LED on
          GPIO.output(22, True)

      #0.1 Second Delay
      time.sleep(0.1)
</code>```

The Command:

```<code>    pi@raspberrypi:~/Desktop/LearnPython $ sudo python3 IoTLED.py
</code>```

The Output:

```<code>    pi@raspberrypi:~/Desktop/LearnPython $ sudo python3 IoTLED.py
    Traceback (most recent call last):
      File "IoTLED.py", line 4, in <module>
        import pyrebase
      File "/usr/local/lib/python3.5/distpackages/pyrebase/__init__.py", line 1, in <module>
        from .pyrebase import initialize_app
      File "/usr/local/lib/python3.5/distpackages/pyrebase/pyrebase.py", line 17, in <module>
        from oauth2client.service_account import ServiceAccountCredentials
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/service_account.py", line 26, in <module>
        from oauth2client import crypt
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/crypt.py", line 23, in <module>
        from oauth2client import _pure_python_crypt
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/_pure_python_crypt.py", line 24, in <module>
        from pyasn1_modules.rfc2459 import Certificate
      File "/usr/local/lib/python3.5/dist-packages/pyasn1_modules/rfc2459.py", line 20, in <module>
        from pyasn1.type import opentype
      ImportError: cannot import name 'opentype'
</code>```

My Suspicions:

I suspect the opentype library is missing.

End Remarks:

I am really really really stuck at this point for more than a day now. I need help. Thank you so much and I really appreciate your help.

答:
You can try this also. It worked for me. </p>

```<code>pip install --upgrade pyasn1-modules
</code>```

Body:
I'm trying to follow the instructions for utilizing Firebase in my py code running on Raspberry Pi 2 B+. While running on python 3, bad stuff happens.

I have included the pyrebase in my script but when I run it using python3 I get following instead (see below please). I have been working on various other languages but I just picked python and Raspberry Pi for a project that I had in mind.

This post will have both my code and the terminal output that I get when I run the code

My Code:

#import Libraries
import RPi.GPIO as GPIO
import time
import pyrebase
import os

#Firebase Configuration
config = {
          "apiKey": "apiKey",
          "authDomain": "rpitest-xxxxx.firebaseapp.com",
          "databaseURL": "rpitest-xxxxx.firebaseio.com",
          "storageBucket": "rpitest-xxxxx.appspot.com"
}

firebase = pyrebase.initialize_app(config)

#GPIO Setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(22, GPIO.OUT)

#Firebase Database Intialization
db = firebase.database()

#While loop to run until user kills program
while(True):
    #Get value of LED
    led = db.child("led").get()

    #Sort through children of LED(we only have one)
    for user in led.each():
    #Check value of child(which is 'state')
      if(user.val() == "OFF"):
          #If value is off, turn LED off
          GPIO.output(22, False)
      else:
          #If value is not off(implies it's on), turn LED on
          GPIO.output(22, True)

      #0.1 Second Delay
      time.sleep(0.1)

The Command:

    pi@raspberrypi:~/Desktop/LearnPython $ sudo python3 IoTLED.py

The Output:

    pi@raspberrypi:~/Desktop/LearnPython $ sudo python3 IoTLED.py
    Traceback (most recent call last):
      File "IoTLED.py", line 4, in <module>
        import pyrebase
      File "/usr/local/lib/python3.5/distpackages/pyrebase/__init__.py", line 1, in <module>
        from .pyrebase import initialize_app
      File "/usr/local/lib/python3.5/distpackages/pyrebase/pyrebase.py", line 17, in <module>
        from oauth2client.service_account import ServiceAccountCredentials
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/service_account.py", line 26, in <module>
        from oauth2client import crypt
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/crypt.py", line 23, in <module>
        from oauth2client import _pure_python_crypt
      File "/usr/local/lib/python3.5/dist-packages/oauth2client/_pure_python_crypt.py", line 24, in <module>
        from pyasn1_modules.rfc2459 import Certificate
      File "/usr/local/lib/python3.5/dist-packages/pyasn1_modules/rfc2459.py", line 20, in <module>
        from pyasn1.type import opentype
      ImportError: cannot import name 'opentype'

My Suspicions:

I suspect the opentype library is missing.

End Remarks:

I am really really really stuck at this point for more than a day now. I need help. Thank you so much and I really appreciate your help.

Body:
You can try this also. It worked for me.

pip install --upgrade pyasn1-modules


问:
Fill in web form from an app and submit
I have a webpage with a simple form with 3 input fields, Name, Email and Course and a submit button. Nothing fancy.

Upon developing an android app, I would like to know how I could fill in that web form from within my android app without using a webview to actually load the webpage.

答:
Add this dependency in your build.gradle(Module:app)

```<code>dependencies {
implementation 'com.android.support:customtabs:27.0.2'
}
</code>```

Add this method in Activity.

```<code>public boolean isPackageExisted(String targetPackage){
PackageManager pm=getPackageManager();
    try {
        PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}
</code>```

Add this onCreate of Activity

```<code>if (isPackageExisted("com.android.chrome")){
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.setPackage("com.android.chrome");
customTabsIntent.intent.setAction(Intent.ACTION_VIEW);
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
customTabsIntent.launchUrl(getApplicationContext(), Uri.parse("Your URL"));
}
</code>```

Title: Fill in web form from an app and submit

Body:
Add this dependency in your build.gradle(Module:app)

dependencies {
implementation 'com.android.support:customtabs:27.0.2'
}

Add this method in Activity.

public boolean isPackageExisted(String targetPackage){
PackageManager pm=getPackageManager();
    try {
        PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}

Add this onCreate of Activity

if (isPackageExisted("com.android.chrome")){
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.setPackage("com.android.chrome");
customTabsIntent.intent.setAction(Intent.ACTION_VIEW);
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
customTabsIntent.launchUrl(getApplicationContext(), Uri.parse("Your URL"));
}


问:
How to execute multiple unix commands using Java and capture individual output or error if any
I have got this requirement where I need to execute a list of unix commands and then against each command I should store its result.
Eg.
Commands - cd dir1, pwd, ls

My output should contain -

cd dir1-
pwd-dir1
ls-a, b, c, d(assume these are present under dir1 directory)

I tried using JSch library and tried using shell and exec channel types.

But this does not allow me to send a command and read output and then send another and read output.

What I did as of now is
Using exec send all the commands and an echo command after each command and then read till that echo for that command output.

Using shell I sent commands but it waits for an exit command other wise it goes to infinite wait.

Also how can we get the error for individual commands

Please suggest if there is any way to achieve this.

答:
If the commands are independent, open a new "exec" channel for each.

If the later commands depend on previous commands, there's no nice solution.

You have actually already found the best way:

What I did as of now is Using exec send all the commands and an echo command after each command and then read till that echo for that command output.

See also JSch Shell channel execute commands one by one testing result before proceeding.