问:
Grails, executing a javascript by clicking on a column in a table row
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

```<code><td><g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link></td>
</code>```

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```

In the template _AvailableProductData.gsp:

```<code>    <g:each in="${prodBuffer}" status="i" var="pb">
  <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><a onclick="listOffers(${pb.id})">${pb.volumeOffered}</a></td>
</code>```

In the template _ListOffers.gsp:

```<code><div id="offerList">
    <g:set var="entityName" value='Offers' />
    <div id="list-offers" class="content scaffold-list" role="main">
        <h1><g:message code="default.list.label" args="[entityName]" /></h1>
        <table style="width:100%">
            <thead>
                <tr>
                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />
                </tr>
            </thead>
            <tbody>
                <g:each in="${offerDetails}" status="i" var="od">
                    <tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
                        <td><g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link></td>
                        <td>${od?.volumeOffered}</td>
                    </tr>
                </g:each>
            </tbody>
        </table>
        <div class="pagination">
            <g:paginate total="${offersCount ?: 0}" />
        </div>
    </div>
</div>
</code>```

In the controller:

```<code>def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

Added a printout to see what params contains:

```<code>def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}
</code>```

The printout is:

```<code>#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]
</code>```

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

```<code>    <script type="text/javascript">
        function availableProducts(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'availableProducts' )}',
                    data: [sawMill],
                    type: 'get'
            }).success( function ( data ) { $( '#divToUpdate' ).html( data ); });
        }

        function listOffers(){
            $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

        $( document ).ready( function() {
            $( '.offers' ).click( function ( event ){
                alert('HEJ')
                $.ajax({
                    url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
                    data: [this.id],
                    type: 'get'
                }).success( function ( data ) { $( '#offerList' ).html( data ); });
            });
        });
        $( document ).ready( function() {
            $('.test1').bind('click', function (){
            alert('KLICKED');
            });
        });

    </script>
</code>```

And the gsp-part in the template:

```<code>        <g:each in="${prodBuffer}" status="i" var="pb">
            <tr id="{$pb.id}" class="offers" class=" ${ (i % 2) == 0 ? 'even': 'odd'}">
                <td><g:checkBox name="toOffer" value="${pb.id}" checked="false"  /></td>
                <td><g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link></td>
                <td>${pb.sawMill}</td>
                <td>${pb.product}</td>
                <td>${pb.length}</td>
                <td>${pb.volumeAvailable}</td>
                <td><a  onclick='listOffers()' > ${pb.volumeOffered}</a></td>
</code>```

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
        <script type="text/javascript">
            $( document ).ready( function() {
                $( '.off1' ).click( function ( event ){
                    alert('HEJ');
                });
            });
        </script>
    </head>
    <body>
        <a href="#list-author" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content…"/></a>
        <div class="nav" role="navigation">
            <ul>
                <li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
                <li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
            </ul>
        </div>
        <div id="list-author" class="content scaffold-list" role="main">
            <h1><g:message code="default.list.label" args="[entityName]" /></h1>
            <g:if test="${flash.message}">
                <div class="message" role="status">${flash.message}</div>
            </g:if>
            <table>
                <th></th>
                <tbody
                    <g:each in="${authorList}" status='i' var='a'>
                        <tr id="${a.id}" class="off1">
                            <td><g:field  type="text" name="author" value="${a?.name}"/> </td>
                        </tr>
                    </g:each>
            <div class="pagination">
                <g:paginate total="${authorCount ?: 0}" />
            </div>
        </div>
    </body>
</html>
</code>```

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```0

-- Controller:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```1

-- Script A:

```<code>    <script type="text/javascript">
        function listOffers(id){
        $.ajax({
                url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
        data: [id],
        type: 'get'
        }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
    </script>
.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>
</code>```2

-- Script B:

```<code>        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });
</code>```

Script B: never respond - WHY?

Output from controller using script A:

```<code>### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]
</code>```

Modified script A -- data is empty:

```<code>        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }
</code>```

Output from controller using modified version of script A:

```<code>### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]
</code>```

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

答:
You need to change your  element like this

```<code><td><a onclick="listOffers(${pb.id})>${pb.volumeOffered}</a></td>
</code>```

and Jquery function which accept id.

```<code><script type="text/javascript">
    function listOffers(id){
    $.ajax({
            url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
    data: [id],
    type: 'get'
    }).success( function ( data ) { $( '#offerList' ).html( data ); });
    }
</script>
</code>```

Body:
I have a view consisting of two lists: products and offers. You can select several rows by checking checkboxes on them and then by clicking on a link, offer lines will be created for each selected product.
Every offer line has the id of the product which I will use to list all offers created for that product in a list below the list of products.

I tried to solve that by using a javascript which should be activated when you click on a link or field in the product list.
The script sends a message to the controller that creates the list of offers for this product and then render a template in this view.

I can just use a link and call the controller and the template will be rendered but of course not the rest of the view.

So I need to have line:

<g:link action="listOffers" id="${pb.id}">${pb.volumeOffered}</g:link>

replaced with something better that can call my javascript-function.
I read somewhere you could put an -onclick="javascript-function" in the g:link tag but it doesn't work.

Below is the most important part of controller and gsp in this case.

In the List.gsp:

.....
.....
    <g:render template="ListOffers" model="[offerDetails:offerDetails]"/>

In the template _AvailableProductData.gsp:

    <g:each in="${prodBuffer}" status="i" var="pb">

                ${pb.volumeOffered}

In the template _ListOffers.gsp:

    <g:set var="entityName" value='Offers' />

<g:message code="default.list.label" args="[entityName]" />

                    <g:sortableColumn property="product" title='Product' />
                    <g:sortableColumn property="volumeOffered" title='Volume' />

                <g:each in="${offerDetails}" status="i" var="od">

                        <g:link class="edit" action="edit" resource="offerDetail" id="${od?.id}"> ${od.product?.encodeAsHTML()}</g:link>
                        ${od?.volumeOffered}

                </g:each>

            <g:paginate total="${offersCount ?: 0}" />

In the controller:

def listOffers(){
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

Added a printout to see what params contains:

def listOffers(){
    System.out.println("#--#"+params)
    def List<OfferDetail> offerDetails = getOfferList()
    render(template:"ListOffers", model:[offerDetails: offerDetails])
}

The printout is:

#--#[undefined:, controller:ordersAndStore, format:null, action:listOffers]

Following is the complete javascript section, the first one is working good but then comes the onclick version that responds and calls the controller but can not send the id. Then comes your version and another one simple but no one is working.

And the gsp-part in the template:

        <g:each in="${prodBuffer}" status="i" var="pb">

                <g:checkBox name="toOffer" value="${pb.id}" checked="false"  />
                <g:link action="edit_prodbuffer" id="${pb.id}">${pb.id}</g:link>
                ${pb.sawMill}
                ${pb.product}
                ${pb.length}
                ${pb.volumeAvailable}
                 ${pb.volumeOffered}

==================================================

I have taken an old test project which I cleaned and modified to this simple example that still don't work:

<!DOCTYPE html>

        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>

        <g:message code="default.link.skip.label" default="Skip to content…"/>

<g:message code="default.home.label"/>

<g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link>

<g:message code="default.list.label" args="[entityName]" />

            <g:if test="${flash.message}">

${flash.message}

            </g:if>

                <tbody
                    <g:each in="${authorList}" status='i' var='a'>

                            <g:field  type="text" name="author" value="${a?.name}"/>

                    </g:each>

                <g:paginate total="${authorCount ?: 0}" />

I begin to be desperate, can't make this work but I must :(
I'll list the code again with some different settings and the output.
Sure something must be wrong with my code as others can make it work but what is wrong?

Part of the GSP-file where things start, there is two alternative lines one is commented here.

                <g:each in="${authorList}" status='i' var='a'>

                        <g:field  type="text" name="author" value="${a?.name}"/>

                </g:each>

-- Controller:

def listOffers() {
    System.out.println("### --- HEJ --- ### "+params)
}

-- Script A:

    function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [id],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

-- Script B:

        $( document ).ready( function() {
            $(".off1").click( function(event){
                alert('HEJ');
            });
        });

Script B: never respond - WHY?

Output from controller using script A:

### --- HEJ --- ### [undefined:, controller:author, format:null, action:listOffers, id:null]

Modified script A -- data is empty:

        function listOffers(id){
            alert('HEJ<<<<<<<<<<<<<<'+ id);
            $.ajax({
                url:'${g.createLink( controller:'author', action:'listOffers', id:"${id}" )}',
                data: [],
                type: 'get'
            }).success( function ( data ) { $( '#offerList' ).html( data ); });
        }

Output from controller using modified version of script A:

### --- HEJ --- ### [controller:author, format:null, action:listOffers, id:null]

The alert call works ok and I get the correct value of id there.
As yo can see from the controller printout id is null and if data contains id I also get 'undefined:' as a parameter.
If I remove id from data, now data[], this 'undefined:' disappear

Body:
You need to change your  element like this

<td><a onclick="listOffers(${pb.id})>${pb.volumeOffered}</a></td>

and Jquery function which accept id.

<script type="text/javascript">
    function listOffers(id){
    $.ajax({
            url:'${g.createLink( controller:'ordersAndStore', action:'listOffers' )}',
    data: [id],
    type: 'get'
    }).success( function ( data ) { $( '#offerList' ).html( data ); });
    }
</script>


来源: stackexchange

问:
Laravel 5.4 - Make view login error
I'm trying to do a controller for my site in this way

```<code>class MyController extends BaseController {

public function login()
{
    $this->layout->testata = View::make('OUT');
    $this->layout->content = View::make('auth.login');
}
</code>```

but Laravel says "Attempt to assign property of non-object".
What's the problem?

Basecontroller has only the contructor

```<code>class BaseController extends Controller {

    public $layout = 'a.main';
    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
            $this->layout = View::make($this->layout);
        }
    }

}
</code>```

Where is the problem?

答:
In your BaseController, you have a property named as $layout and its default value is a.main which is a string.

In your login method of MyController class you are setting the testata and content property of $layout property. But what that $layout property is holding? Its holding a string a.main. That string is not object that has neither testata property nor content property. That's why you are getting this error.

Now, you can claim that you are setting up that $layout property to an object in your setupLayout method of BaseController. But the question is, when the setupLayout is being called? There is no signed that the $layout property is holding any object without the initial default value a.main.

As a quick fix, you can call your setupLayout method in the constructor of the BaseController so that the $layout property will be set up while the BaseController will be initiated. Something as below:

```<code>class BaseController extends Controller {

    public $layout = 'a.main';

    public function __construct(){
        parent::__construct();
        $this->setupLayout();
    }

    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
            $this->layout = View::make($this->layout);
        }
    }
}
</code>```

Besides, To solve the you should add initialize the $layout variable to an object stdClass(Standard class of PHP) so that $layout property is no more an non-object. Then you can set your testata and content.

```<code>$this->layout = new \stdClass; //or new stdClass();
$this->layout->testata = View::make('OUT');
$this->layout->content = View::make('auth.login');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel 5.4 - Make view login error

Body:
I'm trying to do a controller for my site in this way

class MyController extends BaseController {

public function login()
{
    $this->layout->testata = View::make('OUT');
    $this->layout->content = View::make('auth.login');
}

but Laravel says "Attempt to assign property of non-object".
What's the problem?

Basecontroller has only the contructor

class BaseController extends Controller {

    public $layout = 'a.main';
    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
            $this->layout = View::make($this->layout);
        }
    }

}

Where is the problem?

Body:
In your BaseController, you have a property named as $layout and its default value is a.main which is a string.

In your login method of MyController class you are setting the testata and content property of $layout property. But what that $layout property is holding? Its holding a string a.main. That string is not object that has neither testata property nor content property. That's why you are getting this error.

Now, you can claim that you are setting up that $layout property to an object in your setupLayout method of BaseController. But the question is, when the setupLayout is being called? There is no signed that the $layout property is holding any object without the initial default value a.main.

As a quick fix, you can call your setupLayout method in the constructor of the BaseController so that the $layout property will be set up while the BaseController will be initiated. Something as below:

class BaseController extends Controller {

    public $layout = 'a.main';

    public function __construct(){
        parent::__construct();
        $this->setupLayout();
    }

    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
            $this->layout = View::make($this->layout);
        }
    }
}

Besides, To solve the you should add initialize the $layout variable to an object stdClass(Standard class of PHP) so that $layout property is no more an non-object. Then you can set your testata and content.

$this->layout = new \stdClass; //or new stdClass();
$this->layout->testata = View::make('OUT');
$this->layout->content = View::make('auth.login');


问:
SQL Server 2012+ : Merge elements by time periods
I have been struggling for a while now with that problem and I need some help.
I have the following query :

```<code>CREATE TABLE Example(
Start NVARCHAR(8),
Endd NVARCHAR(8),
Col1 NVARCHAR(2),
Col2 NVARCHAR(2));

INSERT into Example (Start,Endd,Col1,Col2)
VALUES ('20130801','20140316','02','01'),
('20140317','20140319','04','02'),
('20140320','20140320','04','02'),
('20140321','20140421','02','Z8'),
('20140422','20140429','02','Z9'),
('20140430','20140902','04','02'),
('20140903','20150201','04','02'),
('20150202','20150223','04','02'),
('20150224','20150527','04','02'),
('20150528','99991231','04','02')
;

select MIN(Start)AS Start,MAX(Endd) AS Endd,Col1,Col2 from
(
    SELECT top (100000000) Start, Endd,Col1, Col2,dense_rank() over(partition by Col1, Col2 order by Start,Endd) as rank
    ,LEAD (Col1) OVER (order by Start,Endd DESC) as l1
    ,LEAD (Col2) OVER (order by Start,Endd DESC) as l2
    ,LAG (Col1) OVER (order by Start,Endd DESC) as l11
    ,LAG (Col2) OVER (order by Start,Endd DESC) as l22
    FROM Example sp
    order by Start,Endd
)rq
GROUP BY Col1,Col2,case when (rq.l1=Col1 and rq.l2=Col2) or (rq.l11=Col1 and rq.l22=Col2)  then 0 else rank end
order by Start,Endd;
</code>```

My goal is to merge those data to have the following result:

However as you can see in the query result, when i have the same values for Col1 and Col2 on different time periods, the merge is not done correctly. It basically tries to merge them all in one, which create issues in the value for the new period.

Would someone be able to help me?

答:
You were getting close in your query and you may have found a solution by now. This is a classic Islands and Gaps problem. I am giving the longer version with no use of LEAD AND LAG. You can replace perhaps 45% of the code below by using those windowing functions with perhaps a dense rank.

```<code>DECLARE  @Example TABLE(
Start NVARCHAR(8),
Endd NVARCHAR(8),
Col1 NVARCHAR(2),
Col2 NVARCHAR(2));

INSERT into @Example (Start,Endd,Col1,Col2)
VALUES ('20130801','20140316','02','01'),
('20140317','20140319','04','02'),
('20140320','20140320','04','02'),
('20140321','20140421','02','Z8'),
('20140422','20140429','02','Z9'),
('20140430','20140902','04','02'),
('20140903','20150201','04','02'),
('20150202','20150223','04','02'),
('20150224','20150527','04','02'),
('20150528','99991231','04','02')

SELECT
    TableID=MAX(TableID),Col1=MAX(Col1),Col2=MAX(Col2),Start=MIN(Start),Endd=MAX(Endd)
FROM
(
    SELECT
        TableID,Col1,Col2,Start,Endd,ChangeID=MAX(ChangeOnlyTableID)
    FROM
    (
        SELECT
            AllRecords.TableID,AllRecords.Col1,AllRecords.Col2,AllRecords.Start,AllRecords.Endd,ChangeOnlyTableID=ChangesOnly.TableID
        FROM
        (
            SELECT * FROM
            (
                SELECT
                    This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
                    Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
                FROM
                (
                    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                )AS This
                LEFT OUTER JOIN
                (
                    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                )
                AS Next ON This.TableID=Next.TableID+1
            )
            AS ChangeMarkers
            WHERE Changed=1
        )
        AS AllRecords
        INNER JOIN
        (
            SELECT * FROM
            (
                SELECT
                    This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
                    Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
                FROM
                    (
                        SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                    ) AS This
                    LEFT OUTER JOIN
                    (
                        SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                    ) AS Next ON This.TableID=Next.TableID+1
            )
            AS ChangeMarkers
                WHERE Changed=1
        )
        AS ChangesOnly ON ChangesOnly.Col1=AllRecords.Col1 AND ChangesOnly.Col2=AllRecords.Col2 AND ChangesOnly.TableID<=AllRecords.TableID
    )AS JoinedResults
    GROUP BY
        TableID,Col1,Col2,Start,Endd
)
AS Final
GROUP BY
    Col1,Col2,ChangeID
ORDER BY
    MAX(TableID)
</code>```

You may choose to shorten this somewhat with a few CTE's to produce a query such as:

```<code>;WITH TableWithIDs AS
(
    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
)
,ChangeMarkers AS
(
    SELECT
        This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
        Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
    FROM
        TableWithIDs AS This
        LEFT OUTER JOIN TableWithIDs AS Next ON This.TableID=Next.TableID+1
)
,ChangesOnly AS
(
    SELECT * FROM ChangeMarkers WHERE Changed=1
)
,
JoinedResults AS
(
    SELECT
        AllRecords.TableID,AllRecords.Col1,AllRecords.Col2,AllRecords.Start,AllRecords.Endd,ChangeOnlyTableID=ChangesOnly.TableID
    FROM
        ChangeMarkers AllRecords
        INNER JOIN ChangesOnly ON ChangesOnly.Col1=AllRecords.Col1 AND ChangesOnly.Col2=AllRecords.Col2 AND ChangesOnly.TableID<=AllRecords.TableID
)

SELECT
    TableID=MAX(TableID),Col1=MAX(Col1),Col2=MAX(Col2),Start=MIN(Start),Endd=MAX(Endd)
FROM
(
    SELECT
        TableID,Col1,Col2,Start,Endd,ChangeID=MAX(ChangeOnlyTableID)
    FROM
        JoinedResults
    GROUP BY
        TableID,Col1,Col2,Start,Endd
)
AS Final
GROUP BY
    Col1,Col2,ChangeID
ORDER BY
    MAX(TableID)
</code>```

There are also some clever hacks that can be applied further using virtual keys however I went the most direct but more verbose route. You should be able to improve on this using a DENSE_RANK() with LEAD() OR LAG()

Body:
I have been struggling for a while now with that problem and I need some help.
I have the following query :

CREATE TABLE Example(
Start NVARCHAR(8),
Endd NVARCHAR(8),
Col1 NVARCHAR(2),
Col2 NVARCHAR(2));

INSERT into Example (Start,Endd,Col1,Col2)
VALUES ('20130801','20140316','02','01'),
('20140317','20140319','04','02'),
('20140320','20140320','04','02'),
('20140321','20140421','02','Z8'),
('20140422','20140429','02','Z9'),
('20140430','20140902','04','02'),
('20140903','20150201','04','02'),
('20150202','20150223','04','02'),
('20150224','20150527','04','02'),
('20150528','99991231','04','02')
;

select MIN(Start)AS Start,MAX(Endd) AS Endd,Col1,Col2 from
(
    SELECT top (100000000) Start, Endd,Col1, Col2,dense_rank() over(partition by Col1, Col2 order by Start,Endd) as rank
    ,LEAD (Col1) OVER (order by Start,Endd DESC) as l1
    ,LEAD (Col2) OVER (order by Start,Endd DESC) as l2
    ,LAG (Col1) OVER (order by Start,Endd DESC) as l11
    ,LAG (Col2) OVER (order by Start,Endd DESC) as l22
    FROM Example sp
    order by Start,Endd
)rq
GROUP BY Col1,Col2,case when (rq.l1=Col1 and rq.l2=Col2) or (rq.l11=Col1 and rq.l22=Col2)  then 0 else rank end
order by Start,Endd;

My goal is to merge those data to have the following result:

However as you can see in the query result, when i have the same values for Col1 and Col2 on different time periods, the merge is not done correctly. It basically tries to merge them all in one, which create issues in the value for the new period.

Would someone be able to help me?

Body:
You were getting close in your query and you may have found a solution by now. This is a classic Islands and Gaps problem. I am giving the longer version with no use of LEAD AND LAG. You can replace perhaps 45% of the code below by using those windowing functions with perhaps a dense rank.

DECLARE  @Example TABLE(
Start NVARCHAR(8),
Endd NVARCHAR(8),
Col1 NVARCHAR(2),
Col2 NVARCHAR(2));

INSERT into @Example (Start,Endd,Col1,Col2)
VALUES ('20130801','20140316','02','01'),
('20140317','20140319','04','02'),
('20140320','20140320','04','02'),
('20140321','20140421','02','Z8'),
('20140422','20140429','02','Z9'),
('20140430','20140902','04','02'),
('20140903','20150201','04','02'),
('20150202','20150223','04','02'),
('20150224','20150527','04','02'),
('20150528','99991231','04','02')

SELECT
    TableID=MAX(TableID),Col1=MAX(Col1),Col2=MAX(Col2),Start=MIN(Start),Endd=MAX(Endd)
FROM
(
    SELECT
        TableID,Col1,Col2,Start,Endd,ChangeID=MAX(ChangeOnlyTableID)
    FROM
    (
        SELECT
            AllRecords.TableID,AllRecords.Col1,AllRecords.Col2,AllRecords.Start,AllRecords.Endd,ChangeOnlyTableID=ChangesOnly.TableID
        FROM
        (
            SELECT * FROM
            (
                SELECT
                    This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
                    Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
                FROM
                (
                    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                )AS This
                LEFT OUTER JOIN
                (
                    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                )
                AS Next ON This.TableID=Next.TableID+1
            )
            AS ChangeMarkers
            WHERE Changed=1
        )
        AS AllRecords
        INNER JOIN
        (
            SELECT * FROM
            (
                SELECT
                    This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
                    Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
                FROM
                    (
                        SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                    ) AS This
                    LEFT OUTER JOIN
                    (
                        SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
                    ) AS Next ON This.TableID=Next.TableID+1
            )
            AS ChangeMarkers
                WHERE Changed=1
        )
        AS ChangesOnly ON ChangesOnly.Col1=AllRecords.Col1 AND ChangesOnly.Col2=AllRecords.Col2 AND ChangesOnly.TableID<=AllRecords.TableID
    )AS JoinedResults
    GROUP BY
        TableID,Col1,Col2,Start,Endd
)
AS Final
GROUP BY
    Col1,Col2,ChangeID
ORDER BY
    MAX(TableID)

You may choose to shorten this somewhat with a few CTE's to produce a query such as:

;WITH TableWithIDs AS
(
    SELECT TableID=ROW_NUMBER() OVER(ORDER BY Start,Endd,Col1,Col2),Start,Endd,Col1,Col2 FROM @Example
)
,ChangeMarkers AS
(
    SELECT
        This.Start,This.Endd,This.TableID,This.Col1,This.Col2,
        Changed=CASE WHEN (Next.Col1=This.Col1 AND Next.Col2=This.Col2) THEN 0 ELSE 1 END
    FROM
        TableWithIDs AS This
        LEFT OUTER JOIN TableWithIDs AS Next ON This.TableID=Next.TableID+1
)
,ChangesOnly AS
(
    SELECT * FROM ChangeMarkers WHERE Changed=1
)
,
JoinedResults AS
(
    SELECT
        AllRecords.TableID,AllRecords.Col1,AllRecords.Col2,AllRecords.Start,AllRecords.Endd,ChangeOnlyTableID=ChangesOnly.TableID
    FROM
        ChangeMarkers AllRecords
        INNER JOIN ChangesOnly ON ChangesOnly.Col1=AllRecords.Col1 AND ChangesOnly.Col2=AllRecords.Col2 AND ChangesOnly.TableID<=AllRecords.TableID
)

SELECT
    TableID=MAX(TableID),Col1=MAX(Col1),Col2=MAX(Col2),Start=MIN(Start),Endd=MAX(Endd)
FROM
(
    SELECT
        TableID,Col1,Col2,Start,Endd,ChangeID=MAX(ChangeOnlyTableID)
    FROM
        JoinedResults
    GROUP BY
        TableID,Col1,Col2,Start,Endd
)
AS Final
GROUP BY
    Col1,Col2,ChangeID
ORDER BY
    MAX(TableID)

There are also some clever hacks that can be applied further using virtual keys however I went the most direct but more verbose route. You should be able to improve on this using a DENSE_RANK() with LEAD() OR LAG()


问:
Display image in WPF from database
I have the following database:

and I would like to display all employees and their pictures in a listbox. Whenever I run my code, I receive an System.InvalidOperationException at this part of the code:

```<code>    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var list = db.Employees;
        list.Load();
        liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
    }
</code>```

This is my WPF code:

```<code><Window x:Class="NorthwindWPF.employeeList"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:NorthwindWPF"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="employeeList" Height="350" Width="300">
    <Grid>
        <ListBox x:Name="liemp"
            DisplayMemberPath="FirstName"
            SelectedValuePath="EmployeeID">
            <Image Source="{Binding PhotoPath}" />
        </ListBox>

    </Grid>
</Window>
</code>```

And this is my class code:

```<code>namespace NorthwindWPF
{
    /// <summary>
    /// Interaction logic for employeeList.xaml
    /// </summary>
    public partial class employeeList : Window
    {

        NorthwindEntities db = new NorthwindEntities();

        public employeeList()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var list = db.Employees;
            list.Load();
            liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
        }

    }
}
</code>```

答:
You have directly added a single Image item to the ListBox.

```<code><ListBox ...>
    <Image Source="{Binding PhotoPath}" /> <!-- here -->
</ListBox>
</code>```

Subsequently setting the ListBox's ItemsSource will then fail with an InvalidOperationException.

Instead of setting the ListBox's DisplayMemberPath property, you should define its ItemTemplate like this:

```<code><ListBox x:Name="liemp" SelectedValuePath="EmployeeID">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding PhotoPath}"/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Display image in WPF from database

Body:
I have the following database:

and I would like to display all employees and their pictures in a listbox. Whenever I run my code, I receive an System.InvalidOperationException at this part of the code:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var list = db.Employees;
        list.Load();
        liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
    }

This is my WPF code:

<Window x:Class="NorthwindWPF.employeeList"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:NorthwindWPF"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="employeeList" Height="350" Width="300">
    <Grid>
        <ListBox x:Name="liemp"
            DisplayMemberPath="FirstName"
            SelectedValuePath="EmployeeID">
            <Image Source="{Binding PhotoPath}" />
        </ListBox>

    </Grid>
</Window>

And this is my class code:

namespace NorthwindWPF
{
    ///
    /// Interaction logic for employeeList.xaml
    ///
    public partial class employeeList : Window
    {

        NorthwindEntities db = new NorthwindEntities();

        public employeeList()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var list = db.Employees;
            list.Load();
            liemp.ItemsSource = list.Local.OrderBy(l => l.LastName);
        }

    }
}

Body:
You have directly added a single Image item to the ListBox.

<ListBox ...>
    <Image Source="{Binding PhotoPath}" /> <!-- here -->
</ListBox>

Subsequently setting the ListBox's ItemsSource will then fail with an InvalidOperationException.

Instead of setting the ListBox's DisplayMemberPath property, you should define its ItemTemplate like this:

<ListBox x:Name="liemp" SelectedValuePath="EmployeeID">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding PhotoPath}"/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


问:
Automating MS Word in Server 2012 R2
Firstly, please don't reply with the generic advice not to automate Word on a server or a link to the MS web page on "how to automate word on a server if you really must". I am aware of this.

I have a process which runs as a Windows service and uses .Net OLE interop to automate Office (mostly just Open and SaveAs). This code has worked reliably for 8 years on literally hundreds of servers using many combinations of Windows and Office versions, both 32 and 64 bit, so I am happy that the mechanism is reliable. So far...

With Server 2012 R2, it works with PowerPoint and Excel but fails trying to open a word document:

```<code>System.Runtime.InteropServices.COMException (0x800A16A0):
  The file appears to be corrupted.
   at Microsoft.Office.Interop.Word.Documents.Open...
</code>```

My observations so far which may or may not be relevant:

fails on all documents

works fine in Windows 8.1

the same problem has happened both on a customer site and in our test environment, so is unlikely to be purely environmental

my application is using .Net 3.5

the code is linked against the 2003 Interop assemblies (obviously later office versions are supported by assembly binding redirection)

we have tried it with office 2013 both 32 and 64 bit with the same results, but not tried earlier versions of office

it fails whether the service is running as LocalSystem or as a standard user account

if we run the service process in the foreground (i.e. literally double-clicking on the executable) the problem does not happen

Obviously I still have things to investigate but interested to hear if anyone else has seen this specific problem even if you haven't solved it. Please note there are many difficulties and problems with office automation so unless your symptoms are very similar to mine, you probably don't have the same problem.

答: For some machines you need to run  " mmc comexp.msc /32 "  to set the DCOM setting for MS Word. I found that we needed to do this when 32 bit version of Word was installed only. </p>

Title: Automating MS Word in Server 2012 R2

Body:
Firstly, please don't reply with the generic advice not to automate Word on a server or a link to the MS web page on "how to automate word on a server if you really must". I am aware of this.

I have a process which runs as a Windows service and uses .Net OLE interop to automate Office (mostly just Open and SaveAs). This code has worked reliably for 8 years on literally hundreds of servers using many combinations of Windows and Office versions, both 32 and 64 bit, so I am happy that the mechanism is reliable. So far...

With Server 2012 R2, it works with PowerPoint and Excel but fails trying to open a word document:

System.Runtime.InteropServices.COMException (0x800A16A0):
  The file appears to be corrupted.
   at Microsoft.Office.Interop.Word.Documents.Open...

My observations so far which may or may not be relevant:

fails on all documents

works fine in Windows 8.1

the same problem has happened both on a customer site and in our test environment, so is unlikely to be purely environmental

my application is using .Net 3.5

the code is linked against the 2003 Interop assemblies (obviously later office versions are supported by assembly binding redirection)

we have tried it with office 2013 both 32 and 64 bit with the same results, but not tried earlier versions of office

it fails whether the service is running as LocalSystem or as a standard user account

if we run the service process in the foreground (i.e. literally double-clicking on the executable) the problem does not happen

Obviously I still have things to investigate but interested to hear if anyone else has seen this specific problem even if you haven't solved it. Please note there are many difficulties and problems with office automation so unless your symptoms are very similar to mine, you probably don't have the same problem.


问:
QT cast a widget to a combobox
I have a table[][] of widgets and depending on a value that I have I'll instantiate that widget to a QLabel or to a QCombobox.

```<code>QWidget *tab[9][9];

if(modele->firstvalue(i,j) ==0) {
    tab[i][j]= new QComboBox();
    tab[i][j]->setStyleSheet("border: 1px solid red");
    ((QComboBox)tab[i][j]).addItem("Test");

}
else {
    tab[i][j] = new QLabel(QString::number(modele->firstvalue(i,j)));
}
</code>```

So in my widget after the execution I see all the comboboxes but not with the values (no items added)

PS:
It's about a sudoku game. If there are a lot multiple values then I create a combobox with all the possible values, else a QLabel with a single value.

答:
The problem is in this line:

```<code>((QComboBox)tab[i][j]).addItem("Test");
</code>```

It's a bit obfuscated due to the C cast. Had you used the C++ cast, you'd write:

```<code>static_cast<QComboBox>(tab[i][j]).addItem("Test");
</code>```

The static_cast is redundant syntax, and it's now obvious that the code means:

```<code>QComboBox(tab[i][j]).addItem("Test");
</code>```

As you can see, you're creating a temporary combo box with tab[i][j] as the parent, then adding an item to it, and immediately destroying it when the scope is exited. The original combo box you've created 3 lines above it is not modified here.

Instead, you need to write (don't use C-style casts in C++):

```<code>static_cast<QComboBox*>(tab[i][j])->addItem("Test");
</code>```

Ideally, write the code so you won't need the cast at all:

```<code>auto box = new QComboBox;
box->setStyleSheet("border: 1px solid red");
box->addItem("Test");
tab[i][j] = box;
</code>```

Title: QT cast a widget to a combobox

Body:
I have a table[][] of widgets and depending on a value that I have I'll instantiate that widget to a QLabel or to a QCombobox.

QWidget *tab[9][9];

if(modele->firstvalue(i,j) ==0) {
    tab[i][j]= new QComboBox();
    tab[i][j]->setStyleSheet("border: 1px solid red");
    ((QComboBox)tab[i][j]).addItem("Test");

}
else {
    tab[i][j] = new QLabel(QString::number(modele->firstvalue(i,j)));
}

So in my widget after the execution I see all the comboboxes but not with the values (no items added)

PS:
It's about a sudoku game. If there are a lot multiple values then I create a combobox with all the possible values, else a QLabel with a single value.

Body:
The problem is in this line:

((QComboBox)tab[i][j]).addItem("Test");

It's a bit obfuscated due to the C cast. Had you used the C++ cast, you'd write:

static_cast<QComboBox>(tab[i][j]).addItem("Test");

The static_cast is redundant syntax, and it's now obvious that the code means:

QComboBox(tab[i][j]).addItem("Test");

As you can see, you're creating a temporary combo box with tab[i][j] as the parent, then adding an item to it, and immediately destroying it when the scope is exited. The original combo box you've created 3 lines above it is not modified here.

Instead, you need to write (don't use C-style casts in C++):

static_cast<QComboBox*>(tab[i][j])->addItem("Test");

Ideally, write the code so you won't need the cast at all:

auto box = new QComboBox;
box->setStyleSheet("border: 1px solid red");
box->addItem("Test");
tab[i][j] = box;


问:
Creating NSCollectionView with datasource programmatically
I am trying to create a NSCollectionView programmatically using a NSCollectionViewDataSource.

The code is very simple:

```<code>self.collectionView = [[NSCollectionView alloc] init];
// Add collection view to self.view etc.
self.collectionView.dataSource = self;
[self.collectionView registerClass:[NSCollectionViewItem class] forItemWithIdentifier:@"test"]
self.collectionView.collectionViewLayout = gridLayout;
[self.collectionView reloadData]
</code>```

This leads to the following methods getting called (if I don't set the collectionViewLayout property explicitly these two don't get called either):

```<code>- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView*)collectionView
- (NSInteger)collectionView:(NSCollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
</code>```

However, collectionView:itemForRepresentedObjectAtIndexPath: is never called. Is there something else that I need to do in order to make sure that the last data source method is called? I have made sure that the two count calls return > 0, so that's not the problem.

答:
I've been working through different scenario's in the past days, and I dare say that using an NSScrollView, or not, makes practically no difference. With or without scrollView, I've ended up with the same errors and limitations.

What does make a huge difference is the choice between "old school" and the new-fangled collectionView. By "old school" I mean setting the itemPrototype and contents properties, something like this:

```<code>    NSCollectionView *collectionView = [[NSCollectionView alloc] init];
    collectionView.itemPrototype = [TBCollectionViewItem new];
    collectionView.content = self.collectionItems;

    NSInteger index = 0;
    for (NSString *title in _collectionItems) {
        NSIndexPath *path = [NSIndexPath indexPathForItem:index inSection:0];
        TBCollectionViewItem *item = [collectionView makeItemWithIdentifier:@"Test" forIndexPath:path];
        item.representedObject = title;
        index++;
    }
    // Plays well with constraints
</code>```

New school, something along these lines:

```<code>NSCollectionView *collectionView = [[NSCollectionView alloc] init];
collectionView.identifier = TBCollectionViewIdentifier;

[collectionView registerClass:[TBCollectionViewItem class] forItemWithIdentifier:TBCollectionViewItemIdentifier]; //register before makeItemWithIdentifier:forIndexPath: is called.
TBCollectionViewGridLayout *gridLayout = [TBCollectionViewGridLayout collectionViewGridLayout:NSMakeSize(250, 100)]; //getting the contentSize from the scrollView does not help
collectionView.collectionViewLayout = gridLayout;
collectionView.dataSource = self;
</code>```

Now, you may have noticed the comment that registerClass: must be called before makeItemWithIdentifier:forIndexPath. In practice, that means calling registerClass: before setting .dataSource, whereas in your code you set .dataSource first. The docs state:

Although you can register new items at any time, you must not call the makeItemWithIdentifier:forIndexPath: method until after you register the corresponding item.

I wish I could say that by switching those two lines, all layout problems will be solved. Unfortunately, I've found that the .collectionViewLayout / .dataSource combination is a recipe for (auto)layout disaster. Whether that can be fixed by switching from NSCollectionViewGridLayout to flowLayout, I'm not yet certain.

Body:
I am trying to create a NSCollectionView programmatically using a NSCollectionViewDataSource.

The code is very simple:

self.collectionView = [[NSCollectionView alloc] init];
// Add collection view to self.view etc.
self.collectionView.dataSource = self;
[self.collectionView registerClass:[NSCollectionViewItem class] forItemWithIdentifier:@"test"]
self.collectionView.collectionViewLayout = gridLayout;
[self.collectionView reloadData]

This leads to the following methods getting called (if I don't set the collectionViewLayout property explicitly these two don't get called either):

- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView*)collectionView
- (NSInteger)collectionView:(NSCollectionView*)collectionView numberOfItemsInSection:(NSInteger)section

However, collectionView:itemForRepresentedObjectAtIndexPath: is never called. Is there something else that I need to do in order to make sure that the last data source method is called? I have made sure that the two count calls return > 0, so that's not the problem.

Body:
I've been working through different scenario's in the past days, and I dare say that using an NSScrollView, or not, makes practically no difference. With or without scrollView, I've ended up with the same errors and limitations.

What does make a huge difference is the choice between "old school" and the new-fangled collectionView. By "old school" I mean setting the itemPrototype and contents properties, something like this:

    NSCollectionView *collectionView = [[NSCollectionView alloc] init];
    collectionView.itemPrototype = [TBCollectionViewItem new];
    collectionView.content = self.collectionItems;

    NSInteger index = 0;
    for (NSString *title in _collectionItems) {
        NSIndexPath *path = [NSIndexPath indexPathForItem:index inSection:0];
        TBCollectionViewItem *item = [collectionView makeItemWithIdentifier:@"Test" forIndexPath:path];
        item.representedObject = title;
        index++;
    }
    // Plays well with constraints

New school, something along these lines:

NSCollectionView *collectionView = [[NSCollectionView alloc] init];
collectionView.identifier = TBCollectionViewIdentifier;

[collectionView registerClass:[TBCollectionViewItem class] forItemWithIdentifier:TBCollectionViewItemIdentifier]; //register before makeItemWithIdentifier:forIndexPath: is called.
TBCollectionViewGridLayout *gridLayout = [TBCollectionViewGridLayout collectionViewGridLayout:NSMakeSize(250, 100)]; //getting the contentSize from the scrollView does not help
collectionView.collectionViewLayout = gridLayout;
collectionView.dataSource = self;

Now, you may have noticed the comment that registerClass: must be called before makeItemWithIdentifier:forIndexPath. In practice, that means calling registerClass: before setting .dataSource, whereas in your code you set .dataSource first. The docs state:

Although you can register new items at any time, you must not call the makeItemWithIdentifier:forIndexPath: method until after you register the corresponding item.

I wish I could say that by switching those two lines, all layout problems will be solved. Unfortunately, I've found that the .collectionViewLayout / .dataSource combination is a recipe for (auto)layout disaster. Whether that can be fixed by switching from NSCollectionViewGridLayout to flowLayout, I'm not yet certain.


问:
PHP: Detecting references in $GLOBALS
I have a simple way to detect references in an array (For debugging purposes)

First I clone the array with array_values and then I alter the clone and look for changes in the original. If it's changed that element is a reference.

Short example:

```<code><?php

$a = [
    'a' => 'b',
    2 => 3,
];

$b = ['wow'];

$a['ref'] = &$b;

function getrefs($array) {
    $marker = uniqid();
    $copy = array_values($array);
    $i = 0;
    $return = [];
    foreach ($array as $key => &$val) {
        $stash = $val;
        $copy[$i] = $marker;
        if ($val === $marker) {
            $val = $stash;
            $return[] = $key;
        }
        $i++;
    }
    return $return;
}

var_dump($a);
var_dump(getrefs($a));
</code>```

The problem is that when I try to use this on $GLOBALS it's not working, and I can't figure out why. Everything in $GLOBALS should be a reference by all rights.

Is $GLOBALS just so strange that it's the only array where array_values won't correctly copy references?

答:
It's a possibility that you're not accounting for recursion. The built-in PHP function:

```<code>var_dump($GLOBALS);
</code>```

Will have the following output

```<code>array(7) {
   ["_GET"]=>
      array(0) {
   }
   ["_POST"]=>
      array(0) {
   }
   ["_COOKIE"]=>
      array(1) {
      ["PHPSESSID"]=>
      string(26) "od602et6qcfj6pa3pkjtl8go57"
   }
   ["_FILES"]=>
      array(0) {
   }
   ["GLOBALS"]=>
      *RECURSION*
   ["_SESSION"]=>
      &array(0) {
   }
}
</code>```

Title: PHP: Detecting references in $GLOBALS

Body:
I have a simple way to detect references in an array (For debugging purposes)

First I clone the array with array_values and then I alter the clone and look for changes in the original. If it's changed that element is a reference.

Short example:

<?php

$a = [
    'a' => 'b',
    2 => 3,
];

$b = ['wow'];

$a['ref'] = &$b;

function getrefs($array) {
    $marker = uniqid();
    $copy = array_values($array);
    $i = 0;
    $return = [];
    foreach ($array as $key => &$val) {
        $stash = $val;
        $copy[$i] = $marker;
        if ($val === $marker) {
            $val = $stash;
            $return[] = $key;
        }
        $i++;
    }
    return $return;
}

var_dump($a);
var_dump(getrefs($a));

The problem is that when I try to use this on $GLOBALS it's not working, and I can't figure out why. Everything in $GLOBALS should be a reference by all rights.

Is $GLOBALS just so strange that it's the only array where array_values won't correctly copy references?

Body:
It's a possibility that you're not accounting for recursion. The built-in PHP function:

var_dump($GLOBALS);

Will have the following output

array(7) {
   ["_GET"]=>
      array(0) {
   }
   ["_POST"]=>
      array(0) {
   }
   ["_COOKIE"]=>
      array(1) {
      ["PHPSESSID"]=>
      string(26) "od602et6qcfj6pa3pkjtl8go57"
   }
   ["_FILES"]=>
      array(0) {
   }
   ["GLOBALS"]=>
      *RECURSION*
   ["_SESSION"]=>
      &array(0) {
   }
}


问:
Passing data back to Django view
Inside of a table in my template I have the following which works great:

```<code><tbody>
{% for item in items %}
<tr>
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.status }}</td>
    <td>{{ item.start_time }}</td>
    <td>{{ item.end_time }}</td>
</tr>
</tbody>
</code>```

I would like to add a form that posts the items to a view.  I've tried this:

```<code><form align="center" action="{% url 'app:doit' %}" method="post" ><b></b>
{% csrf_token %}
    <input type="hidden" name="items" value="{{ items}}" />
    <input type="submit" name="export" value="Export" >
</form>
</code>```

but that doesn't work as I expected it would. The data comes into the view as a sequence of characters, something like this, ",..." How do I pass {{items}} back to a view so I can process the items as python objects?

The export method in my view contains this:

```<code>if 'items' in request.POST:
    my_items = request.POST['items']
</code>```

答:
You cannot POST a QuerSet back to a view. HTML form cannot understand a Django QuerySet. That would be nice, though!

What you can do is to create a custom template tag that would generate this:

```<code><input type="hidden" name="items" value="{% my_items items %}" />
</code>```

to this:

```<code><input type="hidden" name="items" value="1,2,5,7,8" />
</code>```

where these numbers are the id of each item. You can also use the name field if you like, since it's not very secure to expose the ids.

Then, once POSTed, inside the view I would do:

```<code>if 'items' in request.POST:
    # my_item_values is a str
    my_item_values = request.POST['items']
    try:
        my_item_values = my_item_values.split(',')
    except TypeError:
        # Handle error of conversion from string to list here
    else:
        # typecast succedded. Get your items!
        items = Item.objects.filter(id__in=my_item_values)  # This is a QuerySet
        # or this (if you used the names)
        items = Item.objects.filter(name__in=my_item_values)  # This is a QuerySet
</code>```

The custom template tag would look like this:

```<code>@register.simple_tag()
def my_items(items):
    return ','.join([item.name for item in items])
</code>```

Title: Passing data back to Django view

Body:
Inside of a table in my template I have the following which works great:

{% for item in items %}

    {{ item.id }}
    {{ item.name }}
    {{ item.status }}
    {{ item.start_time }}
    {{ item.end_time }}

I would like to add a form that posts the items to a view.  I've tried this:

<form align="center" action="{% url 'app:doit' %}" method="post" >
{% csrf_token %}
    <input type="hidden" name="items" value="{{ items}}" />
    <input type="submit" name="export" value="Export" >
</form>

but that doesn't work as I expected it would. The data comes into the view as a sequence of characters, something like this, ",..." How do I pass {{items}} back to a view so I can process the items as python objects?

The export method in my view contains this:

if 'items' in request.POST:
    my_items = request.POST['items']

Body:
You cannot POST a QuerSet back to a view. HTML form cannot understand a Django QuerySet. That would be nice, though!

What you can do is to create a custom template tag that would generate this:

<input type="hidden" name="items" value="{% my_items items %}" />

to this:

<input type="hidden" name="items" value="1,2,5,7,8" />

where these numbers are the id of each item. You can also use the name field if you like, since it's not very secure to expose the ids.

Then, once POSTed, inside the view I would do:

if 'items' in request.POST:
    # my_item_values is a str
    my_item_values = request.POST['items']
    try:
        my_item_values = my_item_values.split(',')
    except TypeError:
        # Handle error of conversion from string to list here
    else:
        # typecast succedded. Get your items!
        items = Item.objects.filter(id__in=my_item_values)  # This is a QuerySet
        # or this (if you used the names)
        items = Item.objects.filter(name__in=my_item_values)  # This is a QuerySet

The custom template tag would look like this:

@register.simple_tag()
def my_items(items):
    return ','.join([item.name for item in items])


问:
App rejected - iPhone Apps must also run on iPad without modification, at iPhone resolution, and at 2X iPhone 3GS resolution
just got my app rejected.
Issue :

```<code>iPhone Apps must also run on iPad without modification, at iPhone resolution, and at 2X iPhone 3GS resolution
</code>```

But i have set the Devices option in XCODE to be only on Iphone, does apple require me to run them on ipad as well?

Plus- i dont know if it's connected - they added this section :

```<code>PLA 3.3.12

We found that your app uses the iOS Advertising Identifier but does not include ad functionality. This does not comply with the terms of the iOS Developer Program License Agreement, as required by the App Store Review Guidelines.

Specifically, section 3.3.12 of the iOS Developer Program License Agreement states:

"You and Your Applications (and any third party with whom you have contracted to serve advertising) may use the Advertising Identifier, and any information obtained through the use of the Advertising Identifier, only for the purpose of serving advertising. If a user resets the Advertising Identifier, then You agree not to combine, correlate, link or otherwise associate, either directly or indirectly, the prior Advertising Identifier and any derived information with the reset Advertising Identifier."

Note: iAd does not use the AdSupport framework, ASIdentifierManager, or the Advertising Identifier. Therefore they are not required for iAd implementations and should not be included in your app for iAd support.
</code>```

2) Does the ads rejected me as well?  or they just added this with no connection to the rejection?

答:
Apple requires that apps run on all iOS platforms.  Accordingly I had to add constraints to my storyboard to adjust the location of subviews on each screen.  Because adding each constraint is tedious, I used Cirrious Fluent Layout which worked very well for me.  Below is the code I used on my screen that included a imageview.  This was the most complicated screen to "fix" because (apparently) the imagevies somehow changed all the screen sizes, being an iOS developer novice, I had no idea why this worked, only that it did.

First I needed to add the reference:

```<code>using Cirrious.FluentLayouts.Touch;
</code>```

Code:

```<code>//This line is required to turn off all autosizing/positioning
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

// Get the screen dimensions and the middle of the screen
// for button positioning

var barheight = this.NavigationController.NavigationBar.Bounds.Height;
// Height of the navigation bar

var height = UIScreen.MainScreen.Bounds.Height;
var width = UIScreen.MainScreen.Bounds.Width;
int middle = (int) UIScreen.MainScreen.Bounds.Width / 2;
// We cast to int to truncate float,
// int will convert implictly to float when used (Visual Studio).

var heightavailabletoimageviw = height -74 - 47 - 26 - 60;
// 74 is the height of the banner, 47 is the height of the buttons and
// 26 is the height of the title label plus a 5px gap  The rest of the
// screen is available for use by the image view,
// set heightavailabletoimageviw to this value
// Had to subtract 60 because the image view still overlapped
// the buttons, no idea why.  Anyone?

// Had to add a constraint to the imageview because if I didn't
// it automatically scaled to the size of the image, not good.
ThePhoto.AddConstraints(
    ThePhoto.Width().EqualTo(UIScreen.MainScreen.Bounds.Width),
    ThePhoto.Height().EqualTo(heightavailabletoimageviw)
);

// Had to fix the size of the imagebutton otherwise the button size
// scaled to the size of the image
btnPhoto.AddConstraints(
    btnPhoto.Width().EqualTo(62f),
    btnPhoto.Height().EqualTo(47f)
);

// Now we add the constraints to the viewcontroller to finish up.
View.AddConstraints(

    // Can't cover the navigation bar (unless it isn't there, mine is),
    // this value sets all other relative positions
    Banner.AtTopOf(View, barheight),
    Banner.AtRightOf(View, 0),
    Banner.AtLeftOf(View, 0),

    lblTitle.Below(Banner, 0),
    lblTitle.WithSameWidth(Banner),

    ThePhoto.Below(lblTitle, 5),
    ThePhoto.WithSameWidth(lblTitle),

    // I have no idea why, but I had to use negative
    // values for the buttons to appear on the screen,
    // otherwise they were off screen.
    // If anyone could explain this, I would appreciate it.
    btnUpload.AtBottomOf(View),
    btnUpload.ToLeftOf(View,-60),

    // Same here, had to use negative values for button to
    // position correctly on the screen
    btnPhoto.AtBottomOf(View),
    btnPhoto.ToLeftOf(View,-(middle + 31)),

   // Again, same thing.
   btnMainMenu.AtBottomOf(View),
   btnMainMenu.ToRightOf(View,-80)

);
</code>```

This is how I solved my problem, I re-submitted the app and it now appears on the app store at: https://itunes.apple.com/us/app/oml-photo-manager/id1212622377?mt=8.

Hope this helps someone ....

R/
Prescott ...

Body:
just got my app rejected.
Issue :

iPhone Apps must also run on iPad without modification, at iPhone resolution, and at 2X iPhone 3GS resolution

But i have set the Devices option in XCODE to be only on Iphone, does apple require me to run them on ipad as well?

Plus- i dont know if it's connected - they added this section :

PLA 3.3.12

We found that your app uses the iOS Advertising Identifier but does not include ad functionality. This does not comply with the terms of the iOS Developer Program License Agreement, as required by the App Store Review Guidelines.

Specifically, section 3.3.12 of the iOS Developer Program License Agreement states:

"You and Your Applications (and any third party with whom you have contracted to serve advertising) may use the Advertising Identifier, and any information obtained through the use of the Advertising Identifier, only for the purpose of serving advertising. If a user resets the Advertising Identifier, then You agree not to combine, correlate, link or otherwise associate, either directly or indirectly, the prior Advertising Identifier and any derived information with the reset Advertising Identifier."

Note: iAd does not use the AdSupport framework, ASIdentifierManager, or the Advertising Identifier. Therefore they are not required for iAd implementations and should not be included in your app for iAd support.

2) Does the ads rejected me as well?  or they just added this with no connection to the rejection?

Body:
Apple requires that apps run on all iOS platforms.  Accordingly I had to add constraints to my storyboard to adjust the location of subviews on each screen.  Because adding each constraint is tedious, I used Cirrious Fluent Layout which worked very well for me.  Below is the code I used on my screen that included a imageview.  This was the most complicated screen to "fix" because (apparently) the imagevies somehow changed all the screen sizes, being an iOS developer novice, I had no idea why this worked, only that it did.

First I needed to add the reference:

using Cirrious.FluentLayouts.Touch;

Code:

//This line is required to turn off all autosizing/positioning
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

// Get the screen dimensions and the middle of the screen
// for button positioning

var barheight = this.NavigationController.NavigationBar.Bounds.Height;
// Height of the navigation bar

var height = UIScreen.MainScreen.Bounds.Height;
var width = UIScreen.MainScreen.Bounds.Width;
int middle = (int) UIScreen.MainScreen.Bounds.Width / 2;
// We cast to int to truncate float,
// int will convert implictly to float when used (Visual Studio).

var heightavailabletoimageviw = height -74 - 47 - 26 - 60;
// 74 is the height of the banner, 47 is the height of the buttons and
// 26 is the height of the title label plus a 5px gap  The rest of the
// screen is available for use by the image view,
// set heightavailabletoimageviw to this value
// Had to subtract 60 because the image view still overlapped
// the buttons, no idea why.  Anyone?

// Had to add a constraint to the imageview because if I didn't
// it automatically scaled to the size of the image, not good.
ThePhoto.AddConstraints(
    ThePhoto.Width().EqualTo(UIScreen.MainScreen.Bounds.Width),
    ThePhoto.Height().EqualTo(heightavailabletoimageviw)
);

// Had to fix the size of the imagebutton otherwise the button size
// scaled to the size of the image
btnPhoto.AddConstraints(
    btnPhoto.Width().EqualTo(62f),
    btnPhoto.Height().EqualTo(47f)
);

// Now we add the constraints to the viewcontroller to finish up.
View.AddConstraints(

    // Can't cover the navigation bar (unless it isn't there, mine is),
    // this value sets all other relative positions
    Banner.AtTopOf(View, barheight),
    Banner.AtRightOf(View, 0),
    Banner.AtLeftOf(View, 0),

    lblTitle.Below(Banner, 0),
    lblTitle.WithSameWidth(Banner),

    ThePhoto.Below(lblTitle, 5),
    ThePhoto.WithSameWidth(lblTitle),

    // I have no idea why, but I had to use negative
    // values for the buttons to appear on the screen,
    // otherwise they were off screen.
    // If anyone could explain this, I would appreciate it.
    btnUpload.AtBottomOf(View),
    btnUpload.ToLeftOf(View,-60),

    // Same here, had to use negative values for button to
    // position correctly on the screen
    btnPhoto.AtBottomOf(View),
    btnPhoto.ToLeftOf(View,-(middle + 31)),

   // Again, same thing.
   btnMainMenu.AtBottomOf(View),
   btnMainMenu.ToRightOf(View,-80)

);

This is how I solved my problem, I re-submitted the app and it now appears on the app store at: https://itunes.apple.com/us/app/oml-photo-manager/id1212622377?mt=8.

Hope this helps someone ....

R/
Prescott ...


问:
get variable located inside callback function
```<code>var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}
</code>```

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

答:
declaring a variable on a higher scope will make it accessible. The value in the higher scope will not be updated until the callback is called.</p>

```<code>var result = {};
function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        result.info = JSON.parse(body);
        console.log(result.info.stargazers_count + " Stars");
        console.log(result.info.forks_count + " Forks");
    }
}
</code>```

Body:
var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

Body:
declaring a variable on a higher scope will make it accessible. The value in the higher scope will not be updated until the callback is called.

var result = {};
function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        result.info = JSON.parse(body);
        console.log(result.info.stargazers_count + " Stars");
        console.log(result.info.forks_count + " Forks");
    }
}


问:
Python split by character only if wrapped in parenthesis
I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wrapped in parenthesis.

Question: How can I split by equals sign only when the equals sign is not in between two parenthesis?

Example data:

```<code>PowSup=PS1(type=Emerson,fw=v.03.05.00)
</code>```

Desired output:

```<code>{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}
</code>```

UPDATE: The data does not seem to have any nested parenthesis. (Hopefully that remains true in the future)

UPDATE 2: The key doesn't ever seem to have equals sign either.

UPDATE 3: The full requirements are much more complicated and at this point I am stuck so I have opened up a new question here: Python parse output of mixed format text file to key value pair dictionaries

答:
Simple solution using str.index() function:

```<code>s = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
pos = s.index('=')   # detecting the first position of `=` character
print {s[:pos]:s[pos+1:]}
</code>```

The output:

```<code>{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}
</code>```

Body:
I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wrapped in parenthesis.

Question: How can I split by equals sign only when the equals sign is not in between two parenthesis?

Example data:

PowSup=PS1(type=Emerson,fw=v.03.05.00)

Desired output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

UPDATE: The data does not seem to have any nested parenthesis. (Hopefully that remains true in the future)

UPDATE 2: The key doesn't ever seem to have equals sign either.

UPDATE 3: The full requirements are much more complicated and at this point I am stuck so I have opened up a new question here: Python parse output of mixed format text file to key value pair dictionaries

Body:
Simple solution using str.index() function:

s = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
pos = s.index('=')   # detecting the first position of `=` character
print {s[:pos]:s[pos+1:]}

The output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}


问:
Thread-safe implementation of the Copy-on-write (COW) idiom?
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

```<code>class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};
</code>```

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

```<code>class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};
</code>```

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?

答: RcMap's reference counts need to be made atomic in order to be thread safe. In G++ 4.1, you an use the atomic builtins to implement this.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?

In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but the copies rarely modify the contained map. I found that COW gives me a 22% performance boost, compared to copying the whole map contents in the Foo copy constructor, but my COW implementation crashes when multiple threads are used.

UPDATE:

Okay, here is the code, reduced to a minimal example, since you asked for it:

First, a reference-counting map:

class RcMap {
 public:
  typedef std::map<int,double> Container;
  typedef Container::const_iterator const_iterator;
  typedef Container::iterator iterator;

  RcMap() : count_(1) {}

  RcMap(const RcMap& other) : count_(1) {
    m_ = other.Get();
  }

  unsigned Count() const { return count_; }
  unsigned IncCount() { return ++count_; }
  unsigned DecCount() {
    if(count_ > 0) --count_;
    return count_;
  }
  void insert(int i, double d) {
    m_.insert(std::make_pair(i,d));
  }
  iterator begin() { return m_.begin(); }
  iterator end() { return m_.end(); }
  const_iterator begin() const { return m_.begin(); }
  const_iterator end() const { return m_.end(); }

 protected:
  const Container& Get() const { return m_; }

 private:
  void operator=(const RcMap&); // disallow

  Container m_;
  unsigned count_;
};

And here is the class Foo that contains such a map RcMap, using a Copy-on-write mechanism:

class Foo {
 public:
  Foo() : m_(NULL) {}

  Foo(const Foo& other) : m_(other.m_) {
    if (m_) m_->IncCount();
  }

  Foo& operator= (const Foo& other) {
    RcMap* const old = m_;
    m_ = other.m_;
    if(m_ != 0)
      m_->IncCount();
    if (old != 0 && old->DecCount() == 0) {
      delete old;
    }
    return *this;
  }

  virtual ~Foo() {
    if(m_ != 0 && m_->DecCount() == 0){
      delete m_;
      m_ = 0;
    }
  }

  const RcMap& GetMap() const {
    if(m_ == 0)
      return EmptyStaticRcMap();
    return *m_;
  }

  RcMap& GetMap() {
    if(m_ == 0)
      m_ = new RcMap();
    if (m_->Count() > 1) {
      RcMap* d = new RcMap(*m_);
      m_->DecCount();
      m_ = d;
    }
    assert(m_->Count() == 1);
    return *m_;
  }

  static const RcMap& EmptyStaticRcMap(){
    static const RcMap empty;
    return empty;
  }

 private:
  RcMap* m_;
};

I haven't yet been able to reproduce the crash using this minimal example, but in my original code it happens when I use the copy constructor or assignment operator of Foo objects in parallel. But maybe someone can spot the thread-safety bug?


答:
You can limit the split() operation to a single split (the first =):

```<code>>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> x.split('=', 1)
['PowSup', 'PS1(type=Emerson,fw=v.03.05.00)']
</code>```

You can then use these values to populate your dict:

```<code>>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> key, value = x.split('=', 1)
>>> out = {}
>>> out[key] = value
>>> out
{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}
</code>```

Title: Python split by character only if wrapped in parenthesis

Body:
You can limit the split() operation to a single split (the first =):

>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> x.split('=', 1)
['PowSup', 'PS1(type=Emerson,fw=v.03.05.00)']

You can then use these values to populate your dict:

>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> key, value = x.split('=', 1)
>>> out = {}
>>> out[key] = value
>>> out
{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}


问:
How to play audio without extension
I use SoundIt to stream data on my network.
Soundit exports the sound local using localhost:port
I then use ngrok to make a tunnel to my localhosts port and i get an address
http://xxx.ngrok.io

Is there a way to add to my site only the audio from ngrok's url?

I tried iframe ,object data , embed src
But all these loads the page and makes clients browser using 50% of cpu.
Is it possible to play only the audio from the url?
Thank you

答:
You can use the audio tag

```<code><audio controls>

  <source src="horse.mp3" type="audio/mpeg">

</audio>
</code>```

Then you can use Javascript to start playing and pausing etc.

Title: How to play audio without extension

Body:
You can use the audio tag

<audio controls>

  <source src="horse.mp3" type="audio/mpeg">

</audio>

Then you can use Javascript to start playing and pausing etc.


问:
C macro and makefile and expressions not work as expected
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

```<code>KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"
</code>```

Samples:

3.0.101-0.47.71-default looks like:

```<code>KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"
</code>```

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

```<code>KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="
</code>```

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

```<code>#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)
</code>```

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

```<code>error: operator '==' has no left operand
</code>```

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

答:
If you read: https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_4.html, you will find:

The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro. Its syntax is

#if expression ...

expression is a C expression of integer type, subject to stringent restrictions. It may contain:

...

Macros. All macros in the expression are expanded before actual computation of the expression's value begins.

Identifiers that are not macros, which are all considered to be the number zero. ...

So if you had:

```<code>#if defined(FOO) && FOO == 1
</code>```

And then didn't define foo, it would resolve the expression to:

```<code>0 && 0 == 1
</code>```

which would then resolve to #if 0, which is valid.   However, if you defined FOO to be blank, then it would resolve to:

```<code>1 && == 1
</code>```

The precompiler would then try to parse the expression, and get a syntax error, and fail.   Despite several comments that seem to be out on the web, the precompiler does not short-circuit the parsing of the expression, just the evaluation of the expression.

If you wanted to get around this, you can use some macro trickery as follows:

```<code>#define COMBINE1(W,Y,Z) W##Y##Z
#define COMBINE(W,Y,Z) COMBINE1(W,Y,Z)
#define ISEMPTY(val)  COMBINE(val,4,val) == 4

#if defined FOO
#if ISEMPTY(FOO)
#pragma message "FOO DEFINED AS EMPTY"
#else
#pragma message "FOO DEFINED (NOT EMPTY)"
#endif
#else
#pragma message "FOO NOT DEFINED"
#endif
</code>```

which gives:

```<code>~/sandbox/tst6> gcc tst2.c
tst2.c:12: note: #pragma message: FOO NOT DEFINED
~/sandbox/tst6> gcc tst2.c -DFOO=
tst2.c:7: note: #pragma message: FOO DEFINED AS EMPTY
~/sandbox/tst6> gcc tst2.c -DFOO=1
tst2.c:9: note: #pragma message: FOO DEFINED (NOT EMPTY)
</code>```

Body:
In my C code, I need to check my kernel version and act according to it.
In the makefile I have the following:

KERNEL_MAJOR :=$(word 1, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MINOR :=$(word 2, $(subst ., ,$(KERNEL_HEADERS)))
KERNEL_MICRO :=$(word 1, $(subst -, ,$(word 3, $(subst ., ,$(KERNEL_HEADERS)))))
KERNEL_PATCH_LEVEL :=$(word 1, $(subst ., ,$(word 2, $(subst -, ,$(KERNEL_HEADERS)))))
KARGS := KCPPFLAGS="-DKERNEL_MAJOR=$(KERNEL_MAJOR) -DKERNEL_MINOR=$(KERNEL_MINOR) -DKERNEL_MICRO=$(KERNEL_MICRO) -DKERNEL_PATCH_LEVEL=$(KERNEL_PATCH_LEVEL)"

Samples:

3.0.101-0.47.71-default looks like:

KCPPFLAGS="-DKERNEL_MAJOR=3 -DKERNEL_MINOR=0 -DKERNEL_MICRO=101 -DKERNEL_PATCH_LEVEL=0"

4.1.21.x86_64.1 (notice KERNEL_PATCH_LEVEL):

KCPPFLAGS="-DKERNEL_MAJOR=4 -DKERNEL_MINOR=1 -DKERNEL_MICRO=21 -DKERNEL_PATCH_LEVEL="

I have macro in my code to check if kernel is 3.0.101.0 or 3.0.76.0:

#if defined(KERNEL_MAJOR) && defined(KERNEL_MINOR) && defined(KERNEL_MICRO) && defined(KERNEL_PATCH_LEVEL) && \
    (KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,101) || KERNEL_VERSION(KERNEL_MAJOR,KERNEL_MINOR,KERNEL_MICRO) == KERNEL_VERSION(3,0,76)) \
    && (KERNEL_PATCH_LEVEL == 0)

There are 3 && boolean expressions, if expression #1 is ok, then i want to continue to expression #2, if expression #2 continue, i will continue to expression #3.
When i try to compile (make..) on kernel version 4.1.21.x86_64.1 i receive:

error: operator '==' has no left operand

This is because -DKERNEL_PATCH_LEVEL="  - see the output.

I would expect the make to prevent me from getting to that && condition since expression #2 has failed (3.0.101 or 3.0.76)

Body:
If you read: https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_4.html, you will find:

The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro. Its syntax is

#if expression ...

expression is a C expression of integer type, subject to stringent restrictions. It may contain:

...

Macros. All macros in the expression are expanded before actual computation of the expression's value begins.

Identifiers that are not macros, which are all considered to be the number zero. ...

So if you had:

#if defined(FOO) && FOO == 1

And then didn't define foo, it would resolve the expression to:

0 && 0 == 1

which would then resolve to #if 0, which is valid.   However, if you defined FOO to be blank, then it would resolve to:

1 && == 1

The precompiler would then try to parse the expression, and get a syntax error, and fail.   Despite several comments that seem to be out on the web, the precompiler does not short-circuit the parsing of the expression, just the evaluation of the expression.

If you wanted to get around this, you can use some macro trickery as follows:

#define COMBINE1(W,Y,Z) W##Y##Z
#define COMBINE(W,Y,Z) COMBINE1(W,Y,Z)
#define ISEMPTY(val)  COMBINE(val,4,val) == 4

#if defined FOO
#if ISEMPTY(FOO)
#pragma message "FOO DEFINED AS EMPTY"
#else
#pragma message "FOO DEFINED (NOT EMPTY)"
#endif
#else
#pragma message "FOO NOT DEFINED"
#endif

which gives:

~/sandbox/tst6> gcc tst2.c
tst2.c:12: note: #pragma message: FOO NOT DEFINED
~/sandbox/tst6> gcc tst2.c -DFOO=
tst2.c:7: note: #pragma message: FOO DEFINED AS EMPTY
~/sandbox/tst6> gcc tst2.c -DFOO=1
tst2.c:9: note: #pragma message: FOO DEFINED (NOT EMPTY)


问:
Difference between "//" and "/" in XPath?
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

```<code>//webengagedata//preceding-sibling::*
</code>```

returned 14 results

And this expression

```<code>//webengagedata/preceding-sibling::*
</code>```

returned 9 results

What does the "//" do to match 5 more results?

答:
/ vs // in general

Both child (/) and descendant-or-self (//) are axes in XPath.

/ is short for /child::node()/.

Use / to select a node's immediate children.

// is short for /descendant-or-self::node()/.

Use // to select
a node, its children, its grandchildren, and so on
recursively.

/ vs // with preceding-sibling::*

Your specific question asks about the difference between //preceding-sibling::* and /preceding-sibling::*.

Since your data is offsite and complex, let's consider instead this present and simpler XML:

```<code><r>
  <a/>
  <b>
    <c/>
    <d/>
  </b>
</r>
</code>```

For this XML,

/r/preceding-sibling::* selects nothing because r has no
preceding siblings.

/r//preceding-sibling::* selects the preceding siblings elements of
all of the descendant or self nodes of r. That is, a, b, c and d.
(Remember, /r//preceding-sibling::* is short for /descendant-or-self::node()/preceding-sibling::*, not /descendant-or-self::*/preceding-sibling::*)  Note that even though b and d are predecessor siblings to no elements, they are predecessor siblings to text nodes because the above XML has whitespace after b and d.  If all whitespace were removed, then only a and c would be selected.

/r/descendant::*/preceding-sibling::* selects the preceding sibling elements of all descendant elements of r.  That is, a and c.  Note that b and d are not selected because they are not preceding sibling elements to any descendant elements of r -- unlike the previous example, text nodes do not qualify.

Body:
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

//webengagedata//preceding-sibling::*

returned 14 results

And this expression

//webengagedata/preceding-sibling::*

returned 9 results

What does the "//" do to match 5 more results?

Body:
/ vs // in general

Both child (/) and descendant-or-self (//) are axes in XPath.

/ is short for /child::node()/.

Use / to select a node's immediate children.

// is short for /descendant-or-self::node()/.

Use // to select
a node, its children, its grandchildren, and so on
recursively.

/ vs // with preceding-sibling::*

Your specific question asks about the difference between //preceding-sibling::* and /preceding-sibling::*.

Since your data is offsite and complex, let's consider instead this present and simpler XML:

<r>
  <a/>
  <b>
    <c/>
    <d/>
  </b>
</r>

For this XML,

/r/preceding-sibling::* selects nothing because r has no
preceding siblings.

/r//preceding-sibling::* selects the preceding siblings elements of
all of the descendant or self nodes of r. That is, a, b, c and d.
(Remember, /r//preceding-sibling::* is short for /descendant-or-self::node()/preceding-sibling::*, not /descendant-or-self::*/preceding-sibling::*)  Note that even though b and d are predecessor siblings to no elements, they are predecessor siblings to text nodes because the above XML has whitespace after b and d.  If all whitespace were removed, then only a and c would be selected.

/r/descendant::*/preceding-sibling::* selects the preceding sibling elements of all descendant elements of r.  That is, a and c.  Note that b and d are not selected because they are not preceding sibling elements to any descendant elements of r -- unlike the previous example, text nodes do not qualify.