问:
Perl XML LibXML to replace a node with the other on xsd schema
I have an XML Schema and I would like to replace the RootNode with the element found inside of the RootNode complex Type with.

For example, below expected result is to have the <xs:element name="RootNode" ...> replaced by <xs:element name="real_node" type="RealNode"/> and remove the whole node of <xs:complexType name="RootNode">.

XML Schema:

```<code><xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="RootNode" type="RootNode"/>

    <xs:complexType name="RootNode">
            <xs:sequence>
                    <xs:element name="real_node" type="RealNode"/>
            </xs:sequence>
    </xs:complexType>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>
</code>```

Expected result:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>
</code>```

My script:

```<code>#!/opt/perl/bin/perl -w
use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );
use File::Copy;
use File::Basename;

my $in_qfn  = $ARGV[0];
my ($parser, $doc, $root, $out_qfn);
my ($name, $path, $suffix);
my ($documentroot, $complexdoc, $copyelem, $test, $fnd_type, $parent);

my @files = glob "$in_qfn/*.xsd";

foreach my $file (@files) {
   print "###LI### 1 $file\n";
   ($name, $path, $suffix) = fileparse($file);
   $out_qfn = "${name}NoRoot.${suffix}";

   $parser = XML::LibXML->new();
   $doc    = $parser->parse_file($file);
   $root   = $doc->documentElement();

   my $xpc = XML::LibXML::XPathContext->new($doc);
   $xpc->registerNs('xsd', 'http://www.w3.org/2001/XMLSchema');

   # Get the RootNode element node and delete it
   foreach $test ($xpc->findnodes("//xsd:element", $root)) {
      $fnd_type = $test->getAttribute('type') or next;

      if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) {
         foreach my $fnd_node ($xpc->findnodes('./@name[.="RootNode"]', $test)) {
            $fnd_type = $fnd_node->getAttribute('type') or next;
            $parent = $fnd_node->[0]->parentNode;
            $parent->removeChild($fnd_node->[0]);
         }
      }
   }

   # Get the RootNode Complext Type node
   foreach $test ($xpc->findnodes("//xsd:complexType", $root)) {
      if ($xpc->findnodes('./@name[.="RootNode"]', $root)) {
         $complexdoc = $xpc->findnodes('./@name[.="RootNode"]', $root);
         $copyelem = $xpc->findnodes("//xsd:element", $complexdoc);
         # Copy the element node within RootNode node to the top level
         $root->appendChild($copyelem->cloneNode(1));
      }
   }

   $doc->toFile($out_qfn);
}
</code>```

However, the script throws error:

```<code>Can't locate object method "getAttribute" via package "XML::LibXML::NodeList"
</code>```

Any help is appreciated.

答:
A call to findnodes in list context will return a list of matching nodes. That is how your first loop

foreach $test ($xpc->findnodes("//xsd:element", $root)) { ... }
```

<p>works, because <code>for</code> applies list context to the expression in parentheses</p>

<p>However, your second loop</p>

<pre class="lang-none prettyprint-override"><code>foreach my $fnd_node ($documentroot = $xpc->findnodes('./@name[.="RootNode"]', $test)) { ... }
</code>```

puts findnodes into scalar context because you first assign the result to $documentroot. That causes findnodes to return an XML::LibXML::NodeList object instead of a list of nodes, and the loop will iterate just once, setting $fnd_node to that object and causing the errors you see

I'm unclear why you have added the assignment to $documentroot, as it will just set both $documentroot and $fnd_node to the same value, which hass no advantage. Your errors would go away if you removed that assignment and replaced $documentroot with$fnd_node in the body of the loop

By the way, there is no need for the test

if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) { ... }
```

<p>before looping over the same call to <code>findnodes</code>. If the call finds no matching nodes then the <code>for</code> loop won't execute at all</p>

<p><br/></p>

<hr>

<h3>Update</h3>

<p>There were a few other problems with your program. For instance you didn't delete the original <code><xs:complexType name="RootNode"></code> element, and you inserted the contained <code><xs:element name="real_node" type="RealNode"/></code> at the end of the file</p>

<p>I've fixed your code like this</p>

<pre class="lang-perl prettyprint-override"><code>#!/opt/perl/bin/perl
use strict;
use warnings 'all';

use XML::LibXML ();
use XML::LibXML::XPathContext ();
use File::Copy;
use File::Basename;

my ($in_qfn) = @ARGV;

my @files = $in_qfn ? glob "$in_qfn/*.xsd" : 'test.xsd';

for my $file ( @files ) {

    print "###LI### 1 $file\n";

    my ( $name, $path, $suffix ) = fileparse( $file, qr/\.[^.]*/ );
    my $out_qfn = "${name}NoRoot${suffix}";

    print "###LO### 1 $out_qfn\n";

    my $parser = XML::LibXML->new();
    my $doc    = $parser->parse_file( $file );
    my $root   = $doc->documentElement();

    my $xpc = XML::LibXML::XPathContext->new( $doc );
    $xpc->registerNs( 'xsd', 'http://www.w3.org/2001/XMLSchema' );

    # Get the RootNode element node and delete it
    for my $element_root ( $xpc->findnodes( '//xsd:element[@name="RootNode"]', $root ) ) {
        my $parent = $element_root->parentNode;
        $parent->removeChild( $element_root );
    }

    # Get the RootNode Complex Type node
    for my $complex_root ( $xpc->findnodes( '//xsd:complexType[@name="RootNode"]', $root ) ) {

        my ($copyelem) = $xpc->findnodes( ".//xsd:element", $complex_root );

        # Copy the element node within RootNode node to the top level
        $root->insertBefore(
            $copyelem->cloneNode( 1 ),
            $root->firstChild
        );

        # Put a newline before the cloned copy
        $root->insertBefore(
            XML::LibXML::Text->new( "\n\n    " ),
            $root->firstChild
        );

        # Remove the <xs:complexType name="RootNode">
        $complex_root->parentNode->removeChild($complex_root);
    }

    $doc->toFile( $out_qfn );
}
</code>```

output

<?xml version="1.0"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">

    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99"/>
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>
```

Body:
I have an XML Schema and I would like to replace the RootNode with the element found inside of the RootNode complex Type with.

For example, below expected result is to have the <xs:element name="RootNode" ...> replaced by <xs:element name="real_node" type="RealNode"/> and remove the whole node of <xs:complexType name="RootNode">.

XML Schema:

<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="RootNode" type="RootNode"/>

    <xs:complexType name="RootNode">
            <xs:sequence>
                    <xs:element name="real_node" type="RealNode"/>
            </xs:sequence>
    </xs:complexType>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>

Expected result:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>

My script:

#!/opt/perl/bin/perl -w
use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );
use File::Copy;
use File::Basename;

my $in_qfn  = $ARGV[0];
my ($parser, $doc, $root, $out_qfn);
my ($name, $path, $suffix);
my ($documentroot, $complexdoc, $copyelem, $test, $fnd_type, $parent);

my @files = glob "$in_qfn/*.xsd";

foreach my $file (@files) {
   print "###LI### 1 $file\n";
   ($name, $path, $suffix) = fileparse($file);
   $out_qfn = "${name}NoRoot.${suffix}";

   $parser = XML::LibXML->new();
   $doc    = $parser->parse_file($file);
   $root   = $doc->documentElement();

   my $xpc = XML::LibXML::XPathContext->new($doc);
   $xpc->registerNs('xsd', 'http://www.w3.org/2001/XMLSchema');

   # Get the RootNode element node and delete it
   foreach $test ($xpc->findnodes("//xsd:element", $root)) {
      $fnd_type = $test->getAttribute('type') or next;

      if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) {
         foreach my $fnd_node ($xpc->findnodes('./@name[.="RootNode"]', $test)) {
            $fnd_type = $fnd_node->getAttribute('type') or next;
            $parent = $fnd_node->[0]->parentNode;
            $parent->removeChild($fnd_node->[0]);
         }
      }
   }

   # Get the RootNode Complext Type node
   foreach $test ($xpc->findnodes("//xsd:complexType", $root)) {
      if ($xpc->findnodes('./@name[.="RootNode"]', $root)) {
         $complexdoc = $xpc->findnodes('./@name[.="RootNode"]', $root);
         $copyelem = $xpc->findnodes("//xsd:element", $complexdoc);
         # Copy the element node within RootNode node to the top level
         $root->appendChild($copyelem->cloneNode(1));
      }
   }

   $doc->toFile($out_qfn);
}

However, the script throws error:

Can't locate object method "getAttribute" via package "XML::LibXML::NodeList"

Any help is appreciated.

Body:
A call to findnodes in list context will return a list of matching nodes. That is how your first loop

foreach $test ($xpc->findnodes("//xsd:element", $root)) { ... }

works, because for applies list context to the expression in parentheses

However, your second loop

foreach my $fnd_node ($documentroot = $xpc->findnodes('./@name[.="RootNode"]', $test)) { ... }

puts findnodes into scalar context because you first assign the result to $documentroot. That causes findnodes to return an XML::LibXML::NodeList object instead of a list of nodes, and the loop will iterate just once, setting $fnd_node to that object and causing the errors you see

I'm unclear why you have added the assignment to $documentroot, as it will just set both $documentroot and $fnd_node to the same value, which hass no advantage. Your errors would go away if you removed that assignment and replaced $documentroot with$fnd_node in the body of the loop

By the way, there is no need for the test

if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) { ... }

before looping over the same call to findnodes. If the call finds no matching nodes then the for loop won't execute at all

Update

There were a few other problems with your program. For instance you didn't delete the original <xs:complexType name="RootNode"> element, and you inserted the contained <xs:element name="real_node" type="RealNode"/> at the end of the file

I've fixed your code like this

#!/opt/perl/bin/perl
use strict;
use warnings 'all';

use XML::LibXML ();
use XML::LibXML::XPathContext ();
use File::Copy;
use File::Basename;

my ($in_qfn) = @ARGV;

my @files = $in_qfn ? glob "$in_qfn/*.xsd" : 'test.xsd';

for my $file ( @files ) {

    print "###LI### 1 $file\n";

    my ( $name, $path, $suffix ) = fileparse( $file, qr/\.[^.]*/ );
    my $out_qfn = "${name}NoRoot${suffix}";

    print "###LO### 1 $out_qfn\n";

    my $parser = XML::LibXML->new();
    my $doc    = $parser->parse_file( $file );
    my $root   = $doc->documentElement();

    my $xpc = XML::LibXML::XPathContext->new( $doc );
    $xpc->registerNs( 'xsd', 'http://www.w3.org/2001/XMLSchema' );

    # Get the RootNode element node and delete it
    for my $element_root ( $xpc->findnodes( '//xsd:element[@name="RootNode"]', $root ) ) {
        my $parent = $element_root->parentNode;
        $parent->removeChild( $element_root );
    }

    # Get the RootNode Complex Type node
    for my $complex_root ( $xpc->findnodes( '//xsd:complexType[@name="RootNode"]', $root ) ) {

        my ($copyelem) = $xpc->findnodes( ".//xsd:element", $complex_root );

        # Copy the element node within RootNode node to the top level
        $root->insertBefore(
            $copyelem->cloneNode( 1 ),
            $root->firstChild
        );

        # Put a newline before the cloned copy
        $root->insertBefore(
            XML::LibXML::Text->new( "\n\n    " ),
            $root->firstChild
        );

        # Remove the <xs:complexType name="RootNode">
        $complex_root->parentNode->removeChild($complex_root);
    }

    $doc->toFile( $out_qfn );
}

output

<?xml version="1.0"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">

    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99"/>
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>


来源: stackexchange

问:
Background Blur - CSS
Hello I try to make this background Blur like this image so I'd like to know if I can do it using CSS3 only or I need to use Javascript & Jquery:

And if I will use css only How to make the blur is responsive.

Here my simple code:

#bg{
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

#bg {
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-bg {
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 99;
  /* Pull the background 70px higher to the same place as #bg's */
  /*background-position: center -70px;*/
  -webkit-filter: blur(10px);
  filter: blur(10px);
}

#search {
  position: relative;
  z-index: 100;
  padding: 20px;
  background: rgba(34,34,34,0.75);
}
#search h2{
    color:#ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg">
        <div id="search-container">
            <div id="search-bg"></div>
            <div id="search">
                <h2>Hello World</h2>
            </div>
        </div>
    </div></code>```

答:
To blur all the background

You can't easily attach effect to a background image. You should blur it with a software and set it as background-image.

You can have a blur background in css with a div placing behind yout site content, and blur this div like that :
http://codepen.io/aniketpant/pen/DsEve

```<code><div class="background-image"></div>
<div class="content"> Your text </div>
</code>```

Blur behind an element

You can get this result with CSS3 backdrop filter:

https://webkit.org/blog/3632/introducing-backdrop-filters/

ContentLicense: CC BY-SA 3.0

Title: Background Blur - CSS

Body:
Hello I try to make this background Blur like this image so I'd like to know if I can do it using CSS3 only or I need to use Javascript & Jquery:

And if I will use css only How to make the blur is responsive.

Here my simple code:

#bg{
  background-image: url('http://store6.up-00.com/2017-03/149079039538851.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}

#bg {
  background-position: center top;
  padding: 70px 90px 120px 90px;
}

#search-container {
  position: relative;
}

#search-bg {
  /* Absolutely position it, but stretch it to all four corners, then put it just behind #search's z-index */
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: 99;
  /* Pull the background 70px higher to the same place as #bg's */
  /*background-position: center -70px;*/
  -webkit-filter: blur(10px);
  filter: blur(10px);
}

#search {
  position: relative;
  z-index: 100;
  padding: 20px;
  background: rgba(34,34,34,0.75);
}
#search h2{
    color:#ffffff;
}

Hello World

Body:
To blur all the background

You can't easily attach effect to a background image. You should blur it with a software and set it as background-image.

You can have a blur background in css with a div placing behind yout site content, and blur this div like that :
http://codepen.io/aniketpant/pen/DsEve

<div class="background-image"></div>
<div class="content"> Your text </div>

Blur behind an element

You can get this result with CSS3 backdrop filter:

https://webkit.org/blog/3632/introducing-backdrop-filters/


问:
aggregate by count in r
I have a dataset as below:

```<code>Group   Class
  A       1
  A       2
  A       1
  A       1
  B       2
  B       2
  B       2
  B       1
  B       3
  B       1
  C       1
  C       1
  C       1
  C       2
  C       3
</code>```

I want to aggregate the table by the ‘Group’ column and the value on the ‘Class’ column would be the Class with maximum count. For instance, for Group A, 1 appears three times, so the value for Class is 1. Similarly, for Group 2, 2 appears three times, so the value for Class is 2. The result table should be the following:

```<code>Group   Class
  A       1
  B       2
  C       1
</code>```

I am new to R programming and would appreciate your help in solving this problem. Thanks!

答:
You could also do this without using aggregate, so using table and max.col instead:

```<code>tb <- table(df$Group, df$Class)
data.frame("Group"=rownames(tb), "CLass"=max.col(tb))

#  Group CLass
#1     A     1
#2     B     2
#3     C     1
</code>```

Which seems to be faster:

```<code>library(microbenchmark)

# by Ronak Shah in comments
f1 <- function(df) aggregate(Class~Group, df, function(x) which.max(table(x)))
# this answer
f2 <- function(df) {tb <- table(df$Group, df$Class);
 data.frame("Group"=rownames(tb), "CLass"=max.col(tb));}

all(f1(df)==f2(df))
# [1] TRUE

microbenchmark(f1(df), f2(df))

# Unit: microseconds
   # expr     min       lq     mean   median      uq      max neval
 # f1(df) 800.153 838.9130 923.6484 870.0115 918.988 1981.901   100
 # f2(df) 298.367 319.0995 353.4915 338.6305 380.246  599.439   100
</code>```

```<code>df <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"),
    Class = c(1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 3L, 1L, 1L, 1L,
    1L, 2L, 3L)), .Names = c("Group", "Class"), class = "data.frame", row.names = c(NA,
-15L))
</code>```

Title: aggregate by count in r

Body:
I have a dataset as below:

Group   Class
  A       1
  A       2
  A       1
  A       1
  B       2
  B       2
  B       2
  B       1
  B       3
  B       1
  C       1
  C       1
  C       1
  C       2
  C       3

I want to aggregate the table by the ‘Group’ column and the value on the ‘Class’ column would be the Class with maximum count. For instance, for Group A, 1 appears three times, so the value for Class is 1. Similarly, for Group 2, 2 appears three times, so the value for Class is 2. The result table should be the following:

Group   Class
  A       1
  B       2
  C       1

I am new to R programming and would appreciate your help in solving this problem. Thanks!

Body:
You could also do this without using aggregate, so using table and max.col instead:

tb <- table(df$Group, df$Class)
data.frame("Group"=rownames(tb), "CLass"=max.col(tb))

#  Group CLass
#1     A     1
#2     B     2
#3     C     1

Which seems to be faster:

library(microbenchmark)

# by Ronak Shah in comments
f1 <- function(df) aggregate(Class~Group, df, function(x) which.max(table(x)))
# this answer
f2 <- function(df) {tb <- table(df$Group, df$Class);
 data.frame("Group"=rownames(tb), "CLass"=max.col(tb));}

all(f1(df)==f2(df))
# [1] TRUE

microbenchmark(f1(df), f2(df))

# Unit: microseconds
   # expr     min       lq     mean   median      uq      max neval
 # f1(df) 800.153 838.9130 923.6484 870.0115 918.988 1981.901   100
 # f2(df) 298.367 319.0995 353.4915 338.6305 380.246  599.439   100

df <- structure(list(Group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"),
    Class = c(1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 3L, 1L, 1L, 1L,
    1L, 2L, 3L)), .Names = c("Group", "Class"), class = "data.frame", row.names = c(NA,
-15L))


问:
Output for an RNN
I'm taking the Coursera course Neural Networks for Machine Learning hosted by Geoffrey Hinton from the University of Toronto and there is a quiz question in week 7 for which my answer differs from the right one.

The question goes like this:

One question is, how should I get a probability between 0 and 1 if the Whh weight is negative and the logistic h unit gives values between 0 and 1. Given the above, their linear combination will allways be negative.

A second question would be if we also have to use backpropagation in order to get the right answer?

The way I've started to tackle this question is the following:

```<code>h0 = 1/( 1 + exp(- (Whh * hbias + Wxh*x0)) )

h1 = 1/( 1 + exp(- (Whh * h0 + Wxh*x1)))

y1 = Why * h1
</code>```

Which of my assumptions are incorrect?

Regards,
Cristian

答:
Try this.

```<code>h0 = sigmoid(x0*Wxh + hbias)
h1 = sigmoid(x1*Wxh + Whh*h0 + hbias)
y1 = h1*Why
</code>```

Title: Output for an RNN

Body:
I'm taking the Coursera course Neural Networks for Machine Learning hosted by Geoffrey Hinton from the University of Toronto and there is a quiz question in week 7 for which my answer differs from the right one.

The question goes like this:

One question is, how should I get a probability between 0 and 1 if the Whh weight is negative and the logistic h unit gives values between 0 and 1. Given the above, their linear combination will allways be negative.

A second question would be if we also have to use backpropagation in order to get the right answer?

The way I've started to tackle this question is the following:

h0 = 1/( 1 + exp(- (Whh * hbias + Wxh*x0)) )

h1 = 1/( 1 + exp(- (Whh * h0 + Wxh*x1)))

y1 = Why * h1

Which of my assumptions are incorrect?

Regards,
Cristian

Body:
Try this.

h0 = sigmoid(x0*Wxh + hbias)
h1 = sigmoid(x1*Wxh + Whh*h0 + hbias)
y1 = h1*Why


问:
Django get the Model name using ORM's related field name
I have a string like this order__product__category__description which is a related expression of my Django's model structure

Now I have a model called Shipment

field = 'order__product__category__description'

Here description is a column name of table/model Category. Here comes the question, just by having this model Shipment and this field string order__product__category__description how do I find these models Order, Product, Category.

My use-case is I need to store all the field_names of Category in a list. Any idea on how to connect the dots? having left with just two details Shipment & that field string.

First thing comes to mind is to split by __ and to come up with a list like this ['order','product','category'] and to iterate the model _meta based on the field name. Any other elegant ways would be appreciated.

答:
I didn't understand well. Anyway hope this you want.

```<code>field = 'order__product__category__description'
</code>```

To get product from Shipment instance

```<code>product_var = ".".join(field.split("__")[:2])
</code>```

Then

```<code>from operator import attrgetter
attrgetter(product_var)(shipment_instance)
</code>```

Also you can get all related as a tuple

```<code>attrgetter(".".join(field.split("__")[:1]), ".".join(field.split("__")[:2]), ".".join(field.split("__")[:3]), ".".join(field.split("__")[:4]))(shipment_instance)
</code>```

Hope this helps.

Body:
I didn't understand well. Anyway hope this you want.

field = 'order__product__category__description'

To get product from Shipment instance

product_var = ".".join(field.split("__")[:2])

Then

from operator import attrgetter
attrgetter(product_var)(shipment_instance)

Also you can get all related as a tuple

attrgetter(".".join(field.split("__")[:1]), ".".join(field.split("__")[:2]), ".".join(field.split("__")[:3]), ".".join(field.split("__")[:4]))(shipment_instance)

Hope this helps.


问:
Nested loops with conditions in javascript
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();```
</div>
</div>
</p>

<p>i'm expecting a result of</p>

```full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];
```

but i cant figure how to do it.

答:
Create another function to parse the Object and parse it.

function parseObj(o){
  Str = "{
";
  var i=0;
  while(i<Object.keys(o).length-1){
    Str += "  "+Object.keys(o)[i]+" : "+o[Object.keys(o)[i]]+",
";
    i++;
  }
  Str += "  "+Object.keys(o)[i]+" : "+o[Object.keys(o)[i]]+"
}";
  return Str;
}

function day_schedule() {

  var time_plan = [{
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  }, {
    "lesson_start": "09:00",
    "lesson_end": "10:00"
  }, {
    "lesson_start": "10:00",
    "lesson_end": "11:00"
  }, {
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  }, {
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  }, {
    "lesson_start": "13:00",
    "lesson_end": "13:30"
  }, {
    "lesson_start": "13:30",
    "lesson_end": "14:30"
  }];

  var day = [{
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  }, {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  }, {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  }];
  empty={"
  var key1 = 'lesson_start';
  var key2 = 'lesson_end';
  var full_day = [];

  for (var d = 0; d < day.length; d++) {
    var start_time = day[d].lesson_start;
    var end_time = day[d].lesson_end;

    for (var i = 0; i < time_plan.length; i++) {
      var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
      if (search_key == true) {
        document.writeln('day matched == ' + parseObj(day[d])+'
');
        full_day.push(day[d]);
      } else {
        full_day.push({
          lesson_start: ' ',
          lesson_end: ' ',
          subject_name: ' '
        });
      }

    }

 //   console.log('full day', full_day.length, full_day);

  }
}

day_schedule();```

Body:
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();

i'm expecting a result of

full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];

but i cant figure how to do it.

Body:
Create another function to parse the Object and parse it.

function parseObj(o){
  Str = "{<br />";
  var i=0;
  while(i<Object.keys(o).length-1){
    Str += "&ensp;&ensp;"+Object.keys(o)[i]+" : "+o[Object.keys(o)[i]]+",<br />";
    i++;
  }
  Str += "&ensp;&ensp;"+Object.keys(o)[i]+" : "+o[Object.keys(o)[i]]+"<br />}";
  return Str;
}

function day_schedule() {

  var time_plan = [{
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  }, {
    "lesson_start": "09:00",
    "lesson_end": "10:00"
  }, {
    "lesson_start": "10:00",
    "lesson_end": "11:00"
  }, {
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  }, {
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  }, {
    "lesson_start": "13:00",
    "lesson_end": "13:30"
  }, {
    "lesson_start": "13:30",
    "lesson_end": "14:30"
  }];

  var day = [{
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  }, {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  }, {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  }];
  empty={"
  var key1 = 'lesson_start';
  var key2 = 'lesson_end';
  var full_day = [];

  for (var d = 0; d < day.length; d++) {
    var start_time = day[d].lesson_start;
    var end_time = day[d].lesson_end;

    for (var i = 0; i < time_plan.length; i++) {
      var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
      if (search_key == true) {
        document.writeln('day matched == ' + parseObj(day[d])+'<br>');
        full_day.push(day[d]);
      } else {
        full_day.push({
          lesson_start: ' ',
          lesson_end: ' ',
          subject_name: ' '
        });
      }

    }

 //   console.log('full day', full_day.length, full_day);

  }
}

day_schedule();


问:
Prevent browser autofilling hidden fields
We use jQuery to hide fields that aren't relevant, depending on previous answers. It seems somehow the browser (Chrome) has managed to insert the users's email address into it.  Autocomplete is already set to off.  The field id and name are like "field-32", not even anything like "username" or "email".

Is this something out of our control? I suppose could try clearing all hidden fields on submit.... but that would break other stuff where I do need hidden fields.

答:
You can change the autocomplete:</p>

```<code><input type="text" name="mail" autocomplete="new-mail">
</code>```

Body:
You can change the autocomplete:

<input type="text" name="mail" autocomplete="new-mail">


问:
Jenkins job: Could not push to git from shell
I need to use jenkins job to synchronize two repositories. So I have created a job, added two git repositories using Multiple SCMs plugin.

And added shell commands, example:

```<code>cd first_project
sha=`cat last_commit_merged`
cd ..
cd second_project
new_sha=`git rev-parse HEAD`
git diff-index "$sha" --binary > my.patch
cd ..
cd first_project
if [ "$sha" != "$new_sha" ]
then
  git apply ../second_project/my.patch
  echo "$new_sha" > last_commit_merged
  git add .
  git commit -m "New sync, date `date +'%Y-%m-%d %H:%M:%S'`";
  git push origin HEAD
fi
</code>```

So when job starts, it successfully clones both repositories in folders: first_project and second_project, I could create my.patch, apply it and commit, but command:
git push origin HEAD does not work and I could not figure out how to setup correctly git in shell to make it working, the error is:

```<code>+ git push origin HEAD
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

If anyone could help that would be much appreciated

Thanks

答:
The solution is to create id_rsa file manually in shell like this:</p>

```<code>cat <<EOF >/root/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
content of the file
-----END RSA PRIVATE KEY-----
EOF
chmod 400 ~/.ssh/id_rsa
</code>```

Body:
I need to use jenkins job to synchronize two repositories. So I have created a job, added two git repositories using Multiple SCMs plugin.

And added shell commands, example:

cd first_project
sha=`cat last_commit_merged`
cd ..
cd second_project
new_sha=`git rev-parse HEAD`
git diff-index "$sha" --binary > my.patch
cd ..
cd first_project
if [ "$sha" != "$new_sha" ]
then
  git apply ../second_project/my.patch
  echo "$new_sha" > last_commit_merged
  git add .
  git commit -m "New sync, date `date +'%Y-%m-%d %H:%M:%S'`";
  git push origin HEAD
fi

So when job starts, it successfully clones both repositories in folders: first_project and second_project, I could create my.patch, apply it and commit, but command:
git push origin HEAD does not work and I could not figure out how to setup correctly git in shell to make it working, the error is:

+ git push origin HEAD
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Build step 'Execute shell' marked build as failure
Finished: FAILURE

If anyone could help that would be much appreciated

Thanks

Body:
The solution is to create id_rsa file manually in shell like this:

cat <<EOF >/root/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
content of the file
-----END RSA PRIVATE KEY-----
EOF
chmod 400 ~/.ssh/id_rsa


问:
How to get multiple selected radio buttons value using Jquery
I want to get multiple radio buttons value using Jquery. But now could only get the first one's value.

```<code><form action="get" method="post">
                    <table width="100%">
                    <tbody id="checklistwrapper">

                    <tr class="checklisttr" id="1">

                    <td align="left" width="40%"><br>
                    <label for="veryiii" style="align:left;">Within your circle of competence?</label>
                    </td>

                    <td align="center">
                    <label for="veryi" width="12%">Worst</label><br><br>
                    <input type="radio" id="veryi" value="5.0" name="circle">
                    </td>

                    <td align="center" width="12%"><br><br>
                    <input type="radio" id="vii" value="4.5" name="circle">
                    </td>

                    <td align="center" width="12%">
                    <label for="veryiii">Neutral</label><br><br>
                    <input type="radio" id="veryiii" value="3.0" name="circle">
                    </td>

                    <td align="center" width="12%"><br><br>
                    <input type="radio" id="viv" value="1.5" name="circle">
                    </td>

                    <td align="center" width="12%">
                    <label for="veryv">Best</label><br><br>
                    <input type="radio" id="veryv" value="1.0" name="circle">
                    </td>
                    </tr>

                    <tr class="checklisttr" id="2">

                    <td align="left" width="40%"><br>
                    <label for="veryiii" style="align:left;">Macro economic environment favorable?</label>
                    </td>

                    <td align="center" width="12%"><br>
                    <input type="radio" id="veryi" value="5.0" name="macro">
                    </td>

                    <td align="center" width="12%"><br>
                    <input type="radio" id="vii" value="4.5" name="macro">
                    </td>

                    <td align="center" width="12%"><br>
                    <input type="radio" id="veryiii" value="3.0" name="macro">
                    </td>

                    <td align="center" width="12%"><br>
                    <input type="radio" id="viv" value="1.5" name="macro">
                    </td>

                    <td align="center" width="12%"><br>
                    <input type="radio" id="veryv" value="1.0" name="macro">
                    </td>
                    </tr>

                    </tbody></table>

                    <div style="float:right;margin-top:10px;margin-bottom:5px;">
                        <button type="button" id="savechecklist">Save Checklist</button>
                    </div>
</code>```

```<code>    $('#savechecklist').click(function(){
    var the_value;
    //the_value = jQuery('input:radio:checked').val();
    //the_value = jQuery('input[name=macro]:radio:checked').val();
    the_value = getChecklistItems();
    //alert(the_value);
});

function getChecklistItems() {
    var columns = [];

    $('tr.checklisttr').each(function() {
        //columns.push($(this).('input:radio:checked').val());
        //the_value = $(this).('input:radio:checked').val();
        var the_value = jQuery('input:radio:checked').attr('id');
        alert(the_value);
    });

    return columns.join('|');
}
</code>```

答:
```<code>$('#savechecklist').click(function() {
    var the_value;
    //the_value = jQuery('input:radio:checked').val();
    //the_value = jQuery('input[name=macro]:radio:checked').val();
    the_value = getChecklistItems();
    alert(the_value);
});

function getChecklistItems() {
    var result =
        $("tr.checklisttr > td > input:radio:checked").get();

    var columns = $.map(result, function(element) {
        return $(element).attr("id");
    });

    return columns.join("|");
}
</code>```

http://jsfiddle.net/btG5L/

ContentLicense: CC BY-SA 2.5

Body:
I want to get multiple radio buttons value using Jquery. But now could only get the first one's value.

<form action="get" method="post">

                    Within your circle of competence?

                    Worst

                    <input type="radio" id="veryi" value="5.0" name="circle">

                    <input type="radio" id="vii" value="4.5" name="circle">

                    Neutral

                    <input type="radio" id="veryiii" value="3.0" name="circle">

                    <input type="radio" id="viv" value="1.5" name="circle">

                    Best

                    <input type="radio" id="veryv" value="1.0" name="circle">

                    Macro economic environment favorable?

                    <input type="radio" id="veryi" value="5.0" name="macro">

                    <input type="radio" id="vii" value="4.5" name="macro">

                    <input type="radio" id="veryiii" value="3.0" name="macro">

                    <input type="radio" id="viv" value="1.5" name="macro">

                    <input type="radio" id="veryv" value="1.0" name="macro">

                        <button type="button" id="savechecklist">Save Checklist</button>

    $('#savechecklist').click(function(){
    var the_value;
    //the_value = jQuery('input:radio:checked').val();
    //the_value = jQuery('input[name=macro]:radio:checked').val();
    the_value = getChecklistItems();
    //alert(the_value);
});

function getChecklistItems() {
    var columns = [];

    $('tr.checklisttr').each(function() {
        //columns.push($(this).('input:radio:checked').val());
        //the_value = $(this).('input:radio:checked').val();
        var the_value = jQuery('input:radio:checked').attr('id');
        alert(the_value);
    });

    return columns.join('|');
}

Body:
$('#savechecklist').click(function() {
    var the_value;
    //the_value = jQuery('input:radio:checked').val();
    //the_value = jQuery('input[name=macro]:radio:checked').val();
    the_value = getChecklistItems();
    alert(the_value);
});

function getChecklistItems() {
    var result =
        $("tr.checklisttr > td > input:radio:checked").get();

    var columns = $.map(result, function(element) {
        return $(element).attr("id");
    });

    return columns.join("|");
}

http://jsfiddle.net/btG5L/


问:
pywin32 win32gui.PumpWaitingMessages() placement
I'm attempting to write some python code to detect a monitor changed event in Windows; I'm using pywin32, largely based around code from the pywin32 example. It appears that the placement of PumpWaitingMessages makes a difference; the code below does detect a monitor change (i.e. OnDeviceChange gets run) but the lp argument is 0, so I can't get any useful info from it (i.e. the monitor identifier).

```<code>class Foo(QObject):
    def OnDeviceChange(self, hwnd, msg, wp, lp):
        info = win32gui_struct.UnpackDEV_BROADCAST(lp)
        print("Device change notification:", wp, str(info))  #
        return True

    def __init__(self):
        wc = win32gui.WNDCLASS()
        wc.lpszClassName = 'test_devicenotify'
        wc.style = win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW | win32con.CS_HREDRAW
        wc.hbrBackground = win32con.COLOR_WINDOW + 1
        wc.lpfnWndProc = {win32con.WM_DEVICECHANGE: self.OnDeviceChange}
        class_atom = win32gui.RegisterClass(wc)
        hwnd = win32gui.CreateWindow(wc.lpszClassName,
            'Waiting for Monitor Change',
            # no need for it to be visible.
            win32con.WS_CAPTION,
            100, 100, 900, 900, 0, 0, 0, None)
        filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE(
                                            GUID_DEVINTERFACE_MONITOR)
        hdev = win32gui.RegisterDeviceNotification(hwnd, filter,
                                                   win32con.DEVICE_NOTIFY_WINDOW_HANDLE)

f = Foo()
while True:
    win32gui.PumpWaitingMessages()
    time.sleep(0.01)
</code>```

However, if I move the while True loop from the very end of the code to the end of the __init__ method, then the lp argument is populated, and I can get the info I want.

Any ideas why the placement of the while loop would make a difference?

答:
Although it's part of the borrowed code, I'm going to start with a recommendation of renaming variable filter to something else, because it's shadowing [Python]: filter(function, iterable) (didn't change myself when I edited the post since I couldn't post a comment specifying why I've done it). Also, you might want to add the missing pieces to have a working code snippet: imports, definitions (e.g. GUID_DEVINTERFACE_MONITOR, I browsed Ioevent.h, and I couldn't find neither USB nor display related GUIDs)

I suspected 2 things that might be held accountable for this behavior:

Mixing PyQt (which has its own windows handling) with plain WinAPI (as I wrote in my comment), and the possibility that one of the 2 might step on the other's toes

Python scopes ([Python]:
Execution model)

I didn't want to install PyQt, so I started exploring the other possibility. I was able to reproduce the same behavior with the original code (that you started from). The problem was that at the end of TestDeviceNotifications, hdev (returned by RegisterDeviceNotification), was going out of scope.

The same thing happens here: after exiting __init__, (when messages will start to be sent to the window) hdev will be an invalid handle. To correct this, make it global:

declare it at module level (before Foo) like: hdev = None

instruct __init__ to operate on the global variable instead of creating a new local one with the same name. Somewhere in __init__, before hdev = win32gui.RegisterDeviceNotification add global hdev, and it will be persistent

Note(s):

Typically, all created resources should be freed when they're no longer needed. This is what you should do with wc and hwnd. Regarding hdev, [MSDN]: RegisterDeviceNotification function doesn't mention anything about calling CloseHandle (or smth similar) upon it, so I think, it's good

Body:
I'm attempting to write some python code to detect a monitor changed event in Windows; I'm using pywin32, largely based around code from the pywin32 example. It appears that the placement of PumpWaitingMessages makes a difference; the code below does detect a monitor change (i.e. OnDeviceChange gets run) but the lp argument is 0, so I can't get any useful info from it (i.e. the monitor identifier).

class Foo(QObject):
    def OnDeviceChange(self, hwnd, msg, wp, lp):
        info = win32gui_struct.UnpackDEV_BROADCAST(lp)
        print("Device change notification:", wp, str(info))  #
        return True

    def __init__(self):
        wc = win32gui.WNDCLASS()
        wc.lpszClassName = 'test_devicenotify'
        wc.style = win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW | win32con.CS_HREDRAW
        wc.hbrBackground = win32con.COLOR_WINDOW + 1
        wc.lpfnWndProc = {win32con.WM_DEVICECHANGE: self.OnDeviceChange}
        class_atom = win32gui.RegisterClass(wc)
        hwnd = win32gui.CreateWindow(wc.lpszClassName,
            'Waiting for Monitor Change',
            # no need for it to be visible.
            win32con.WS_CAPTION,
            100, 100, 900, 900, 0, 0, 0, None)
        filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE(
                                            GUID_DEVINTERFACE_MONITOR)
        hdev = win32gui.RegisterDeviceNotification(hwnd, filter,
                                                   win32con.DEVICE_NOTIFY_WINDOW_HANDLE)

f = Foo()
while True:
    win32gui.PumpWaitingMessages()
    time.sleep(0.01)

However, if I move the while True loop from the very end of the code to the end of the __init__ method, then the lp argument is populated, and I can get the info I want.

Any ideas why the placement of the while loop would make a difference?


问:
jquery mouseenter on child div with bigger dimensions than parent div
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }</code>```

    Test

```

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

答:
You can prevent the event from propagating from the child to the parent, so it doesn't trigger on the parent when you're over the child:</p>

```<code>$(".child").mouseover(function(e) {
    e.stopPropagation();
});
</code>```

Body:
I have a parent div with height=100px which is smaller than child div which has height=200px.

When I attach jquery mouseenter on parent div then the event triggers even if I hover the pointer over child ( hover over the portion of child which extends the height of parent ).

Can anyone explain this?

$(document).ready(function() {
  $(".parent").mouseover(function(e) {
   console.log(e.target);
  });
  $(".child").mouseover(function(e) {
   console.log(e.target);
  });
  $(".grandchild").mouseover(function(e) {
   console.log(e.target);
  });
 });

.parent {
   background-color: green;
   height: 50px;
  }
  .child {
   background-color: red;
   height: 100px;
  }
  .grandchild {
   background-color: blue;
   height: 200px;
  }

    Test

--UPDATE--
At first it unclear to me what was exactly the problem. Now I think I understand (I updated the code).

Say we have a parent div with width=100px and height=100px.

Then we have a child div with width=200px and height=200px (bigger area than parent).

When I hover the mouse over the child (but not over the parent yet) the browser calculates that the pointer is over the parent too, although it does not.

So if I have a handler both on child and on parent, they will fire both by the time I enter the child div only.

Thank you.

Body:
You can prevent the event from propagating from the child to the parent, so it doesn't trigger on the parent when you're over the child:

$(".child").mouseover(function(e) {
    e.stopPropagation();
});


问:
On Android 5.0 lollipop maybe due to depricated getRunningTask() method
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

```<code>public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}
</code>```

DetectorService

```<code>public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}
</code>```

MonitorlogThread

```<code>private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}
</code>```

答:
Can you try this. </p>

```<code>    ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
        ActivityManager.RunningAppProcessInfo runningAppProcessInfo = (ActivityManager.RunningAppProcessInfo) am.getRunningAppProcesses();
        String foregroundTaskPackageName = runningAppProcessInfo.pkgList.getClass().getPackage().getName();
        PackageManager pm = getBaseContext().getPackageManager();
        PackageInfo foregroundAppPackageInfo = null;
        String foregroundTaskAppName = null;
        String foregroundTaskActivityName = runningAppProcessInfo.pkgList.getClass().getName();
        try {
            foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
            foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

            //debug: log.i("Detector",foregroundTaskAppName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    } else {
        ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
        String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
        PackageManager pm = getBaseContext().getPackageManager();
        PackageInfo foregroundAppPackageInfo = null;
        String foregroundTaskAppName = null;
        String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
        try {
            foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
            foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

            //debug: log.i("Detector",foregroundTaskAppName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }
</code>```

Body:
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}

DetectorService

public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}

MonitorlogThread

private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}

Body:
Can you try this.

    ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
        ActivityManager.RunningAppProcessInfo runningAppProcessInfo = (ActivityManager.RunningAppProcessInfo) am.getRunningAppProcesses();
        String foregroundTaskPackageName = runningAppProcessInfo.pkgList.getClass().getPackage().getName();
        PackageManager pm = getBaseContext().getPackageManager();
        PackageInfo foregroundAppPackageInfo = null;
        String foregroundTaskAppName = null;
        String foregroundTaskActivityName = runningAppProcessInfo.pkgList.getClass().getName();
        try {
            foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
            foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

            //debug: log.i("Detector",foregroundTaskAppName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    } else {
        ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
        String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
        PackageManager pm = getBaseContext().getPackageManager();
        PackageInfo foregroundAppPackageInfo = null;
        String foregroundTaskAppName = null;
        String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
        try {
            foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
            foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

            //debug: log.i("Detector",foregroundTaskAppName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }


问:
Running adb commands on all connected devices
Is there a way of running adb commands on all connected devices? To uninstall an app from all connected devices with "adb uninstall com.example.android".

The commands I am interested in is mainly install and uninstall.

I was thinking about writing a bash script for this, but I feel like someone should have done it already :)

答:
This is an improved version of the script from 強大な. The original version was not matching some devices.</p>

```<code>DEVICES=`adb devices | grep -v devices | grep device | cut -f 1`
for device in $DEVICES; do
    echo "$device $@ ..."
    adb -s $device $@
done
</code>```

Body:
This is an improved version of the script from 強大な. The original version was not matching some devices.

DEVICES=`adb devices | grep -v devices | grep device | cut -f 1`
for device in $DEVICES; do
    echo "$device $@ ..."
    adb -s $device $@
done

ContentLicense: CC BY-SA 4.0


问:
Input elemnts in HTMLLoader are readonly in adobe AIR
Lets say i have a html file that contain a form:

```<code><form method="post" action="url">
    <input type="text" id="fullname" />
    <input type="text" id="bodyText" />
    <input type="submit">
</form>
</code>```

we have load this html file using HTMLLoader inside an swf file.

```<code>_htmlLoader = new HTMLLoader();
_htmlLoader.paintsDefaultBackground = false;
var req:URLRequest = new URLRequest(urlValue);
_htmlLoader.load(req);
_stage.addChild(_htmlLoader);
</code>```

After loading this Swf file using Loader inside main application, text boxes are readonly and can't type in it.
But we can change focus of them using Mouse.

```<code>var loader1:Loader = new Loader();
loader1.load(new URLRequest("path to file.swf"));
// ...
this.addChild(loader1);
// ...
</code>```

What is the problem?

答:
The proposed solution ("wait the DOMContentLoaded event before addChild") didn't work for me.

Instead it worked using the FULL_SCREEN_INTERACTIVE display state.
According to Adobe's documentation about FULL_SCREEN:

"keyboard interactivity is enabled for mobile devices"

(I guess it's it's disabled others profiles like Desktop).

While FULL_SCREEN_INTERACTIVE:

Specifies that the Stage is in full-screen mode with keyboard interactivity enabled. As of Flash Player 11.3, this capability is supported in both AIR applications and browser-based applications.

So in my case the solution was:

```<code>_stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE
</code>```

Body:
Lets say i have a html file that contain a form:

<form method="post" action="url">
    <input type="text" id="fullname" />
    <input type="text" id="bodyText" />
    <input type="submit">
</form>

we have load this html file using HTMLLoader inside an swf file.

_htmlLoader = new HTMLLoader();
_htmlLoader.paintsDefaultBackground = false;
var req:URLRequest = new URLRequest(urlValue);
_htmlLoader.load(req);
_stage.addChild(_htmlLoader);

After loading this Swf file using Loader inside main application, text boxes are readonly and can't type in it.
But we can change focus of them using Mouse.

var loader1:Loader = new Loader();
loader1.load(new URLRequest("path to file.swf"));
// ...
this.addChild(loader1);
// ...

What is the problem?

Body:
The proposed solution ("wait the DOMContentLoaded event before addChild") didn't work for me.

Instead it worked using the FULL_SCREEN_INTERACTIVE display state.
According to Adobe's documentation about FULL_SCREEN:

"keyboard interactivity is enabled for mobile devices"

(I guess it's it's disabled others profiles like Desktop).

While FULL_SCREEN_INTERACTIVE:

Specifies that the Stage is in full-screen mode with keyboard interactivity enabled. As of Flash Player 11.3, this capability is supported in both AIR applications and browser-based applications.

So in my case the solution was:

_stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE


问:
Code First calling a stored procedure passing in 3 params validation errors
I have been successful with calling a stored procedure when passing in just 1 parameter, but now with my code first dbcontext, I am wanting to keep it simple, but I altered the code based on some answer I seen  :/  not working

OK, first off here is code that does work:

```<code>var param = new SqlParameter("@dt", myTime);
var result = _db.Database.SqlQuery<QAList>("dbo.GetDateTime @datetime", param).ToList();
</code>```

The above code works just fine, but this code here is not working (I'm passing in 3 params)

```<code>var paramPhone = validRequest.Phone;
var paramAccount = validRequest.AccountNumber;
var paramLead = validRequest.LeadId;

var result = _db.ValidRequests.SqlQuery(
    "dbo.CheckForValidRequest @Phone, @AccountNumber, @LeadId", paramPhone, paramAccount, paramLead);
</code>```

Now I know that I am NOT using the same type of syntax dbcontext.Database,  but that was based on what I had read elsewhere.

I did set up a DbSet, so it is looking like this

```<code> public DbSet<ValidRequest> ValidRequests { get; set; }
</code>```

However, I did not do anythig in OnModelCreating with modelBuilder like I normally do with linq to SQL queries.

My error message:

One or more validation errors were detected during model generation:

MyProject.ValidRequest: EntityType 'ValidRequest' has no key defined. Define the key for this EntityType.

  ValidRequests: EntityType: EntitySet 'ValidRequests' is based on type 'ValidRequest' that has no keys defined

Normally I would define a key, but this is a stored procedure that I'm calling...

UPDATE : Trying a different way , but yes... it is jumping into onModelCreating

I was trying this approach

```<code> using(var _db = new ClearviewContext())
   {
      var p = new SqlParameter("@Phone", paramPhone);
      var a = new SqlParameter("@AccountNumber", paramAccount);
      var l = new SqlParameter("@LeadId", paramLead);
      var r = _db.Database.ExecuteSqlCommand("exec CheckForValidRequest @Phone, @AccountNumber, @LeadId", p, a, l);
   }
</code>```

That returns -1  when I should get a 0 based on the data I passed in :/

UPDATE 2  -  I added an OUPUT param and was spending too much time , I really want to figure out how to fix this, but for now sadly I resorted to going OLD SCHOOL  :(

```<code>SqlCommand cmd = new SqlCommand(sprocName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Phone", paramPhone);
cmd.Parameters.AddWithValue("@AccountNumber",  paramAccount);
cmd.Parameters.AddWithValue("@LeadId", paramLead);
SqlParameter outParam = new SqlParameter();
outParam.ParameterName = "@clean";
outParam.SqlDbType = SqlDbType.Int;
outParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outParam);

conn.Open();
cmd.ExecuteNonQuery();
xt = outParam.Value.ToString();
</code>```

答:
in the early versions of EF,Entity model class was derived from Objectcontext
     but now it is derived from DbContext class which is a wrapper class for the ObjectContext class.

To call the Stored Procedure, we need the entity instance as of ObjectContext

```<code> var context = (_entity as IobjectContextAdapter).ObjectContext;//ObjectContext have ExecuteStoreQuery<T> as overloaded method and T denote the return type
</code>```

1. Stored Procedure without parameters:

  a.  GetStatus – Name of Stored Procedure.

  b.  empty collection of object as Parameters.

```<code>var lst = context.ExecuteStoreQuery<tblStatu>("GetStatus", new string[] { });
</code>```

2. Stored Procedure with parameters:

a.  GetMyName – Name of Stored Procedure.

b.  @FirstName, @LastName = Parameters.

c.  parameter -  collection of object as Parameters.

```<code>var parameter = new object[] {
                 new SqlParameter("@FirstName", "Vikas"),
                 new SqlParameter("@LastName", "Mahajan")
                };
Int32 recordID = context.ExecuteStoreQuery<Int32>("GetMyName", @FirstName,@LastName, parameter).FirstOrDefault();
</code>```

3. Stored Procedure With complex Return Type:
For Complex Return Type, we need to declare a Custom Class with the properties as of in the return dataset of stored procedure.

a. SvcRequestStatus(T) – Custom Class

b. GetStatusDynamixQuery - Name of Stored Procedures.

c. empty collection of object as Parameters.

```<code>IEnumerable<SvcRequestStatus> lst1 = context.ExecuteStoreQuery<SvcRequestStatus>("GetStatusDynamixQuery", new string[] { });
</code>```

Hope this will help!!

Body:
I have been successful with calling a stored procedure when passing in just 1 parameter, but now with my code first dbcontext, I am wanting to keep it simple, but I altered the code based on some answer I seen  :/  not working

OK, first off here is code that does work:

var param = new SqlParameter("@dt", myTime);
var result = _db.Database.SqlQuery<QAList>("dbo.GetDateTime @datetime", param).ToList();

The above code works just fine, but this code here is not working (I'm passing in 3 params)

var paramPhone = validRequest.Phone;
var paramAccount = validRequest.AccountNumber;
var paramLead = validRequest.LeadId;

var result = _db.ValidRequests.SqlQuery(
    "dbo.CheckForValidRequest @Phone, @AccountNumber, @LeadId", paramPhone, paramAccount, paramLead);

Now I know that I am NOT using the same type of syntax dbcontext.Database,  but that was based on what I had read elsewhere.

I did set up a DbSet, so it is looking like this

 public DbSet<ValidRequest> ValidRequests { get; set; }

However, I did not do anythig in OnModelCreating with modelBuilder like I normally do with linq to SQL queries.

My error message:

One or more validation errors were detected during model generation:

MyProject.ValidRequest: EntityType 'ValidRequest' has no key defined. Define the key for this EntityType.

  ValidRequests: EntityType: EntitySet 'ValidRequests' is based on type 'ValidRequest' that has no keys defined

Normally I would define a key, but this is a stored procedure that I'm calling...

UPDATE : Trying a different way , but yes... it is jumping into onModelCreating

I was trying this approach

 using(var _db = new ClearviewContext())
   {
      var p = new SqlParameter("@Phone", paramPhone);
      var a = new SqlParameter("@AccountNumber", paramAccount);
      var l = new SqlParameter("@LeadId", paramLead);
      var r = _db.Database.ExecuteSqlCommand("exec CheckForValidRequest @Phone, @AccountNumber, @LeadId", p, a, l);
   }

That returns -1  when I should get a 0 based on the data I passed in :/

UPDATE 2  -  I added an OUPUT param and was spending too much time , I really want to figure out how to fix this, but for now sadly I resorted to going OLD SCHOOL  :(

SqlCommand cmd = new SqlCommand(sprocName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Phone", paramPhone);
cmd.Parameters.AddWithValue("@AccountNumber",  paramAccount);
cmd.Parameters.AddWithValue("@LeadId", paramLead);
SqlParameter outParam = new SqlParameter();
outParam.ParameterName = "@clean";
outParam.SqlDbType = SqlDbType.Int;
outParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outParam);

conn.Open();
cmd.ExecuteNonQuery();
xt = outParam.Value.ToString();

Body:
in the early versions of EF,Entity model class was derived from Objectcontext
     but now it is derived from DbContext class which is a wrapper class for the ObjectContext class.

To call the Stored Procedure, we need the entity instance as of ObjectContext

 var context = (_entity as IobjectContextAdapter).ObjectContext;//ObjectContext have ExecuteStoreQuery<T> as overloaded method and T denote the return type

1. Stored Procedure without parameters:

  a.  GetStatus – Name of Stored Procedure.

  b.  empty collection of object as Parameters.

var lst = context.ExecuteStoreQuery<tblStatu>("GetStatus", new string[] { });

2. Stored Procedure with parameters:

a.  GetMyName – Name of Stored Procedure.

b.  @FirstName, @LastName = Parameters.

c.  parameter -  collection of object as Parameters.

var parameter = new object[] {
                 new SqlParameter("@FirstName", "Vikas"),
                 new SqlParameter("@LastName", "Mahajan")
                };
Int32 recordID = context.ExecuteStoreQuery<Int32>("GetMyName", @FirstName,@LastName, parameter).FirstOrDefault();

3. Stored Procedure With complex Return Type:
For Complex Return Type, we need to declare a Custom Class with the properties as of in the return dataset of stored procedure.

a. SvcRequestStatus(T) – Custom Class

b. GetStatusDynamixQuery - Name of Stored Procedures.

c. empty collection of object as Parameters.

IEnumerable<SvcRequestStatus> lst1 = context.ExecuteStoreQuery<SvcRequestStatus>("GetStatusDynamixQuery", new string[] { });

Hope this will help!!


问:
Check if android device rotation possible
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

```<code>if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}
</code>```

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

答: Every device supports the rotation feature although but you can not check that either device supports the rotation or not. You can only check the sensor and the rotation mode that if device is on portrait or on landscape. </p>

Body:
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo