问:
XSLT - Counting child nodes after applying muenchian grouping
For the below input XML, I am able to group all the child <invoice> elements under the appropriate <shippingBill> element using muenchian grouping method. However there is a requirement to include the count of the number of <shippingBill>elements and the <invoice> elements in the final output XML. I am not sure how to go about it.

Input XML

```<code><bank>
    <shippingBills>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoice>
                <invoiceSerialNo>1</invoiceSerialNo>
                <invoiceNo>183</invoiceNo>
                <invoiceDate>07/02/2016</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoice>
                <invoiceSerialNo>2</invoiceSerialNo>
                <invoiceNo>184</invoiceNo>
                <invoiceDate>07/02/2016</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoice>
                <invoiceSerialNo>1</invoiceSerialNo>
                <invoiceNo>172</invoiceNo>
                <invoiceDate>29/09/2015</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoice>
                <invoiceSerialNo>2</invoiceSerialNo>
                <invoiceNo>173</invoiceNo>
                <invoiceDate>29/09/2015</invoiceDate>
            </invoice>
        </shippingBill>
    </shippingBills>
</bank>
</code>```

XSL

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:key name="key-bill" match="shippingBill" use="shippingBillNo"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBills">
        <xsl:copy>
            <xsl:apply-templates
                select="shippingBill[generate-id() = generate-id(key('key-bill', shippingBillNo)[1])]"
                mode="group" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBill" mode="group">
        <shippingBill>
            <xsl:apply-templates select="*[not(self::invoice)]" />
            <invoices>
                <xsl:apply-templates select="key('key-bill', shippingBillNo)/invoice" />
            </invoices>
        </shippingBill>
    </xsl:template>
</xsl:stylesheet>
</code>```

Final Output XML Required

The <checkSum> element has been added which has child elements that hold the respective counts.

```<code><bank>
    <checkSum>
        <noOfInvoices>4</noOfInvoices>
        <noOfShippingBills>2</noOfShippingBills>
    </checkSum>
    <shippingBills>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoices>
                <invoice>
                    <invoiceSerialNo>1</invoiceSerialNo>
                    <invoiceNo>183</invoiceNo>
                    <invoiceDate>07/02/2016</invoiceDate>
                </invoice>
                <invoice>
                    <invoiceSerialNo>2</invoiceSerialNo>
                    <invoiceNo>184</invoiceNo>
                    <invoiceDate>07/02/2016</invoiceDate>
                </invoice>
            </invoices>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoices>
                <invoice>
                    <invoiceSerialNo>1</invoiceSerialNo>
                    <invoiceNo>172</invoiceNo>
                    <invoiceDate>29/09/2015</invoiceDate>
                </invoice>
                <invoice>
                    <invoiceSerialNo>2</invoiceSerialNo>
                    <invoiceNo>173</invoiceNo>
                    <invoiceDate>29/09/2015</invoiceDate>
                </invoice>
            </invoices>
        </shippingBill>
    </shippingBills>
</bank>
</code>```

答:
I would do it this way:

XSLT 1.0

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:strip-space elements="*" />
    <xsl:key name="key-bill" match="shippingBill" use="shippingBillNo" />

    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBills">
        <xsl:variable name="distinct-bills" select="shippingBill[generate-id() = generate-id(key('key-bill', shippingBillNo)[1])]" />
        <checkSum>
            <noOfInvoices>
                <xsl:value-of select="count(shippingBill/invoice)" />
            </noOfInvoices>
            <noOfShippingBills>
                <xsl:value-of select="count($distinct-bills)" />
            </noOfShippingBills>
        </checkSum>
        <xsl:copy>
            <xsl:apply-templates select="$distinct-bills" mode="group" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBill" mode="group">
        <shippingBill>
            <xsl:apply-templates select="*[not(self::invoice)]" />
            <invoices>
                <xsl:apply-templates select="key('key-bill', shippingBillNo)/invoice" />
            </invoices>
        </shippingBill>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
For the below input XML, I am able to group all the child <invoice> elements under the appropriate <shippingBill> element using muenchian grouping method. However there is a requirement to include the count of the number of <shippingBill>elements and the <invoice> elements in the final output XML. I am not sure how to go about it.

Input XML

<bank>
    <shippingBills>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoice>
                <invoiceSerialNo>1</invoiceSerialNo>
                <invoiceNo>183</invoiceNo>
                <invoiceDate>07/02/2016</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoice>
                <invoiceSerialNo>2</invoiceSerialNo>
                <invoiceNo>184</invoiceNo>
                <invoiceDate>07/02/2016</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoice>
                <invoiceSerialNo>1</invoiceSerialNo>
                <invoiceNo>172</invoiceNo>
                <invoiceDate>29/09/2015</invoiceDate>
            </invoice>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoice>
                <invoiceSerialNo>2</invoiceSerialNo>
                <invoiceNo>173</invoiceNo>
                <invoiceDate>29/09/2015</invoiceDate>
            </invoice>
        </shippingBill>
    </shippingBills>
</bank>

XSL

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:key name="key-bill" match="shippingBill" use="shippingBillNo"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBills">
        <xsl:copy>
            <xsl:apply-templates
                select="shippingBill[generate-id() = generate-id(key('key-bill', shippingBillNo)[1])]"
                mode="group" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBill" mode="group">
        <shippingBill>
            <xsl:apply-templates select="*[not(self::invoice)]" />
            <invoices>
                <xsl:apply-templates select="key('key-bill', shippingBillNo)/invoice" />
            </invoices>
        </shippingBill>
    </xsl:template>
</xsl:stylesheet>

Final Output XML Required

The <checkSum> element has been added which has child elements that hold the respective counts.

<bank>
    <checkSum>
        <noOfInvoices>4</noOfInvoices>
        <noOfShippingBills>2</noOfShippingBills>
    </checkSum>
    <shippingBills>
        <shippingBill>
            <shippingBillNo>5786885</shippingBillNo>
            <shippingBillDate>10/02/2016</shippingBillDate>
            <LEODate>11/02/2016</LEODate>
            <invoices>
                <invoice>
                    <invoiceSerialNo>1</invoiceSerialNo>
                    <invoiceNo>183</invoiceNo>
                    <invoiceDate>07/02/2016</invoiceDate>
                </invoice>
                <invoice>
                    <invoiceSerialNo>2</invoiceSerialNo>
                    <invoiceNo>184</invoiceNo>
                    <invoiceDate>07/02/2016</invoiceDate>
                </invoice>
            </invoices>
        </shippingBill>
        <shippingBill>
            <shippingBillNo>3318135</shippingBillNo>
            <shippingBillDate>01/10/2015</shippingBillDate>
            <LEODate>01/10/2015</LEODate>
            <invoices>
                <invoice>
                    <invoiceSerialNo>1</invoiceSerialNo>
                    <invoiceNo>172</invoiceNo>
                    <invoiceDate>29/09/2015</invoiceDate>
                </invoice>
                <invoice>
                    <invoiceSerialNo>2</invoiceSerialNo>
                    <invoiceNo>173</invoiceNo>
                    <invoiceDate>29/09/2015</invoiceDate>
                </invoice>
            </invoices>
        </shippingBill>
    </shippingBills>
</bank>

Body:
I would do it this way:

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:strip-space elements="*" />
    <xsl:key name="key-bill" match="shippingBill" use="shippingBillNo" />

    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBills">
        <xsl:variable name="distinct-bills" select="shippingBill[generate-id() = generate-id(key('key-bill', shippingBillNo)[1])]" />
        <checkSum>
            <noOfInvoices>
                <xsl:value-of select="count(shippingBill/invoice)" />
            </noOfInvoices>
            <noOfShippingBills>
                <xsl:value-of select="count($distinct-bills)" />
            </noOfShippingBills>
        </checkSum>
        <xsl:copy>
            <xsl:apply-templates select="$distinct-bills" mode="group" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="shippingBill" mode="group">
        <shippingBill>
            <xsl:apply-templates select="*[not(self::invoice)]" />
            <invoices>
                <xsl:apply-templates select="key('key-bill', shippingBillNo)/invoice" />
            </invoices>
        </shippingBill>
    </xsl:template>
</xsl:stylesheet>


来源: stackexchange

问:
For loop not working in python
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

```<code>for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]
</code>```

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

答:
You are incorrectly using % format strings, you could create a tuple() but it may be easier to use .format(). You can also split strings for better formatting:

```<code>start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
              "countryid=100&lang=en&page={}&pagesize={}&"
              "sortby=popular&licensetype=all&callback=_producttype_apps&"
              "_=1499255634459".format(i, page) for page in xrange(1,1001)]
</code>```

ContentLicense: CC BY-SA 3.0

Title: For loop not working in python

Body:
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

Body:
You are incorrectly using % format strings, you could create a tuple() but it may be easier to use .format(). You can also split strings for better formatting:

start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
              "countryid=100&lang=en&page={}&pagesize={}&"
              "sortby=popular&licensetype=all&callback=_producttype_apps&"
              "_=1499255634459".format(i, page) for page in xrange(1,1001)]


问:
add click event to Jquery UI accordian Header
When you create a Jquery UI accordian you get a bunch of headers, that when you click them a div opens. However, I would like to preform an additional action upon clicking the header.

How do i do this?

Any ideas?

Thanks!

答:
What I've done when I needed to do this in the past was something like this:</p>

```<code>$('#accordion h3 a').bind('click', function (e) {
  // bind to the the header / anchor clicks
  if (!condition) {
    e.preventDefault();
    e.stopPropagation();
  }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What I've done when I needed to do this in the past was something like this:

$('#accordion h3 a').bind('click', function (e) {
  // bind to the the header / anchor clicks
  if (!condition) {
    e.preventDefault();
    e.stopPropagation();
  }
});


答:
You can do this most easily using variables:</p>

```<code> select t.*,
         (@rn := if(@ws = concat_ws(':', worker_id, shift), @rn + 1,
                    if(@ws := concat_ws(':', worker_id, shift), 0, 0)
                   )
         )
  from t cross join
       (select @rn := -1, @ws := '') params
  order by worker_id, shift;
</code>```

Title: count occurrences of values in a column conditioned to values in another column

Body:
I have a table with three columns: tasks, shift and worker_ID. A task in tasks can be performed by several workers in worker_ID.

tasks | shift | worker_ID
------|-------|----------
111   | 127   | 233
111   | 127   | 34
111   | 127   | 455
333   | 127   | 444
333   | 127   | 34
333   | 127   | 200
333   | 127   | 100
444   | 127   | 34
444   | 127   | 567
444   | 127   | 888
666   | 125   | 100
666   | 125   | 200
666   | 125   | 345
666   | 125   | 100
555   | 125   | 34
555   | 125   | 100
555   | 125   | 457

I would like to create an sql query to count the occurrences of each worker_ID in each specific shift to return the following additional column (num_occ):

tasks | shift | worker_ID | num_occ
------|-------|-----------|--------
111   | 127   | 233       |  0
111   | 127   | 34        |  0
111   | 127   | 455       |  0
333   | 127   | 444       |  0
333   | 127   | 34        |  1
333   | 127   | 200       |  0
333   | 127   | 100       |  0
444   | 127   | 34        |  2
444   | 127   | 567       |  0
444   | 127   | 888       |  0
666   | 125   | 100       |  0
666   | 125   | 200       |  0
666   | 125   | 345       |  0
666   | 125   | 100       |  1
555   | 125   | 34        |  0
555   | 125   | 100       |  2
555   | 125   | 457       |  0

Any help would be greatly appreciated.
Thanks

Body:
You can do this most easily using variables:

 select t.*,
         (@rn := if(@ws = concat_ws(':', worker_id, shift), @rn + 1,
                    if(@ws := concat_ws(':', worker_id, shift), 0, 0)
                   )
         )
  from t cross join
       (select @rn := -1, @ws := '') params
  order by worker_id, shift;


问:
Installing Script in Atom
I struggle with a very basic problem in the Atom editor. I simply want to run a python file but am unable to just open a command line or console. In other forums I read, I need to install Script. I tried to do it in Packages -> Settings View. But if I type 'script' in the install packages field, only this response appears: Searching for “script” failed.Show output…

How can I make Atom to find this packages?
Thx

答:
press ctrl+, to open your preferences

go to install

search for script

press install

Title: Installing Script in Atom


问:
Specifying Room dimensions in networked-a-frame
I am new to a-frame and have followed the examples of haydenjameslee networked-aframe. I was wondering if there is a way to specify the room size when defining the a-scene in it's tag</p>

```<code><a-scene networked-scene="app: myApp; room: room1;">
</code>```

答:
I have a workaround, for I don't fully understand how the component works.

I found there is a player list under the reference NAF.entities.entities

I made a component attached to the scene:

```<code>AFRAME.registerComponent('foo',{
  init:function(){
    setTimeout(function(){
      console.log(Object.keys(NAF.entities.entities));
      console.log(Object.keys(NAF.entities.entities)[0]);
      console.log(Object.keys(NAF.entities.entities).length);
    },5000);
  }
});
</code>```

The first log gives me an array of the players id's.

The second one gives the id of the first element.

The last gives me the number of the players.

You can check for the number of players on load, and if the number is exceeded, just deny access, change the room, or href to a 'lobby' website.

 Working glitch here: glitch.com/edit/#!/sudden-antler

 Of course instead of waiting 5 seconds i should be listening to a loaded event, I'll look into it once im not so busy.

Body:
I have a workaround, for I don't fully understand how the component works.

I found there is a player list under the reference NAF.entities.entities

I made a component attached to the scene:

AFRAME.registerComponent('foo',{
  init:function(){
    setTimeout(function(){
      console.log(Object.keys(NAF.entities.entities));
      console.log(Object.keys(NAF.entities.entities)[0]);
      console.log(Object.keys(NAF.entities.entities).length);
    },5000);
  }
});

The first log gives me an array of the players id's.

The second one gives the id of the first element.

The last gives me the number of the players.

You can check for the number of players on load, and if the number is exceeded, just deny access, change the room, or href to a 'lobby' website.

 Working glitch here: glitch.com/edit/#!/sudden-antler

 Of course instead of waiting 5 seconds i should be listening to a loaded event, I'll look into it once im not so busy.


问:
Jquery Ajax GET call different results
I've written a few lines of code to tackle the following problem:

Get the TwitchTV UserID based on the username. The usernames are in an arrray. After hitting a button a GET AJAX request will be called to GET the UserID and to push it in another array and the call to the API will made via AJAX after hitting a button.

My problem is that if I hit the button again the usersID are in wrong order.

If I set async: false, it works.

Is this problem because of Asynchronous AJAX? What would be the approach for a valid fix? Use callback? A hint in the right direction would be appreciated.

The comments in the code are for testing.

Code:

```<code><script>

        var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
            clientID = "?client_id=XXX";
            userID = [];
            userStatus = [];
for(var i=0; i<users.length; i++){
          idCall(users[i]);

        };
function idCall (data){
            $.ajax({
              type: "GET",
              url: "https://api.twitch.tv/kraken/users/" + data + clientID,
              async: false,
              cache: false,
              dataType: "jsonp",
              success: function (data){
                console.log(data._id);
              },
              error: function (data) {
                console.log("error");
              }});
        };
</script>
</code>```

答:
Yes, it is because of the AJAX calls. One AJAX call might finish before the other and therefore the different order.

An obvious solution is to use jQuery promises but another solution to this problem could be that you sort your array after your AJAX calls have been completed.

You can sort your array according to the username string like this:

```<code>data.sort();
</code>```

If you have an array of objects, which you don't in the example code, you can sort it like this:

```<code>data.sort(function (a, b) { return (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0); } );
</code>```

After going through the comments, I thought to give some more code that can a better idea on how to solve this.

```<code><script>

var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
clientID = "?client_id=XXX";
userID = [];
userStatus = [];

var count = 0;
for(var i=0; i<users.length; i++){
    idCall(users[i]);
}

function idCall (data){
   $.ajax({
        type: "GET",
        url: "https://api.twitch.tv/kraken/users/" + data + clientID,
        async: false,
        cache: false,
        dataType: "jsonp",
        success: function (data){
            console.log(data._id);
            userID.push(data._id);
            count++;
            if( count === users.length - 1 ) {
                userID.sort();
            }
        },
        error: function (data) {
            console.log("error");
        }

   });
}
</code>```

Title: Jquery Ajax GET call different results

Body:
Yes, it is because of the AJAX calls. One AJAX call might finish before the other and therefore the different order.

An obvious solution is to use jQuery promises but another solution to this problem could be that you sort your array after your AJAX calls have been completed.

You can sort your array according to the username string like this:

data.sort();

If you have an array of objects, which you don't in the example code, you can sort it like this:

data.sort(function (a, b) { return (a.Name > b.Name) ? 1 : ((b.Name > a.Name) ? -1 : 0); } );

After going through the comments, I thought to give some more code that can a better idea on how to solve this.

<script>

var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
clientID = "?client_id=XXX";
userID = [];
userStatus = [];

var count = 0;
for(var i=0; i<users.length; i++){
    idCall(users[i]);
}

function idCall (data){
   $.ajax({
        type: "GET",
        url: "https://api.twitch.tv/kraken/users/" + data + clientID,
        async: false,
        cache: false,
        dataType: "jsonp",
        success: function (data){
            console.log(data._id);
            userID.push(data._id);
            count++;
            if( count === users.length - 1 ) {
                userID.sort();
            }
        },
        error: function (data) {
            console.log("error");
        }

   });
}


问:
Select/DeSelect All with Checkbox on ListView (Windows 10)
Hi i want do Select/DeSelect items with checkbox , my source codes :

XAML :

```<code><ListView
        x:Name="downListView"
        Grid.RowSpan="2"
        Margin="-1,29,1,3"
        ScrollViewer.HorizontalScrollBarVisibility="Hidden"
        ScrollViewer.HorizontalScrollMode="Disabled"
        ScrollViewer.VerticalScrollBarVisibility="Visible"
        ScrollViewer.VerticalScrollMode="Enabled"
        SelectionMode="Multiple">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Margin="0,2,0,2" Loaded="downListView_Loaded">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal">
                    <TextBlock
                            x:Name="downPosition"
                            Foreground="#C2C2CA"
                            Text="{Binding position}" />
                    <TextBlock Text=":" />
                    <TextBlock
                            x:Name="downTitle"
                            Foreground="#C2C2CA"
                            Text="{Binding title}" />
                </StackPanel>
                <ProgressBar
                            x:Name="downBar"
                            Grid.Row="1"
                            Background="White"
                            Foreground="#DC143C"
                            Value="{Binding Percent}" />
                <TextBlock
                            x:Name="downStat"
                            Grid.Row="2"
                            Foreground="#C2C2CA"
                            Text="{Binding Status}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

C# :

```<code>private ObservableCollection<VideoDatas> listItems = ...;
downListView.ItemsSource = listItems;
</code>```

I tried this :

```<code>private void downListView_Loaded(object sender, RoutedEventArgs e)
{
    Panel panel = sender as Panel;
    if (panel != null)
    {
        ListViewItem lvi = FindParent<ListViewItem>(panel);
        if (lvi != null)
        {
            lvi.SetBinding(ListViewItem.IsSelectedProperty, new Binding()
            {
                Path = new PropertyPath(nameof(VideoDatas.IsSelected)),
                Source = panel.DataContext,
                Mode = BindingMode.TwoWay
            });
        }
    }
}
public static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null)
        return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

private void CheckedChanged()
{
    if (listItems != null)
    {
        foreach (VideoDatas item in listItems)
        {
            if (dSelectAll.IsChecked == true)
            {
                item.IsSelected = true;
                dSelectAllText.Text = "DeSelect All | Choose for download";
            }
            else
            {
                item.IsSelected = false;
                dSelectAllText.Text = "Select All | Choose for download";
            }
        }
    }
}

private void dSelectAll_Click(object sender, RoutedEventArgs e)
{
    CheckedChanged();
}
</code>```

VideoDatas.cs

```<code>private bool isSelected;
public bool IsSelected
{
    get
    {
        return isSelected;
    }
    set
    {
        if (value != isSelected)
        {
            isSelected = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
            }
        }
    }
}
</code>```

But this code just select ex:10 items/170 items.Just select showin items on listview, dont select other items

答:
You are manually ticking the built-in CheckBox inside each ListViewItem on load. This solution looks OK but the issue is that the ListView is virtualizing its items so it only realizes a few of them to save memory, and you end up only ticking them.

The right way is to use the built-in methods downListView.SelectAll() to select all of them, and downListView.SelectedItems.Clear(); to deselect all of them.

Body:
Hi i want do Select/DeSelect items with checkbox , my source codes :

XAML :

<ListView
        x:Name="downListView"
        Grid.RowSpan="2"
        Margin="-1,29,1,3"
        ScrollViewer.HorizontalScrollBarVisibility="Hidden"
        ScrollViewer.HorizontalScrollMode="Disabled"
        ScrollViewer.VerticalScrollBarVisibility="Visible"
        ScrollViewer.VerticalScrollMode="Enabled"
        SelectionMode="Multiple">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Margin="0,2,0,2" Loaded="downListView_Loaded">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal">
                    <TextBlock
                            x:Name="downPosition"
                            Foreground="#C2C2CA"
                            Text="{Binding position}" />
                    <TextBlock Text=":" />
                    <TextBlock
                            x:Name="downTitle"
                            Foreground="#C2C2CA"
                            Text="{Binding title}" />
                </StackPanel>
                <ProgressBar
                            x:Name="downBar"
                            Grid.Row="1"
                            Background="White"
                            Foreground="#DC143C"
                            Value="{Binding Percent}" />
                <TextBlock
                            x:Name="downStat"
                            Grid.Row="2"
                            Foreground="#C2C2CA"
                            Text="{Binding Status}" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C# :

private ObservableCollection<VideoDatas> listItems = ...;
downListView.ItemsSource = listItems;

I tried this :

private void downListView_Loaded(object sender, RoutedEventArgs e)
{
    Panel panel = sender as Panel;
    if (panel != null)
    {
        ListViewItem lvi = FindParent<ListViewItem>(panel);
        if (lvi != null)
        {
            lvi.SetBinding(ListViewItem.IsSelectedProperty, new Binding()
            {
                Path = new PropertyPath(nameof(VideoDatas.IsSelected)),
                Source = panel.DataContext,
                Mode = BindingMode.TwoWay
            });
        }
    }
}
public static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null)
        return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

private void CheckedChanged()
{
    if (listItems != null)
    {
        foreach (VideoDatas item in listItems)
        {
            if (dSelectAll.IsChecked == true)
            {
                item.IsSelected = true;
                dSelectAllText.Text = "DeSelect All | Choose for download";
            }
            else
            {
                item.IsSelected = false;
                dSelectAllText.Text = "Select All | Choose for download";
            }
        }
    }
}

private void dSelectAll_Click(object sender, RoutedEventArgs e)
{
    CheckedChanged();
}

VideoDatas.cs

private bool isSelected;
public bool IsSelected
{
    get
    {
        return isSelected;
    }
    set
    {
        if (value != isSelected)
        {
            isSelected = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("IsSelected"));
            }
        }
    }
}

But this code just select ex:10 items/170 items.Just select showin items on listview, dont select other items


问:
Should I include Modernizr in my MVC project
Now that I'm busy optimizing my application, I was wondering if should include Modernizr in my MVC project since we are in 2017 and the minimum version of our browser is IE 10 and latest Chrome.</p>

答: Well... Modernizr doesn't do anything on its own, you have to use its feature detection to change your code.... So if you do not plan to change your JS or CSS based on the flags it provides then No - there is no point in including it</p>


问:
Convert data with one column and multiple rows into multi column multi row data
I have an output of web scraped data in R which looks as follows

```<code>Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3
</code>```

Some names may not have email or location. I want convert above data into tabular format. The output should look like

```<code>Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com
</code>```

答:
Insert \nName: before each Name and then read it in using read.dcf (If the data comes from a file replace textConnection(Lines) with the filename, e.g. "myfile.dat", in the first line of code.)  No packages are used.

```<code>L <- trimws(readLines(textConnection(Lines)))
ix <- !grepl(":", L)
L[ix] <- paste("\nName:", L[ix])
read.dcf(textConnection(L))
</code>```

giving the following using the input in the Note at the end:

```<code>     Name    Email            City/Town
[1,] "Name1" "email1@xyz.com" "Location1"
[2,] "Name2" NA               "Location2"
[3,] "Name3" "email3@pqr.com" NA
</code>```

Note:  Input used. This is slightly modified from question to show that it works if Email or City/Town is missing:

```<code>Lines <- "Name1
Email: email1@xyz.com
City/Town: Location1
Name2
City/Town: Location2
Name3
Email: email3@pqr.com"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an output of web scraped data in R which looks as follows

Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3

Some names may not have email or location. I want convert above data into tabular format. The output should look like

Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com

Body:
Insert \nName: before each Name and then read it in using read.dcf (If the data comes from a file replace textConnection(Lines) with the filename, e.g. "myfile.dat", in the first line of code.)  No packages are used.

L <- trimws(readLines(textConnection(Lines)))
ix <- !grepl(":", L)
L[ix] <- paste("\nName:", L[ix])
read.dcf(textConnection(L))

giving the following using the input in the Note at the end:

     Name    Email            City/Town
[1,] "Name1" "email1@xyz.com" "Location1"
[2,] "Name2" NA               "Location2"
[3,] "Name3" "email3@pqr.com" NA

Note:  Input used. This is slightly modified from question to show that it works if Email or City/Town is missing:

Lines <- "Name1
Email: email1@xyz.com
City/Town: Location1
Name2
City/Town: Location2
Name3
Email: email3@pqr.com"


问:
How to store daily/monthly snapshots on Google BigQuery?
we need to store daily and monthly snapshots of some of ours database.

It's not backup, we need to store the data so to analyze them later and to see how they evolve during the time.
We still don't know exactly what sort of queries we will need in two months, for starting we need to track some evolutions of our user base, so we will save daily snapshots of users and other related collections.

We are thinking to put all the stuff on Google BigQuery, it's easy to put data on it and easier to make queries on that data.

We will create some tables, one for each set of data we need, with all the needed columns, plus an extra one that will contain the date on which the extraction process was done.
We will use this column to group the data by day, month, and so on.

An alternative approach could be to create a dataset for each .. well set of data, and one table every time we need a snapshot.
I honestly don't know what is the better between these two, or if there are better options.

答: Probably a bit late, but for future readers: you are probably looking for date-partitioned tables. It corresponds exactly to this use case, and there's a straightforward example in the documentation page.</p>


问:
Django delete without calling signals
I use signals for things that should always be done when an object is deleted, saved, updated, etc. However, there are times when I don't want to call my save signals, so I use

Model.objects.filter(id=instance.id).update(field=value)

instead of the instance's save method:

instance.save()

In the case of deleting objects, there are also times when I don't want to call the delete signals, but I haven't found a way to avoid calling them. Is there a way??

UPDATE:

I'm using django 1.6.2 and calling the delete method like this:

Model.objects.filter(id=instance.id).delete()

on the queryset still still calls the delete signal.

答: In the place where you don't want signals to be called, you have to disconnect them, run you code and then reconnect them again. You can take a look on how mute_signal decorator is implemented in FactoryBoy or just use (but it's basically intended for django tests)</p>

Title: Django delete without calling signals


问:
How to prevent app from being cached in android
After some research I found that Android likes to cache some parts of an app while installing to improve the performance while runtime.

Is there a way to prevent Android from caching things from my app?

I am sharing my app via my website and users install and update the app manually. As soon as I update my app some Activities and Code-parts seems to be cached on their devices.

答:
You could delete your cache everytime before you update or before you close you application.
Code to clear the cache:

```<code> public static void trimCache(Context context) {
      try {
         File dir = context.getCacheDir();
         if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
         }
      } catch (Exception e) {
         // TODO: handle exception
      }
   }

   public static boolean deleteDir(File dir) {
      if (dir != null && dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }

      // The directory is now empty so delete it
      return dir.delete();
   }
</code>```

Call Trimcache when you want to clear the cache (before you update perhaps? or override the onStop() method, to clear the cache when the application is going to close.

Body:
You could delete your cache everytime before you update or before you close you application.
Code to clear the cache:

 public static void trimCache(Context context) {
      try {
         File dir = context.getCacheDir();
         if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
         }
      } catch (Exception e) {
         // TODO: handle exception
      }
   }

   public static boolean deleteDir(File dir) {
      if (dir != null && dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }

      // The directory is now empty so delete it
      return dir.delete();
   }

Call Trimcache when you want to clear the cache (before you update perhaps? or override the onStop() method, to clear the cache when the application is going to close.


问:
Android fingerprint detect new finger added
How to detect if the user add new fingerprint to Android settings after he/she authenticate finger inside my application ?

i.e. iOS have something called (evaluatedPolicyDomainState) to detect changes in fingerprint catalog what is the alternative in Android ?

This require for security reasons to prompt password in this case

答:
From the documentation for setUserAuthenticationRequired:

The key will become irreversibly invalidated once the secure lock screen is disabled (reconfigured to None, Swipe or other mode which does not authenticate the user) or when the secure lock screen is forcibly reset (e.g., by a Device Administrator). Additionally, if the key requires that user authentication takes place for every use of the key, it is also irreversibly invalidated once a new fingerprint is enrolled or once no more fingerprints are enrolled, unless setInvalidatedByBiometricEnrollment(boolean) is used to allow validity after enrollment. Attempts to initialize cryptographic operations using such keys will throw KeyPermanentlyInvalidatedException.

So to check if any new fingerprints have been enrolled since you created your fingerprint-associated key, just create a cipher with that key and try to init the cipher. If any new fingerprints have been enrolled, the init call should trigger a KeyPermanentlyInvalidatedException.


问:
how to get the latest checkout commit on git branch?
I am looking to make a software update using git. It means that the client has a local clone of the remote git repository and from a swing interface it will see the children commits of his current commit, meaning all commits newer than his current commit.

Then the client will check the desired commit from the list of the newer commits and make an update to that commit.

In order to execute git commands, I create few methods using ProcessBuilder.

To test the behavior I have 2 local repositories, and one remote repository.
1. in localRepo1 I clone the remoteRepo, then I write a text into a newFile and I commit it, then push it.
2 in localRepo2 I clone the remoteRepo: it is now a full copy of the remote repo, so it have the newFile also.
3 from the localRepo1 I am writing a newFile2 containing another text and push it to the remote repository.
4 from the localRepo2 I want to see the difference that I only have a commit, not 2. I mean, in localRepo2 I only have the newFile, not the files newFile and newFile2.

I am testing with 2 terminals: int the first I am in the directory localRepo1, and the second terminal is in the directory localRepo2.

executing

```<code>git rev-list --all --date-order
</code>```

in each local repos, then I can clearly see the differences:

localRepo1:

```<code>82d8715010cab1a6649ebecb6adeff9c3c88d85f
a2ad1c5ab691fc63a283d7dde85014606ed85f62
c8757e4f8ff318260577e479e3c9146f79aebacf
</code>```

localRepo2:

```<code>a2ad1c5ab691fc63a283d7dde85014606ed85f62
c8757e4f8ff318260577e479e3c9146f79aebacf
</code>```

I am looking for a command to see that missing commit:

```<code>82d8715010cab1a6649ebecb6adeff9c3c88d85f
</code>```

This missing commit is the one that the client will see into a swing component (comboBox for example - there can be more missing commits) and can check to update to.

How can I see these differences?

答:
I found a satisfying solution:

```<code>git fetch origin
</code>```

then

```<code>git whatchanged ..origin/<branchName>
</code>```

exp:

```<code>git whatchanged ..origin/maste
</code>```

Body:
I am looking to make a software update using git. It means that the client has a local clone of the remote git repository and from a swing interface it will see the children commits of his current commit, meaning all commits newer than his current commit.

Then the client will check the desired commit from the list of the newer commits and make an update to that commit.

In order to execute git commands, I create few methods using ProcessBuilder.

To test the behavior I have 2 local repositories, and one remote repository.
1. in localRepo1 I clone the remoteRepo, then I write a text into a newFile and I commit it, then push it.
2 in localRepo2 I clone the remoteRepo: it is now a full copy of the remote repo, so it have the newFile also.
3 from the localRepo1 I am writing a newFile2 containing another text and push it to the remote repository.
4 from the localRepo2 I want to see the difference that I only have a commit, not 2. I mean, in localRepo2 I only have the newFile, not the files newFile and newFile2.

I am testing with 2 terminals: int the first I am in the directory localRepo1, and the second terminal is in the directory localRepo2.

executing

git rev-list --all --date-order

in each local repos, then I can clearly see the differences:

localRepo1:

82d8715010cab1a6649ebecb6adeff9c3c88d85f
a2ad1c5ab691fc63a283d7dde85014606ed85f62
c8757e4f8ff318260577e479e3c9146f79aebacf

localRepo2:

a2ad1c5ab691fc63a283d7dde85014606ed85f62
c8757e4f8ff318260577e479e3c9146f79aebacf

I am looking for a command to see that missing commit:

82d8715010cab1a6649ebecb6adeff9c3c88d85f

This missing commit is the one that the client will see into a swing component (comboBox for example - there can be more missing commits) and can check to update to.

How can I see these differences?

Body:
I found a satisfying solution:

git fetch origin

then

git whatchanged ..origin/<branchName>

exp:

git whatchanged ..origin/maste


问:
Platform specific testing using Jest on a React Native app
This is the react native component

```<code>//Test.js

export default class Test extends Component {
    render() {
        return(
            <View>
                </Animated.View> {
                  Platform.OS === 'android' &&
                  <TouchableNativeFeedback>
                    // some android specific code
                  </TouchableNativeFeedback>
                }</Animated.View>
            </View>
        )
    }
}
</code>```

THis is the test case;

```<code>//testcases.js
import { Text, TouchableOpacity, Platform } from 'react-native';
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import Test from '../Test'

describe('Testing an App', () => {
    let snapshot;

    beforeAll(() => {
        snapshot = shallow(<Test />);
        Platform.OS = 'android';
    });
    it(' -- must return 1', () => {
      expect(snapshot.find('TouchableNativeFeedback').length).toBe(1);
    });
});
</code>```

While the expected return is 1; The received value is 0; I have set up Platform as 'android' and yet no luck.

I am new to Mobile automation testing; Hence I could be missing something obvious. Should I use react-dom to render and test further?

I feel it's something very obvious, but can't get my finger on it.

This is my package.json

```<code>{
  "name": "exampleApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "15.4.1",
    "react-native": "0.42.3"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    "jest": "20.0.4",
    "enzyme" : "2.8.0",
    "react-dom": "15.4.1",
    "react-addons-test-utils":"15.4.1",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答: You can not change your platform directly in your test. You need to set the desired platform in your settings. Take a look at this documentation to see how to do it.</p>

Body:
This is the react native component

//Test.js

export default class Test extends Component {
    render() {
        return(
            <View>
                </Animated.View> {
                  Platform.OS === 'android' &&
                  <TouchableNativeFeedback>
                    // some android specific code
                  </TouchableNativeFeedback>
                }</Animated.View>
            </View>
        )
    }
}

THis is the test case;

//testcases.js
import { Text, TouchableOpacity, Platform } from 'react-native';
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import Test from '../Test'

describe('Testing an App', () => {
    let snapshot;

    beforeAll(() => {
        snapshot = shallow(<Test />);
        Platform.OS = 'android';
    });
    it(' -- must return 1', () => {
      expect(snapshot.find('TouchableNativeFeedback').length).toBe(1);
    });
});

While the expected return is 1; The received value is 0; I have set up Platform as 'android' and yet no luck.

I am new to Mobile automation testing; Hence I could be missing something obvious. Should I use react-dom to render and test further?

I feel it's something very obvious, but can't get my finger on it.

This is my package.json

{
  "name": "exampleApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "15.4.1",
    "react-native": "0.42.3"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "2.0.0",
    "jest": "20.0.4",
    "enzyme" : "2.8.0",
    "react-dom": "15.4.1",
    "react-addons-test-utils":"15.4.1",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}


问:
Expected singleton odoo 9
After enter 2 and more new row in tree view and click on save get error

```<code>  raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: my.model(2116, 2117)
</code>```

My source code:

```<code>@api.depends('start', 'finish','stop')
def total_fun(self):
    time1 = datetime.strptime(self.start, "%Y-%m-%d %H:%M:%S")
    time2 = datetime.strptime(self.finish, "%Y-%m-%d %H:%M:%S")
    self.total = round(((time2 - time1).seconds / float(60*60) - self.stop))
</code>```

答:
Error message says -> expected singleton this means: you are using recordset instead of record.

To fix this use

```<code>for rec in self:
</code>```

in the begining of function, and then use rec instead of self

Title: Expected singleton odoo 9

Body:
After enter 2 and more new row in tree view and click on save get error

  raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: my.model(2116, 2117)

My source code:

@api.depends('start', 'finish','stop')
def total_fun(self):
    time1 = datetime.strptime(self.start, "%Y-%m-%d %H:%M:%S")
    time2 = datetime.strptime(self.finish, "%Y-%m-%d %H:%M:%S")
    self.total = round(((time2 - time1).seconds / float(60*60) - self.stop))

Body:
Error message says -> expected singleton this means: you are using recordset instead of record.

To fix this use

for rec in self:

in the begining of function, and then use rec instead of self


问:
How to change color in ExpandableRecyclerView
I am using this library but I can't get to a way to change the group background color from white.

EDIT: the xml files as requested in comments:

content_main.xml

the content_main file which include the expandable recyclerview

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</LinearLayout>
</code>```

activity_main.xml

the main activity

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="#64dd17"
    tools:context="ayalma.ir.sample.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>
</code>```

row_drawer.xml

the custom row layout

```<code> <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#ffb74d">
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/carbon_toolbarHeight"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/carbon_padding"
        android:paddingRight="@dimen/carbon_padding" />

    </LinearLayout>
</code>```

答:
Remove your previous library from Gradle

```<code>compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'
</code>```

Add this library to your Gradle

```<code>compile 'com.nineoldandroids:library:2.4.0'
</code>```

Copy this file to your package

```<code>import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;

public class ExpandableRecyclerView extends android.support.v7.widget.RecyclerView {
    public ExpandableRecyclerView(Context context) {
        super(context, null);
        initRecycler();
    }

    public ExpandableRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRecycler();
    }

    public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initRecycler();
    }

    private void initRecycler() {
        setClipToPadding(false);
        setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public Parcelable onSaveInstanceState() {
        //begin boilerplate code that allows parent classes to save state
        Parcelable superState = super.onSaveInstanceState();

        SavedState ss = new SavedState(superState);
        //end

        if (getAdapter() != null)
            ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();

        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        //begin boilerplate code so parent classes can restore state
        if (!(state instanceof SavedState))  // if state is not instance of out SaveState just restore in reg way
        {
            super.onRestoreInstanceState(state);
            return;
        }
        // else if cast him to SavedState

        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        //end

        if (getAdapter() != null)
            ((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);
    }

    static class SavedState implements Parcelable {
        public static final SavedState EMPTY_STATE = new SavedState() {
        };

        SparseBooleanArray stateToSave;
        Parcelable superState;

        SavedState() {
            superState = null;
        }

        SavedState(Parcelable superState) {
            this.superState = superState != EMPTY_STATE ? superState : null;
        }

        private SavedState(Parcel in) {
            Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());
            this.superState = superState != null ? superState : EMPTY_STATE;
            this.stateToSave = in.readSparseBooleanArray();
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(@NonNull Parcel out, int flags) {
            out.writeParcelable(superState, flags);
            out.writeSparseBooleanArray(this.stateToSave);
        }

        public Parcelable getSuperState() {
            return superState;
        }

        //required field that makes Parcelables from a Parcel
        public static final Creator<SavedState> CREATOR =
                new Creator<SavedState>() {
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }

    @Override
    public void setAdapter(android.support.v7.widget.RecyclerView.Adapter adapter) {
        if (!(adapter instanceof Adapter))
            throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");
        super.setAdapter(adapter);
    }

    public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {

        private OnChildItemClickedListener onChildItemClickedListener;

        private static final int TYPE_HEADER = 0;

        SparseBooleanArray expanded = new SparseBooleanArray();

        public Adapter() {
        }

        boolean isExpanded(int group) {
            return expanded.get(group);
        }

        SparseBooleanArray getExpandedGroups() {
            return expanded;
        }

        public void setExpandedGroups(SparseBooleanArray expanded) {
            this.expanded = expanded;
        }

        public void expand(int group) {
            if (isExpanded(group))
                return;

            // this lines of code calculate number of shown item in recycler view. also group is counting .
            int position = 0;
            for (int i = 0; i < group; i++) {
                position++;
                if (isExpanded(i))
                    position += getChildItemCount(i);
            }
            position++; // this for percent group

            notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding
            expanded.put(group, true); // save expanding in sparce array
        }

        public void collapse(int group) {
            if (!isExpanded(group)) // if is not expanded . so nothing to collapse.
                return;

            int position = 0;
            for (int i = 0; i < group; i++) {
                position++;
                if (isExpanded(i))
                    position += getChildItemCount(i); // item
            }
            position++;
            notifyItemRangeRemoved(position, getChildItemCount(group));
            expanded.put(group, false);
        }

        public abstract int getGroupItemCount();

        public abstract int getChildItemCount(int group);

        @Override
        public int getItemCount() {
            int count = 0;
            for (int i = 0; i <= getGroupItemCount(); i++) {
                count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;
            }
            return count;
        }

        public abstract G getGroupItem(int position);

        public abstract C getChildItem(int group, int position);

        public Object getItem(int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group))
                        return getChildItem(group, i);
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0)
                    return getGroupItem(group);
            }
            throw new IndexOutOfBoundsException();
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group)) {
                        onBindChildViewHolder((CVH) holder, group, i);
                        return;
                    }
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0) {
                    onBindGroupViewHolder((GVH) holder, group);
                    return;
                }
            }
            throw new IndexOutOfBoundsException();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);
        }

        protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);

        protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);

        public abstract int getChildItemViewType(int group, int position);

        @Override
        public int getItemViewType(int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group))
                        return getChildItemViewType(group, i);
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0)
                    return TYPE_HEADER;
            }
            throw new IndexOutOfBoundsException();
        }

        public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {
            this.onChildItemClickedListener = onItemClickedListener;
        }

        public void onBindChildViewHolder(CVH holder, final int group, final int position) {
            holder.itemView.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (Adapter.this.onChildItemClickedListener != null) {
                        Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);
                    }

                }
            });
        }

        public void onBindGroupViewHolder(final GVH holder, final int group) {
            if (holder instanceof GroupViewHolder)
                ((GroupViewHolder) holder).setExpanded(isExpanded(group));

            holder.itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isExpanded(group)) {
                        collapse(group);
                        if (holder instanceof GroupViewHolder)
                            ((GroupViewHolder) holder).collapse();
                    } else {
                        expand(group);
                        if (holder instanceof GroupViewHolder)
                            ((GroupViewHolder) holder).expand();
                    }
                }
            });
        }
    }

    public static abstract class GroupViewHolder extends RecyclerView.ViewHolder {

        public GroupViewHolder(View itemView) {
            super(itemView);
        }

        public abstract void expand();

        public abstract void collapse();

        public abstract void setExpanded(boolean expanded);

        public abstract boolean isExpanded();
    }

    public static class SimpleGroupViewHolder extends GroupViewHolder {
        ImageView expandedIndicator;
        TextView text;
        private boolean expanded;

        public SimpleGroupViewHolder(Context context) {
            super(View.inflate(context, R.layout.exr_group, null));

            itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
            text = (TextView) itemView.findViewById(R.id.carbon_groupText);
        }

        public void expand() {
            ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
            animator.setInterpolator(new DecelerateInterpolator());
            animator.setDuration(200);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
                    expandedIndicator.postInvalidate();
                }
            });
            animator.start();
            expanded = true;
        }

        public void collapse() {
            ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
            animator.setInterpolator(new DecelerateInterpolator());
            animator.setDuration(200);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
                    expandedIndicator.postInvalidate();
                }
            });
            animator.start();
            expanded = false;
        }

        public void setExpanded(boolean expanded) {
            ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
            this.expanded = expanded;
        }

        @Override
        public boolean isExpanded() {
            return expanded;
        }

        public void setText(String t) {
            text.setText(t);
        }

        public String getText() {
            return text.getText().toString();
        }
    }

    public interface OnChildItemClickedListener {
        void onChildItemClicked(int group, int position);
    }

}
</code>```

group xml copy to layout folder

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fefefe"
    android:clickable="true"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/carbon_groupText"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_weight="1"
        android:gravity="center_vertical" />

    <ImageView
        android:id="@+id/carbon_groupExpandedIndicator"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center_vertical"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:tint="#000000"
        app:srcCompat="@drawable/ic_expand_more_24dp" />

</LinearLayout>
</code>```

copy inside drawable folder

```<code><?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z"/>
</vector>
</code>```

Now user this inside your xml

```<code><com.example.package.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</code>```

instead of

```<code> <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</code>```

Body:
I am using this library but I can't get to a way to change the group background color from white.

EDIT: the xml files as requested in comments:

content_main.xml

the content_main file which include the expandable recyclerview

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />
</LinearLayout>

activity_main.xml

the main activity

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="#64dd17"
    tools:context="ayalma.ir.sample.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>

row_drawer.xml

the custom row layout

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#ffb74d">
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/carbon_toolbarHeight"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/carbon_padding"
        android:paddingRight="@dimen/carbon_padding" />

    </LinearLayout>

Body:
Remove your previous library from Gradle

compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'

Add this library to your Gradle

compile 'com.nineoldandroids:library:2.4.0'

Copy this file to your package

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;

public class ExpandableRecyclerView extends android.support.v7.widget.RecyclerView {
    public ExpandableRecyclerView(Context context) {
        super(context, null);
        initRecycler();
    }

    public ExpandableRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRecycler();
    }

    public ExpandableRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initRecycler();
    }

    private void initRecycler() {
        setClipToPadding(false);
        setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public Parcelable onSaveInstanceState() {
        //begin boilerplate code that allows parent classes to save state
        Parcelable superState = super.onSaveInstanceState();

        SavedState ss = new SavedState(superState);
        //end

        if (getAdapter() != null)
            ss.stateToSave = ((Adapter) this.getAdapter()).getExpandedGroups();

        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        //begin boilerplate code so parent classes can restore state
        if (!(state instanceof SavedState))  // if state is not instance of out SaveState just restore in reg way
        {
            super.onRestoreInstanceState(state);
            return;
        }
        // else if cast him to SavedState

        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        //end

        if (getAdapter() != null)
            ((Adapter) getAdapter()).setExpandedGroups(ss.stateToSave);
    }

    static class SavedState implements Parcelable {
        public static final SavedState EMPTY_STATE = new SavedState() {
        };

        SparseBooleanArray stateToSave;
        Parcelable superState;

        SavedState() {
            superState = null;
        }

        SavedState(Parcelable superState) {
            this.superState = superState != EMPTY_STATE ? superState : null;
        }

        private SavedState(Parcel in) {
            Parcelable superState = in.readParcelable(ExpandableRecyclerView.class.getClassLoader());
            this.superState = superState != null ? superState : EMPTY_STATE;
            this.stateToSave = in.readSparseBooleanArray();
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(@NonNull Parcel out, int flags) {
            out.writeParcelable(superState, flags);
            out.writeSparseBooleanArray(this.stateToSave);
        }

        public Parcelable getSuperState() {
            return superState;
        }

        //required field that makes Parcelables from a Parcel
        public static final Creator<SavedState> CREATOR =
                new Creator<SavedState>() {
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }

    @Override
    public void setAdapter(android.support.v7.widget.RecyclerView.Adapter adapter) {
        if (!(adapter instanceof Adapter))
            throw new IllegalArgumentException("adapter has to be of type ExpandableRecyclerView.Adapter");
        super.setAdapter(adapter);
    }

    public static abstract class Adapter<CVH extends ViewHolder, GVH extends ViewHolder, C, G> extends RecyclerView.Adapter<ViewHolder> {

        private OnChildItemClickedListener onChildItemClickedListener;

        private static final int TYPE_HEADER = 0;

        SparseBooleanArray expanded = new SparseBooleanArray();

        public Adapter() {
        }

        boolean isExpanded(int group) {
            return expanded.get(group);
        }

        SparseBooleanArray getExpandedGroups() {
            return expanded;
        }

        public void setExpandedGroups(SparseBooleanArray expanded) {
            this.expanded = expanded;
        }

        public void expand(int group) {
            if (isExpanded(group))
                return;

            // this lines of code calculate number of shown item in recycler view. also group is counting .
            int position = 0;
            for (int i = 0; i < group; i++) {
                position++;
                if (isExpanded(i))
                    position += getChildItemCount(i);
            }
            position++; // this for percent group

            notifyItemRangeInserted(position, getChildItemCount(group)); // notify recycler view for expanding
            expanded.put(group, true); // save expanding in sparce array
        }

        public void collapse(int group) {
            if (!isExpanded(group)) // if is not expanded . so nothing to collapse.
                return;

            int position = 0;
            for (int i = 0; i < group; i++) {
                position++;
                if (isExpanded(i))
                    position += getChildItemCount(i); // item
            }
            position++;
            notifyItemRangeRemoved(position, getChildItemCount(group));
            expanded.put(group, false);
        }

        public abstract int getGroupItemCount();

        public abstract int getChildItemCount(int group);

        @Override
        public int getItemCount() {
            int count = 0;
            for (int i = 0; i <= getGroupItemCount(); i++) {
                count += isExpanded(i) ? getChildItemCount(i) + 1 : 1;
            }
            return count;
        }

        public abstract G getGroupItem(int position);

        public abstract C getChildItem(int group, int position);

        public Object getItem(int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group))
                        return getChildItem(group, i);
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0)
                    return getGroupItem(group);
            }
            throw new IndexOutOfBoundsException();
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group)) {
                        onBindChildViewHolder((CVH) holder, group, i);
                        return;
                    }
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0) {
                    onBindGroupViewHolder((GVH) holder, group);
                    return;
                }
            }
            throw new IndexOutOfBoundsException();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return viewType == TYPE_HEADER ? onCreateGroupViewHolder(parent) : onCreateChildViewHolder(parent, viewType);
        }

        protected abstract GVH onCreateGroupViewHolder(ViewGroup parent);

        protected abstract CVH onCreateChildViewHolder(ViewGroup parent, int viewType);

        public abstract int getChildItemViewType(int group, int position);

        @Override
        public int getItemViewType(int i) {
            int group = 0;
            while (group <= getGroupItemCount()) {
                if (i > 0 && !isExpanded(group)) {
                    i--;
                    group++;
                    continue;
                }
                if (i > 0 && isExpanded(group)) {
                    i--;
                    if (i < getChildItemCount(group))
                        return getChildItemViewType(group, i);
                    i -= getChildItemCount(group);
                    group++;
                    continue;
                }
                if (i == 0)
                    return TYPE_HEADER;
            }
            throw new IndexOutOfBoundsException();
        }

        public void setOnChildItemClickedListener(OnChildItemClickedListener onItemClickedListener) {
            this.onChildItemClickedListener = onItemClickedListener;
        }

        public void onBindChildViewHolder(CVH holder, final int group, final int position) {
            holder.itemView.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (Adapter.this.onChildItemClickedListener != null) {
                        Adapter.this.onChildItemClickedListener.onChildItemClicked(group, position);
                    }

                }
            });
        }

        public void onBindGroupViewHolder(final GVH holder, final int group) {
            if (holder instanceof GroupViewHolder)
                ((GroupViewHolder) holder).setExpanded(isExpanded(group));

            holder.itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isExpanded(group)) {
                        collapse(group);
                        if (holder instanceof GroupViewHolder)
                            ((GroupViewHolder) holder).collapse();
                    } else {
                        expand(group);
                        if (holder instanceof GroupViewHolder)
                            ((GroupViewHolder) holder).expand();
                    }
                }
            });
        }
    }

    public static abstract class GroupViewHolder extends RecyclerView.ViewHolder {

        public GroupViewHolder(View itemView) {
            super(itemView);
        }

        public abstract void expand();

        public abstract void collapse();

        public abstract void setExpanded(boolean expanded);

        public abstract boolean isExpanded();
    }

    public static class SimpleGroupViewHolder extends GroupViewHolder {
        ImageView expandedIndicator;
        TextView text;
        private boolean expanded;

        public SimpleGroupViewHolder(Context context) {
            super(View.inflate(context, R.layout.exr_group, null));

            itemView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            expandedIndicator = (ImageView) itemView.findViewById(R.id.carbon_groupExpandedIndicator);
            text = (TextView) itemView.findViewById(R.id.carbon_groupText);
        }

        public void expand() {
            ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
            animator.setInterpolator(new DecelerateInterpolator());
            animator.setDuration(200);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
                    expandedIndicator.postInvalidate();
                }
            });
            animator.start();
            expanded = true;
        }

        public void collapse() {
            ValueAnimator animator = ValueAnimator.ofFloat(1, 0);
            animator.setInterpolator(new DecelerateInterpolator());
            animator.setDuration(200);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    ViewHelper.setRotation(expandedIndicator, 180 * (float) (animation.getAnimatedValue()));
                    expandedIndicator.postInvalidate();
                }
            });
            animator.start();
            expanded = false;
        }

        public void setExpanded(boolean expanded) {
            ViewHelper.setRotation(expandedIndicator, expanded ? 180 : 0);
            this.expanded = expanded;
        }

        @Override
        public boolean isExpanded() {
            return expanded;
        }

        public void setText(String t) {
            text.setText(t);
        }

        public String getText() {
            return text.getText().toString();
        }
    }

    public interface OnChildItemClickedListener {
        void onChildItemClicked(int group, int position);
    }

}

group xml copy to layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fefefe"
    android:clickable="true"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/carbon_groupText"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_weight="1"
        android:gravity="center_vertical" />

    <ImageView
        android:id="@+id/carbon_groupExpandedIndicator"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center_vertical"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:tint="#000000"
        app:srcCompat="@drawable/ic_expand_more_24dp" />

</LinearLayout>

copy inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M16.59,8.59L12,13.17 7.41,8.59 6,10l6,6 6,-6z"/>
</vector>

Now user this inside your xml

<com.example.package.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />

instead of

 <ayalma.ir.expandablerecyclerview.ExpandableRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false" />


问:
Forwarding a Django template dictionary to another template?
Is it possible to reuse a template dictionary in another view ?

For instance, imagine a view performs a search on the db and provide the search results in a dictionary to a template. The template displays the first 10 results and has a link to display  all the results in another page.

Is it possible to forward the template dictionary containing the search results to avoid having to perform the same search again ?

答:
Not really. You can't preserve anything across page views - except by storing it somewhere, eg in the session. You couldn't put it in the template itself, as that would then need to be sent back to the server via a POST for the next request.

In any case, there's not much need to do this. If you use the built-in Paginator class to paginate your search, Django will automatically use LIMIT and OFFSET in the query so that only the objects you're actually displaying will be queried.


问:
Copy Files don't begin with number char in Batch
how to copy files without begin number char in batch files

for example my Dir list its:

```<code>12red.pcx
9red.pcx
96blue.pcx
alipro.pcx
</code>```

then i need only copy alipro.pcx by batch

use this batch code for copy files begin with number char:

```<code>@echo off
set Design_path=D:\
set USB_path=E:\usb\
set t12=12*.pcx
set t9=9*.pcx
set t6=6*.pcx
set tsize=*.pcx
set design12=Dis_12
set design9=Dis_9
set design6=Dis_6
set designsize=D_Size
rem // Create Dir if not exist
if not exist %Design_path%%design12% (mkdir %Design_path%%design12%)
if not exist %Design_path%%design9% (mkdir %Design_path%%design9%)
if not exist %Design_path%%design6% (mkdir %Design_path%%design6%)
if not exist %Design_path%%designsize% (mkdir %Design_path%%designsize%)
if exist %USB_path%%t12% copy %USB_path%%t12% %Design_path%%design12%
if exist %USB_path%%t9% copy %USB_path%%t9% %Design_path%%design9%
if exist %USB_path%%t6% copy %USB_path%%t6% %Design_path%%design6%
</code>```

答:
now for copy any file without start in number 9 , 6 , 12

for example my list its:

```<code>3366.pcx
12gun.pcx
9ghost2.pcx
6bgre.pcx
avf.pcx
</code>```

i need only copy avf.pcx and 3366.pcx .

This my Code

```<code>for /f "delims=" %%a in ('dir %USB_path% /b *.pcx^|findstr /r /c:"^[^9][^6][^12]" ') do (
    echo %%a
    copy "%USB_path%%%a" "%Design_path%%designsize%"
  )
</code>```

Body:
how to copy files without begin number char in batch files

for example my Dir list its:

12red.pcx
9red.pcx
96blue.pcx
alipro.pcx

then i need only copy alipro.pcx by batch

use this batch code for copy files begin with number char:

@echo off
set Design_path=D:\
set USB_path=E:\usb\
set t12=12*.pcx
set t9=9*.pcx
set t6=6*.pcx
set tsize=*.pcx
set design12=Dis_12
set design9=Dis_9
set design6=Dis_6
set designsize=D_Size
rem // Create Dir if not exist
if not exist %Design_path%%design12% (mkdir %Design_path%%design12%)
if not exist %Design_path%%design9% (mkdir %Design_path%%design9%)
if not exist %Design_path%%design6% (mkdir %Design_path%%design6%)
if not exist %Design_path%%designsize% (mkdir %Design_path%%designsize%)
if exist %USB_path%%t12% copy %USB_path%%t12% %Design_path%%design12%
if exist %USB_path%%t9% copy %USB_path%%t9% %Design_path%%design9%
if exist %USB_path%%t6% copy %USB_path%%t6% %Design_path%%design6%

Body:
now for copy any file without start in number 9 , 6 , 12

for example my list its:

3366.pcx
12gun.pcx
9ghost2.pcx
6bgre.pcx
avf.pcx

i need only copy avf.pcx and 3366.pcx .

This my Code

for /f "delims=" %%a in ('dir %USB_path% /b *.pcx^|findstr /r /c:"^[^9][^6][^12]" ') do (
    echo %%a
    copy "%USB_path%%%a" "%Design_path%%designsize%"
  )