问:
Dynamic style sheet Or condition based page layout in XSLT 1.0
I am creating PDF document using xslt 1.0, where I have to apply some static content ("DAFT") on page based on data, like if COMPLETED = 0 then print "DRAFT"
on page otherwise not.

XML data which i used to generate PDF is like below, data will contains different customer and for every customer i am creating new page( using page break) in PDF, some time data will go to next page also..

I have tried to implement static content while i am creating new page/ applying page break, but problem is when data goes (overflow) to next page then this static content is not on next page, so I think this should be done by stylesheet some how which i don,t know.

XML DATA:

```<code><ROWSET1>
  <ROWSET1_ROW>
  <ID_INVOICE>9404</ID_INVOICE>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <COM_LASTNAME>XYZ Lmt</COM_LASTNAME>
  <SALUTATION>Company</SALUTATION>
  <RG_CONTACTTYPE>OU</RG_CONTACTTYPE>
  <NAME1>XYZ Lmt</NAME1>
  <NAME2>COM EMP</NAME2>
  <COMPLETED>0</COMPLETED>
  <DATE_INVOICE>31.05.2017</DATE_INVOICE>
  <INVOICE_YEAR>2017</INVOICE_YEAR>
  <INVOICENR>487</INVOICENR>
  <APPLICATION_NR>7.384.883</APPLICATION_NR>
  <NAME_CUST>EMP1</NAME_CUST>
  <SENT_DATE>15.05.2017</SENT_DATE>
  <ID_PRODUCT>3</ID_PRODUCT>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <INVOICENR_ORDER>4053</INVOICENR_ORDER>
  <SUM_PRODUCT>168</SUM_PRODUCT>
  <IS_INDEP_CONTACT>N</IS_INDEP_CONTACT>
 </ROWSET1_ROW>
 <ROWSET1_ROW>
  <ID_INVOICE>9404</ID_INVOICE>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <COM_LASTNAME>XYZ Lmt</COM_LASTNAME>
  <SALUTATION>Company</SALUTATION>
  <RG_CONTACTTYPE>OU</RG_CONTACTTYPE>
  <NAME1>XYZ Lmt</NAME1>
  <NAME2>COM EMP</NAME2>
  <COMPLETED>0</COMPLETED>
  <DATE_INVOICE>31.05.2017</DATE_INVOICE>
  <INVOICE_YEAR>2017</INVOICE_YEAR>
  <INVOICENR>487</INVOICENR>
  <APPLICATION_NR>7.384.883</APPLICATION_NR>
  <NAME_CUST>EMP2</NAME_CUST>
  <SENT_DATE>15.05.2017</SENT_DATE>
  <ID_PRODUCT>3</ID_PRODUCT>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <INVOICENR_ORDER>4053</INVOICENR_ORDER>
  <SUM_PRODUCT>168</SUM_PRODUCT>
  <IS_INDEP_CONTACT>N</IS_INDEP_CONTACT>
 </ROWSET1_ROW>
 <ROWSET1_ROW>
 ...
</ROWSET1>
<ROWSET2>
 <ROWSET2_ROW>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>290</QUANTITY>
  <APPLICATION_NR>1</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>168</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>-12</QUANTITY>
  <APPLICATION_NR>4</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>168</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>859</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>39</QUANTITY>
  <APPLICATION_NR>1</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>169</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>859</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>-2</QUANTITY>
  <APPLICATION_NR>4</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>169</PRICE>
 </ROWSET2_ROW>
 ...
</ROWSET2>
</code>```

STYLE SHEET (stylesheet.xsl):

```<code><xsl:template name="paperlayout">
        <xsl:param name="draft" select="false()"/>
        <xsl:param name="printheader"/>
        <fo:root>

            <fo:layout-master-set>
                <fo:page-sequence-master master-name="paperlayout">
                    <fo:single-page-master-reference master-reference="title" page-position="first"/>
                    <fo:single-page-master-reference master-reference="rest" page-position="rest"/>
                </fo:page-sequence-master>

                <!-- title page-->
                <fo:simple-page-master master-name="title" page-height="297mm" page-width="210mm" margin-top="20mm"
                margin-bottom="0mm" margin-left="20mm" margin-right="15mm">
                    <fo:region-body region-name="body" margin-bottom="30mm" margin-top="25mm"/>
                    <fo:region-before region-name="header-first" extent="0mm"/>
                    <fo:region-after region-name="footer" extent="20.5mm"/>
                </fo:simple-page-master>

                <!-- rest page-->
                <fo:simple-page-master master-name="rest" page-height="297mm" page-width="210mm" margin-top="20mm"
                margin-bottom="0mm" margin-left="20mm" margin-right="15mm">
                    <fo:region-body region-name="body" margin-bottom="30mm" margin-top="25mm"/>
                    <fo:region-before region-name="header-rest" extent="0mm"/>
                    <fo:region-after region-name="footer" extent="20.5mm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>

            <fo:page-sequence master-reference="paperlayout">
                <!--############## header ##############-->
                <fo:static-content flow-name="header-first">
                    <xsl:if test="$draft">
                        <fo:block-container  position="absolute" left="0mm" top="05mm">
                            <fo:block>
                                <fo:instream-foreign-object>
                                    <svg width="680" height="920" xmlns="http://www.w3.org/2000/svg">
                                        <text font-family="eurostyle" font-size="10pt" font-weight="900" style="fill:rgb(255,192,192)" x="260" y="20" width="680" text-anchor="middle" transform="rotate(-54, 340, 15)">
                                            DRAFT
                                        </text>
                                    </svg>
                                </fo:instream-foreign-object>
                            </fo:block>
                        </fo:block-container>
                    </xsl:if>

                    <xsl:choose>
                        <xsl:when test="$printheader">
                            <xsl:call-template name="logo"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <fo:block-container>
                                <fo:block><fo:leader /></fo:block>
                            </fo:block-container>
                        </xsl:otherwise>
                    </xsl:choose>

                </fo:static-content>

                <fo:static-content flow-name="header-rest">
                    <xsl:if test="$draft">
                        <fo:block-container  position="absolute" left="0mm" top="05mm">
                            <fo:block>
                                <fo:instream-foreign-object>
                                    <svg width="680" height="920" xmlns="http://www.w3.org/2000/svg">
                                        <text font-family="eurostyle" font-size="10pt" font-weight="900" style="fill:rgb(255,192,192)" x="260" y="20" width="680" text-anchor="middle" transform="rotate(-54, 340, 15)">
                                            Entwurf
                                        </text>
                                    </svg>
                                </fo:instream-foreign-object>
                            </fo:block>
                        </fo:block-container>
                    </xsl:if>

                    <xsl:choose>
                        <xsl:when test="$printheader">
                            <xsl:call-template name="logo"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <fo:block-container>
                                <fo:block><fo:leader /></fo:block>
                            </fo:block-container>
                        </xsl:otherwise>
                    </xsl:choose>

                </fo:static-content>

                <!--############## footer ##############-->
                <xsl:if test="$printheader">
                    <xsl:call-template name="footerData"/>
                </xsl:if>

                <!--############## body ##############-->
                <fo:flow flow-name="body" xsl:use-attribute-sets="body">
                    <xsl:call-template name="body"/>
                    <fo:block id="endofdoc"></fo:block>
                </fo:flow>

            </fo:page-sequence>
        </fo:root>
    </xsl:template>
</code>```

XSLT CODE used to create PDF:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:math="http://exslt.org/math"
    xmlns:exslt="http://exslt.org/common"
    xmlns:str="http://exslt.org/strings"
    exclude-result-prefixes="exslt math str">

    <xsl:import href="stylesheet.xsl"/>

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:variable name="debug" select="false()"/>

    <xsl:variable name="dataRowset1" select="DOCUMENT/DATA/ROWSET1/ROWSET1_ROW"/>
    <xsl:param name="printheader" select="true()"/>

    <xsl:key name="key_cust_id" match="ROWSET1_ROW" use="ID_CUSTOMER"/>

    <!-- ###### Main template ###### -->
    <xsl:template match="/">
        <xsl:call-template name="paperlayout">
            <xsl:with-param name="draft" select="//ROWSET1/ROWSET1_ROW/COMPLETED =  0"/>
            <xsl:with-param name="printheader" select="$printheader"/>
        </xsl:call-template>
    </xsl:template>

    <xsl:variable name="newline">
        <xsl:text>
        </xsl:text>
    </xsl:variable>

    <!--############## body ##############-->
    <xsl:template name="body">
        <xsl:apply-templates select="DOCUMENT/DATA" />
    </xsl:template>

    <xsl:template match="DATA">

        <xsl:variable name="dataRowset2" select="ROWSET2" />
        <!-- Status M check -->
        <xsl:if test="ROWSET1 != ''">

            <fo:block-container xsl:use-attribute-sets="section">

                <xsl:variable name="dataRowset1" select="ROWSET1" />

                <xsl:for-each select="//ROWSET1_ROW[generate-id(.)=generate-id(key('key_cust_id', ID_CUSTOMER)[1])]">
                    <xsl:sort select="COM_LASTNAME" />

                    <fo:block page-break-before="always"></fo:block>
                    <fo:table width="100%" font-family="calibri" font-size="10pt">
                        <xsl:call-template name="table-column-define" />
                        <fo:table-body>

                            <xsl:for-each select="key('key_cust_id', ID_CUSTOMER)">

                                <xsl:if test="position() = 1">
                                    <!-- print header of document like company name, date, invocie nr-->
                                    <xsl:call-template name="table-header" />
                                </xsl:if>
                                    <xsl:call-template name="table-data"/>
                            </xsl:for-each>

                        </fo:table-body>
                    </fo:table>
                            <!-- START: when record end print TOTAL -->
                            <xsl:variable name="customer_id" select="ID_CUSTOMER"/>
                            <fo:table width="100%" font-family="calibri" font-size="10pt">
                                <xsl:call-template name="sub-table-column-define" />
                                <fo:table-body>

                                    <fo:table-row xsl:use-attribute-sets="table-row">
                                        <fo:table-cell>
                                            <xsl:attribute name="number-columns-spanned">
                                                <xsl:value-of select="5"/>
                                            </xsl:attribute>
                                        <fo:block><xsl:value-of select="$newline"/></fo:block>
                                        </fo:table-cell>
                                    </fo:table-row>

                                    <xsl:for-each
                                        select="$dataRowset2/ROWSET2_ROW[ID_CUSTOMER/text() = $customer_id]">
                                        <xsl:call-template name="sub-table-data" />
                                    </xsl:for-each>
                                </fo:table-body>
                            </fo:table>
                            <!-- END: when record end print TOTAL -->
                </xsl:for-each>

            </fo:block-container>
        </xsl:if>

    </xsl:template>

</xsl:stylesheet>
</code>```

In above code I am creating key on id_customer, whenever new customer found I am creating header of page then print data belong to this customer in table which come in ROWSET1 then at then end i am printing total which come in ROWSET2.

At then begging of this code, I am passing parameter in style sheet which print "DRAFT" on whole PDF or NOT PRINT AT all, but i want to print draft on every page for particular company which have "COMPLETED = 0" and not printing DRAFT for those company which is not satisfy this condition.

答:
You should take a look at <fo:marker> and <fo:retrieve-marker>. That should do the job. Markers will never be displayed, regardless of if they have content or not. Thats because the retrieve marker searches for a marker on your specified position and displays its content in itself. So if you put nothing into your marker, the retrieve marker will display nothing. If there is content, the retrieve marker will display the content.
The marker has to be in a flow. The retrieve marker has to be in a static-content. That way the retrieve marker will search for the last content of a marker and you can have different static-contents.
Hope that helps you a bit.

Heres the link to some documentation: markers example

Body:
I am creating PDF document using xslt 1.0, where I have to apply some static content ("DAFT") on page based on data, like if COMPLETED = 0 then print "DRAFT"
on page otherwise not.

XML data which i used to generate PDF is like below, data will contains different customer and for every customer i am creating new page( using page break) in PDF, some time data will go to next page also..

I have tried to implement static content while i am creating new page/ applying page break, but problem is when data goes (overflow) to next page then this static content is not on next page, so I think this should be done by stylesheet some how which i don,t know.

XML DATA:

<ROWSET1>
  <ROWSET1_ROW>
  <ID_INVOICE>9404</ID_INVOICE>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <COM_LASTNAME>XYZ Lmt</COM_LASTNAME>
  <SALUTATION>Company</SALUTATION>
  <RG_CONTACTTYPE>OU</RG_CONTACTTYPE>
  <NAME1>XYZ Lmt</NAME1>
  <NAME2>COM EMP</NAME2>
  <COMPLETED>0</COMPLETED>
  <DATE_INVOICE>31.05.2017</DATE_INVOICE>
  <INVOICE_YEAR>2017</INVOICE_YEAR>
  <INVOICENR>487</INVOICENR>
  <APPLICATION_NR>7.384.883</APPLICATION_NR>
  <NAME_CUST>EMP1</NAME_CUST>
  <SENT_DATE>15.05.2017</SENT_DATE>
  <ID_PRODUCT>3</ID_PRODUCT>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <INVOICENR_ORDER>4053</INVOICENR_ORDER>
  <SUM_PRODUCT>168</SUM_PRODUCT>
  <IS_INDEP_CONTACT>N</IS_INDEP_CONTACT>
 </ROWSET1_ROW>
 <ROWSET1_ROW>
  <ID_INVOICE>9404</ID_INVOICE>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <COM_LASTNAME>XYZ Lmt</COM_LASTNAME>
  <SALUTATION>Company</SALUTATION>
  <RG_CONTACTTYPE>OU</RG_CONTACTTYPE>
  <NAME1>XYZ Lmt</NAME1>
  <NAME2>COM EMP</NAME2>
  <COMPLETED>0</COMPLETED>
  <DATE_INVOICE>31.05.2017</DATE_INVOICE>
  <INVOICE_YEAR>2017</INVOICE_YEAR>
  <INVOICENR>487</INVOICENR>
  <APPLICATION_NR>7.384.883</APPLICATION_NR>
  <NAME_CUST>EMP2</NAME_CUST>
  <SENT_DATE>15.05.2017</SENT_DATE>
  <ID_PRODUCT>3</ID_PRODUCT>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <INVOICENR_ORDER>4053</INVOICENR_ORDER>
  <SUM_PRODUCT>168</SUM_PRODUCT>
  <IS_INDEP_CONTACT>N</IS_INDEP_CONTACT>
 </ROWSET1_ROW>
 <ROWSET1_ROW>
 ...
</ROWSET1>
<ROWSET2>
 <ROWSET2_ROW>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>290</QUANTITY>
  <APPLICATION_NR>1</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>168</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>371</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>-12</QUANTITY>
  <APPLICATION_NR>4</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>168</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>859</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>39</QUANTITY>
  <APPLICATION_NR>1</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>169</PRICE>
 </ROWSET2_ROW>
 <ROWSET2_ROW>
  <ID_CUSTOMER>859</ID_CUSTOMER>
  <ID_PRODUCT>3</ID_PRODUCT>
  <QUANTITY>-2</QUANTITY>
  <APPLICATION_NR>4</APPLICATION_NR>
  <PRODUCTNAME>best product</PRODUCTNAME>
  <PRICE>169</PRICE>
 </ROWSET2_ROW>
 ...
</ROWSET2>

STYLE SHEET (stylesheet.xsl):

<xsl:template name="paperlayout">
        <xsl:param name="draft" select="false()"/>
        <xsl:param name="printheader"/>
        <fo:root>

            <fo:layout-master-set>
                <fo:page-sequence-master master-name="paperlayout">
                    <fo:single-page-master-reference master-reference="title" page-position="first"/>
                    <fo:single-page-master-reference master-reference="rest" page-position="rest"/>
                </fo:page-sequence-master>

                <fo:simple-page-master master-name="title" page-height="297mm" page-width="210mm" margin-top="20mm"
                margin-bottom="0mm" margin-left="20mm" margin-right="15mm">
                    <fo:region-body region-name="body" margin-bottom="30mm" margin-top="25mm"/>
                    <fo:region-before region-name="header-first" extent="0mm"/>
                    <fo:region-after region-name="footer" extent="20.5mm"/>
                </fo:simple-page-master>

                <fo:simple-page-master master-name="rest" page-height="297mm" page-width="210mm" margin-top="20mm"
                margin-bottom="0mm" margin-left="20mm" margin-right="15mm">
                    <fo:region-body region-name="body" margin-bottom="30mm" margin-top="25mm"/>
                    <fo:region-before region-name="header-rest" extent="0mm"/>
                    <fo:region-after region-name="footer" extent="20.5mm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>

            <fo:page-sequence master-reference="paperlayout">

                <fo:static-content flow-name="header-first">
                    <xsl:if test="$draft">
                        <fo:block-container  position="absolute" left="0mm" top="05mm">
                            <fo:block>
                                <fo:instream-foreign-object>
                                    <svg width="680" height="920" xmlns="http://www.w3.org/2000/svg">
                                        <text font-family="eurostyle" font-size="10pt" font-weight="900" style="fill:rgb(255,192,192)" x="260" y="20" width="680" text-anchor="middle" transform="rotate(-54, 340, 15)">
                                            DRAFT
                                        </text>
                                    </svg>
                                </fo:instream-foreign-object>
                            </fo:block>
                        </fo:block-container>
                    </xsl:if>

                    <xsl:choose>
                        <xsl:when test="$printheader">
                            <xsl:call-template name="logo"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <fo:block-container>
                                <fo:block><fo:leader /></fo:block>
                            </fo:block-container>
                        </xsl:otherwise>
                    </xsl:choose>

                </fo:static-content>

                <fo:static-content flow-name="header-rest">
                    <xsl:if test="$draft">
                        <fo:block-container  position="absolute" left="0mm" top="05mm">
                            <fo:block>
                                <fo:instream-foreign-object>
                                    <svg width="680" height="920" xmlns="http://www.w3.org/2000/svg">
                                        <text font-family="eurostyle" font-size="10pt" font-weight="900" style="fill:rgb(255,192,192)" x="260" y="20" width="680" text-anchor="middle" transform="rotate(-54, 340, 15)">
                                            Entwurf
                                        </text>
                                    </svg>
                                </fo:instream-foreign-object>
                            </fo:block>
                        </fo:block-container>
                    </xsl:if>

                    <xsl:choose>
                        <xsl:when test="$printheader">
                            <xsl:call-template name="logo"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <fo:block-container>
                                <fo:block><fo:leader /></fo:block>
                            </fo:block-container>
                        </xsl:otherwise>
                    </xsl:choose>

                </fo:static-content>

                <xsl:if test="$printheader">
                    <xsl:call-template name="footerData"/>
                </xsl:if>

                <fo:flow flow-name="body" xsl:use-attribute-sets="body">
                    <xsl:call-template name="body"/>
                    <fo:block id="endofdoc"></fo:block>
                </fo:flow>

            </fo:page-sequence>
        </fo:root>
    </xsl:template>

XSLT CODE used to create PDF:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:math="http://exslt.org/math"
    xmlns:exslt="http://exslt.org/common"
    xmlns:str="http://exslt.org/strings"
    exclude-result-prefixes="exslt math str">

    <xsl:import href="stylesheet.xsl"/>

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:variable name="debug" select="false()"/>

    <xsl:variable name="dataRowset1" select="DOCUMENT/DATA/ROWSET1/ROWSET1_ROW"/>
    <xsl:param name="printheader" select="true()"/>

    <xsl:key name="key_cust_id" match="ROWSET1_ROW" use="ID_CUSTOMER"/>

    <xsl:template match="/">
        <xsl:call-template name="paperlayout">
            <xsl:with-param name="draft" select="//ROWSET1/ROWSET1_ROW/COMPLETED =  0"/>
            <xsl:with-param name="printheader" select="$printheader"/>
        </xsl:call-template>
    </xsl:template>

    <xsl:variable name="newline">
        <xsl:text>
        </xsl:text>
    </xsl:variable>

    <xsl:template name="body">
        <xsl:apply-templates select="DOCUMENT/DATA" />
    </xsl:template>

    <xsl:template match="DATA">

        <xsl:variable name="dataRowset2" select="ROWSET2" />

        <xsl:if test="ROWSET1 != ''">

            <fo:block-container xsl:use-attribute-sets="section">

                <xsl:variable name="dataRowset1" select="ROWSET1" />

                <xsl:for-each select="//ROWSET1_ROW[generate-id(.)=generate-id(key('key_cust_id', ID_CUSTOMER)[1])]">
                    <xsl:sort select="COM_LASTNAME" />

                    <fo:block page-break-before="always"></fo:block>
                    <fo:table width="100%" font-family="calibri" font-size="10pt">
                        <xsl:call-template name="table-column-define" />
                        <fo:table-body>

                            <xsl:for-each select="key('key_cust_id', ID_CUSTOMER)">

                                <xsl:if test="position() = 1">

                                    <xsl:call-template name="table-header" />
                                </xsl:if>
                                    <xsl:call-template name="table-data"/>
                            </xsl:for-each>

                        </fo:table-body>
                    </fo:table>

                            <xsl:variable name="customer_id" select="ID_CUSTOMER"/>
                            <fo:table width="100%" font-family="calibri" font-size="10pt">
                                <xsl:call-template name="sub-table-column-define" />
                                <fo:table-body>

                                    <fo:table-row xsl:use-attribute-sets="table-row">
                                        <fo:table-cell>
                                            <xsl:attribute name="number-columns-spanned">
                                                <xsl:value-of select="5"/>
                                            </xsl:attribute>
                                        <fo:block><xsl:value-of select="$newline"/></fo:block>
                                        </fo:table-cell>
                                    </fo:table-row>

                                    <xsl:for-each
                                        select="$dataRowset2/ROWSET2_ROW[ID_CUSTOMER/text() = $customer_id]">
                                        <xsl:call-template name="sub-table-data" />
                                    </xsl:for-each>
                                </fo:table-body>
                            </fo:table>

                </xsl:for-each>

            </fo:block-container>
        </xsl:if>

    </xsl:template>

</xsl:stylesheet>

In above code I am creating key on id_customer, whenever new customer found I am creating header of page then print data belong to this customer in table which come in ROWSET1 then at then end i am printing total which come in ROWSET2.

At then begging of this code, I am passing parameter in style sheet which print "DRAFT" on whole PDF or NOT PRINT AT all, but i want to print draft on every page for particular company which have "COMPLETED = 0" and not printing DRAFT for those company which is not satisfy this condition.


来源: stackexchange

问:
Vaadin 7 - instant download of dynamically created file
My scenario is: using Vaadin 7.7.10, I have on click generated file, that I want to download once it is generated.

I have generator method, that returns byte[] (could be also easily modified to any OutputStream if needed), then I create StreamResource from it. So I have the resource ready to be downloaded, but now what?

I believe can't use approach with FileDownloader, because there I would have to generate the file every time the page is displayed prior to actual click on extended button (and I don't want to do that, as it is quite expensive operation which will shall only be used on demand).

I was able to achieve the desired effect using Page.getCurrent().open(streamResource, null, false), but .open with Resource argument is deprecated since Vaadin 7, so I don't wanna rely on it...

Is there any workaround or another approach to this?

答:
Vaadin FileDownloader might be still capable to handle this with some customization. However I once created a reporting system with a different approach. The idea is to use component BrowserFrame that takes StreamResource as its constructor param.

File generation is started - for example - by clicking a button. When generation finalizes it results in to a byte[]. From byte[] is created a StreamSource which then is used to create StreamResouce which is then used as contents of BrowserFrame.

Finally this BrowserFrame is added to the ui somewhere which causes browser to react.

In my case there was a need to generate parameterized PDF reports which user could first preview and then download if in need. I had a PDF generator that provided the byte[]. Browser recognized type from file name extension .pdf and opened PDF plugin for preview & download.

You can put any binary stuff to byte[] used to construct BrowserFrame and set appropriate file name extension.

You can also have some Layout in your ui that - for example - has a progress indicator while file is generating in the background and in to which the BrowserFrame component is attached when file is ready.

ContentLicense: CC BY-SA 3.0


问:
Updating version in pom.xml (maven project)
My goal is to change version of a dependance , I modifiy the version in pom.xml  but when I check the effective pom , there are the two versions , in addition.
I clean install maven where it download the new version and when I build it , the new version doesn't appear
I can't unterstand why , help please.</p>

答: Check if the dependency is being injected from other jars. Also try deleting the old version from .m2/repository and then clean install it . </p>


问:
How to get the value of the href attribute?
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

```<code><a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
</code>```

That is, to get the value of the href attribute if the link has a particular text.

答:
This will select the attributes:</p>

```<code>"//a[text()='the right one']/@href"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

a wrong one
the right one
a wrong one

That is, to get the value of the href attribute if the link has a particular text.

Body:
This will select the attributes:

"//a[text()='the right one']/@href"


问:
Javascript arrays with email address and password
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

```<code>var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];
</code>```

Am I supposed to do it differently in Javascript?

答:
Use an array of objects instead:

var users = [
    {
      emailAddress: 'david@email.com',
      password: 'secretCat',
    },
    {
      emailAddress: 'john@email.com',
      password: 'secretCatTwo'
    },

    {
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree'
    },

    {
       emailAddress: 'susan@email.com',
       password: 'secretCatFour'
    },

 ];

 users.forEach((user, index) => {

  console.log("INDEX   :", index);
  console.log("EMAIL   :", user.emailAddress);
  console.log("PASSWORD:", user.password);

 })```

Body:
I work with PHP and I am more familiar with it. I have tried an array in Javascript but keep getting a syntax error and I am not sure why. I have Googled arrays and I do not seem to get the answer.

Here is my array of Users in Javascript:

var users = [
    [
      emailAddress: 'david@email.com',
      password: 'secretCat';
    ],
    [
      emailAddress: 'john@email.com',
      password: 'secretCatTwo';
    ],

    [
      emailAddress: 'chloe@email.com',
      password: 'secretCatThree';
    ],

    [
       emailAddress: 'susan@email.com',
       password: 'secretCatFour';
    ],

];

Am I supposed to do it differently in Javascript?


问:
Reduce runtime in java 8
My program processes a file with about 2500 words.
I want to get the number of lines that contain both words from the file.
I've written the following code for this. This program requires about 3 hours to run!
According to my research, the reason for the high runtime is to use stream. How can I reduce runtime?

```<code>Stream<String> fileLines = Files.lines(ngramPath, Charset.defaultCharset());
    Supplier<Stream<String>> SfileLines = () -> {
        try {
            return Files.lines(ngramPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileLines;
    };
while (reviews1.hasNext())
    {
        String term_i = reviews1.next();
        reviews2= new Scanner(path);
        while(reviews2.hasNext())
            {
                String term_j = reviews2.next();
                if (!term_i.equals(term_j))
                {
                    double pij = (double) SfileLines.get().filter(s -> s.contains(term_i+" ") & s.contains(term_j+" ")).count();
                    term_i_Ass.put(term_j, pij);
                }
            }
            Total.put(term_i, term_i_Ass);
        }
</code>```

UPDATE: The part that has more time to run is the following code:

```<code>double pij = (double) SfileLines.get().filter(s -> s.contains(term_i+" ") & s.contains(term_j+" ")).count();
</code>```

I need to write this line of the program in a different way, which requires less time.

答:
BufferedReader.readLine() is as fast as you need: you can read millions of lines a second with it.

Example of usage:

```<code>BufferedReader br = null;
FileReader fr = null;

try {

        //br = new BufferedReader(new FileReader(FILENAME));
        fr = new FileReader(FILENAME);
        br = new BufferedReader(fr);

        String line;

        while ((line= br.readLine()) != null) {
            System.out.println(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null){
                br.close();
            }
            if (fr != null){
                fr.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
</code>```

If you want to use the Stream, try with:

```<code>    try (Stream<String> stream = Files.lines(Paths.get("path to file"))) {

        stream.forEach(System.out::println);

    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Title: Reduce runtime in java 8

Body:
My program processes a file with about 2500 words.
I want to get the number of lines that contain both words from the file.
I've written the following code for this. This program requires about 3 hours to run!
According to my research, the reason for the high runtime is to use stream. How can I reduce runtime?

Stream<String> fileLines = Files.lines(ngramPath, Charset.defaultCharset());
    Supplier<Stream<String>> SfileLines = () -> {
        try {
            return Files.lines(ngramPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileLines;
    };
while (reviews1.hasNext())
    {
        String term_i = reviews1.next();
        reviews2= new Scanner(path);
        while(reviews2.hasNext())
            {
                String term_j = reviews2.next();
                if (!term_i.equals(term_j))
                {
                    double pij = (double) SfileLines.get().filter(s -> s.contains(term_i+" ") & s.contains(term_j+" ")).count();
                    term_i_Ass.put(term_j, pij);
                }
            }
            Total.put(term_i, term_i_Ass);
        }

UPDATE: The part that has more time to run is the following code:

double pij = (double) SfileLines.get().filter(s -> s.contains(term_i+" ") & s.contains(term_j+" ")).count();

I need to write this line of the program in a different way, which requires less time.

Body:
BufferedReader.readLine() is as fast as you need: you can read millions of lines a second with it.

Example of usage:

BufferedReader br = null;
FileReader fr = null;

try {

        //br = new BufferedReader(new FileReader(FILENAME));
        fr = new FileReader(FILENAME);
        br = new BufferedReader(fr);

        String line;

        while ((line= br.readLine()) != null) {
            System.out.println(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null){
                br.close();
            }
            if (fr != null){
                fr.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

If you want to use the Stream, try with:

    try (Stream<String> stream = Files.lines(Paths.get("path to file"))) {

        stream.forEach(System.out::println);

    } catch (IOException e) {
        e.printStackTrace();
    }


问:
Selenium python types of content loading constraints
I need to parse the news from several sites with javascript and use selenium + PhantomJS for it. But there are videos on these sites, which are useless for me and I don't need them at all. (I was given an advice to use selenium + Chrome or selenium + Firefox, but I don't need any opening windows during parsing).

These videos start playing automatically according to the site's logic, and in the end of the end exception http.client.RemoteDisconnected: Remote end closed connection without response throws.

I think it throws because my internet is very slow and videos can't be full loaded with it.

How can I avoid this problem?

May be any content constraints exist in the selenium or PhantomJS?

Full traceback:

```<code>File "viralnova/viralnova.py", line 101, in parse_viralnova
    _parse_post_link(postlinktest, driver)
  File "viralnova/viralnova.py", line 9, in _parse_post_link
    driver.get(post_link)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 309, in get
    self.execute(Command.GET, {'url': url})
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 295, in execute
    response = self.command_executor.execute(driver_command, params)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 464, in execute
    return self._request(command_info[0], url, body=data)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 526, in _request
    resp = opener.open(request, timeout=self._timeout)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 1346, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 1321, in do_open
    r = h.getresponse()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 1331, in getresponse
    response.begin()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
</code>```

Code is here

```<code>def _parse_post_link(post_link, driver):
    try:
        driver.get(post_link)
    except Exception:
        return None

    post_page_soup = Soup(driver.page_source, "lxml")
    title = post_page_soup.find('div', attrs={'class': 'post-box-detail article'}).h2.text
    print(title)

def parse_viralnova(to_csv=True):
    driver = webdriver.PhantomJS("/Users/user/.phantomjsdriver/phantomjs")
    postlinktest = 'http://www.viralnova.com/restroom-design-fails/'
    _parse_post_link(postlinktest, driver)
</code>```

答:
If it's just parsing the text content that you're after, you might consider using just Python and BeautifulSoup. You shouldn't be triggering anything in the browser this way since you won't use one at all (you mentioned you don't need windows opening) and at the same time the solution will be faster lacking that browser overhead.

If you do need some javascript loaded, you can try using dryscape as well.

Body:
I need to parse the news from several sites with javascript and use selenium + PhantomJS for it. But there are videos on these sites, which are useless for me and I don't need them at all. (I was given an advice to use selenium + Chrome or selenium + Firefox, but I don't need any opening windows during parsing).

These videos start playing automatically according to the site's logic, and in the end of the end exception http.client.RemoteDisconnected: Remote end closed connection without response throws.

I think it throws because my internet is very slow and videos can't be full loaded with it.

How can I avoid this problem?

May be any content constraints exist in the selenium or PhantomJS?

Full traceback:

File "viralnova/viralnova.py", line 101, in parse_viralnova
    _parse_post_link(postlinktest, driver)
  File "viralnova/viralnova.py", line 9, in _parse_post_link
    driver.get(post_link)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 309, in get
    self.execute(Command.GET, {'url': url})
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 295, in execute
    response = self.command_executor.execute(driver_command, params)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 464, in execute
    return self._request(command_info[0], url, body=data)
  File "/Users/user/anaconda/envs/env/lib/python3.6/site-packages/selenium/webdriver/remote/remote_connection.py", line 526, in _request
    resp = opener.open(request, timeout=self._timeout)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 1346, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/Users/user/anaconda/envs/env/lib/python3.6/urllib/request.py", line 1321, in do_open
    r = h.getresponse()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 1331, in getresponse
    response.begin()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "/Users/user/anaconda/envs/env/lib/python3.6/http/client.py", line 266, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

Code is here

def _parse_post_link(post_link, driver):
    try:
        driver.get(post_link)
    except Exception:
        return None

    post_page_soup = Soup(driver.page_source, "lxml")
    title = post_page_soup.find('div', attrs={'class': 'post-box-detail article'}).h2.text
    print(title)

def parse_viralnova(to_csv=True):
    driver = webdriver.PhantomJS("/Users/user/.phantomjsdriver/phantomjs")
    postlinktest = 'http://www.viralnova.com/restroom-design-fails/'
    _parse_post_link(postlinktest, driver)


问:
i want to get some approaches to update the content of ax windows automatically in python
just mean update the content automatically from my plot command
 I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. </p>

答:
This will update a plot

```<code>import matplotlib.pyplot as plt
import numpy as np

data = np.random.random(20) # inital data set
f,ax = plt.subplots() # create the figure and plot
ax.plot(data) # plot initial data

for _ in range(10):
    data = np.random.random(20) # create new data
    ax.cla() # clear subplot's current data
    ax.plot(data) # plot new data

    plt.pause(0.01) # wait a few secs to allow plot to update
    f.canvas.draw() # draw the plot again (in the same window)
</code>```

The important bit here is to clear the current content and then draw again. For some reason to do with the way matplotlib handles plotting there needs to be a pause between the plot command and the draw command (or you have to flush the changes).

Body:
This will update a plot

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random(20) # inital data set
f,ax = plt.subplots() # create the figure and plot
ax.plot(data) # plot initial data

for _ in range(10):
    data = np.random.random(20) # create new data
    ax.cla() # clear subplot's current data
    ax.plot(data) # plot new data

    plt.pause(0.01) # wait a few secs to allow plot to update
    f.canvas.draw() # draw the plot again (in the same window)

The important bit here is to clear the current content and then draw again. For some reason to do with the way matplotlib handles plotting there needs to be a pause between the plot command and the draw command (or you have to flush the changes).


问:
Html click element vs selecting the content
Is there any way to differentiate between clicking a div element and selecting its content,

What I am looking for is to trigger click action only if the div was clicked
but not when its contents were selected

```<code><div onClick="funA">
    Allow content to be copied if selected, else perform funA when clicked
</div>
</code>```

Current onClick behavior triggers when I try to select the content and copy it, as soon as i unpress the click, But I want to not trigger funA or detect its selected and control it somehow.
I hope the question is clear enough, else I will add more specifics to the quesiton.

答:
Refering to Preventing click event with jQuery drag and drop using $("#element").click(function(mouseEvent){ // click event }); will not execute when the mouse is dragged and dropped.

```<code>$("#funA").click(function(mouseEvent){  });

<div id="funA">
    Allow content to be copied if selected, else perform funA when clicked
</div>
</code>```

Body:
Is there any way to differentiate between clicking a div element and selecting its content,

What I am looking for is to trigger click action only if the div was clicked
but not when its contents were selected

    Allow content to be copied if selected, else perform funA when clicked

Current onClick behavior triggers when I try to select the content and copy it, as soon as i unpress the click, But I want to not trigger funA or detect its selected and control it somehow.
I hope the question is clear enough, else I will add more specifics to the quesiton.

Body:
Refering to Preventing click event with jQuery drag and drop using $("#element").click(function(mouseEvent){ // click event }); will not execute when the mouse is dragged and dropped.

$("#funA").click(function(mouseEvent){  });

<div id="funA">
    Allow content to be copied if selected, else perform funA when clicked
</div>


问:
Unable to run multiple spec files at a time using protractor
To run multiple spec files using Protractor i have tried below 2 methods. none of them works.

I changed the "Protractor configuartion" file as below.

specs: [
'.//e2e//Profiles//AdditionalInfo//Certifications//cert_opt_selection-spec.ts',
'.//e2e//Profiles//AdditionalInfo//Certifications//cert_creation-spec.ts'
],

and use the below command

```<code>ng e2e
</code>```

2.From the command prompt i used below command.

```<code>ng e2e --specs='.//e2e//Profiles//AdditionalInfo//Certifications//cert_opt_selection-spec.ts' --specs ='.//e2e//Profiles//AdditionalInfo//Certifications//cert_creation-spec.ts'
</code>```

Can any one help me how to execute multiple spec files at a time in protractor

答:
Modify your config file with below capabilities object,

```<code>  capabilities: {
    'browserName': 'chrome',
    'maxInstances' : 2 // will split your test files across 2 browser instances
    'shardTestFiles': true,
}
</code>```

If you want to run it on different browsers, You need to use multiCapabilities instead of capabilities. Refer https://www.linkedin.com/pulse/parallel-test-execution-protractor-sudharsan-selvaraj/ for additional details on multiCapabilities.

Body:
To run multiple spec files using Protractor i have tried below 2 methods. none of them works.

I changed the "Protractor configuartion" file as below.

specs: [
'.//e2e//Profiles//AdditionalInfo//Certifications//cert_opt_selection-spec.ts',
'.//e2e//Profiles//AdditionalInfo//Certifications//cert_creation-spec.ts'
],

and use the below command

ng e2e

2.From the command prompt i used below command.

ng e2e --specs='.//e2e//Profiles//AdditionalInfo//Certifications//cert_opt_selection-spec.ts' --specs ='.//e2e//Profiles//AdditionalInfo//Certifications//cert_creation-spec.ts'

Can any one help me how to execute multiple spec files at a time in protractor

Body:
Modify your config file with below capabilities object,

  capabilities: {
    'browserName': 'chrome',
    'maxInstances' : 2 // will split your test files across 2 browser instances
    'shardTestFiles': true,
}

If you want to run it on different browsers, You need to use multiCapabilities instead of capabilities. Refer https://www.linkedin.com/pulse/parallel-test-execution-protractor-sudharsan-selvaraj/ for additional details on multiCapabilities.


问:
How to build local web proxy without configuring the browsers
How does Netnanny or k9 Web Protection setup web proxy without configuring the browsers?
How can it be done?</p>

答:
I think what you need is a transparent proxy that support WCCP.

Take a look at squid-cache FAQ page

And the Wikipedia entry for WCCP

With that setup you just need to do some firewall configuration and all your web traffic will be handled by the transparent proxy. And no setup will be needed on your browser.


问:
System.Data.SqlClient. Cannot use after install
I have problem about using the System.Data.SqlClient. I install it from nugget search but then when i got to my project it looks like i cant even use it.

```<code>using System;
using System.Data.SqlClient;
namespace dvadvanced
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var buffer = new SqlConnection();
        }
    }
}
</code>```

I add it but using System.Data.SqlClient just stays grey like i dont have it.

答: Add a reference to System.Data before using the assembly System.Data.SqlClient.

Body:
I have problem about using the System.Data.SqlClient. I install it from nugget search but then when i got to my project it looks like i cant even use it.

using System;
using System.Data.SqlClient;
namespace dvadvanced
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var buffer = new SqlConnection();
        }
    }
}

I add it but using System.Data.SqlClient just stays grey like i dont have it.


问:
C - MPI Slow Performance
I am trying to learn MPI and running into slow performance using MPI on Windows on my laptop (i5-4260U and 4 GB of RAM). I have installed Cygwin and the appropriate libraries for MPI. I am also using CLion and set up MPI using this guide.

I have successfully built the code on CLion as well as compiling it on MPICC. However, when I use MPI Run, the program takes a very long time to run. When I run the program normally without using mpirun, it runs just fine. Even when I specify only 1 process, the program still takes over a minute to print out "Hello World".

Is my laptop the reason for the slow performance or have I not setup MPI correctly to get optimal performance? Thanks!

Code:

```<code>/*Simple MPI Hello World Program*/
#include <stdio.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    int node;

    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &node);

    printf("Hello World from Node %d\n",node);

    MPI_Finalize();
}
</code>```

CMake:

```<code>cmake_minimum_required(VERSION 3.8)
project(MPI_Example)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)
add_executable(MPI_Example ${SOURCE_FILES})

# Require MPI for this project:
find_package(MPI REQUIRED)
set(CMAKE_CXX_COMPILE_FLAGS ${CMAKE_CXX_COMPILE_FLAGS} ${MPI_COMPILE_FLAGS})
set(CMAKE_CXX_LINK_FLAGS ${CMAKE_CXX_LINK_FLAGS} ${MPI_LINK_FLAGS})
include_directories(${MPI_INCLUDE_PATH})
target_link_libraries(MPI_Example ${MPI_LIBRARIES})
</code>```

答:
The most likely issue is a network/virtual interface timeout.
Try disabling WIFI network or VPN interface as test.

For reference of expected timing for MPI hello you can see

https://cygwin.com/ml/cygwin/2016-12/msg00192.html

Title: C - MPI Slow Performance

Body:
I am trying to learn MPI and running into slow performance using MPI on Windows on my laptop (i5-4260U and 4 GB of RAM). I have installed Cygwin and the appropriate libraries for MPI. I am also using CLion and set up MPI using this guide.

I have successfully built the code on CLion as well as compiling it on MPICC. However, when I use MPI Run, the program takes a very long time to run. When I run the program normally without using mpirun, it runs just fine. Even when I specify only 1 process, the program still takes over a minute to print out "Hello World".

Is my laptop the reason for the slow performance or have I not setup MPI correctly to get optimal performance? Thanks!

Code:

/*Simple MPI Hello World Program*/
#include <stdio.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    int node;

    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &node);

    printf("Hello World from Node %d\n",node);

    MPI_Finalize();
}

CMake:

cmake_minimum_required(VERSION 3.8)
project(MPI_Example)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)
add_executable(MPI_Example ${SOURCE_FILES})

# Require MPI for this project:
find_package(MPI REQUIRED)
set(CMAKE_CXX_COMPILE_FLAGS ${CMAKE_CXX_COMPILE_FLAGS} ${MPI_COMPILE_FLAGS})
set(CMAKE_CXX_LINK_FLAGS ${CMAKE_CXX_LINK_FLAGS} ${MPI_LINK_FLAGS})
include_directories(${MPI_INCLUDE_PATH})
target_link_libraries(MPI_Example ${MPI_LIBRARIES})


问:
SQL - Display Minimum Value
I am new to SQL Oracle and have been working on this for nearly 10 hrs.  I am trying to show record that has minimum share amount. Here is my code:

```<code>SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name;
</code>```

All this provides is a list of brokers and their share amounts. I just want the minimum.

Please help! I know it will be something simple but I cant figure out what.

答:
Here's one way that will return all rows that have the minimum share amount:

```<code>SELECT b.first_name||' '||b.last_name AS broker,
       t.share_amount
FROM   brokers b
       right outer JOIN (SELECT *
                         FROM   (select broker_id,
                                        share_amount,
                                        min(share_amount) over () min_share_amount
                                 from   trades)
                         WHERE  share_amount = min_share_amount) t
         ON b.broker_id = t.broker_id;
</code>```

This uses the MIN() analytic function to return the minimum share_amount across the whole trades table. Then we can filter the results to only bring back those rows whose share_amount matches the min_share_amount. Finally, we can join the brokers table to this subquery.

Title: SQL - Display Minimum Value

Body:
I am new to SQL Oracle and have been working on this for nearly 10 hrs.  I am trying to show record that has minimum share amount. Here is my code:

SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name;

All this provides is a list of brokers and their share amounts. I just want the minimum.

Please help! I know it will be something simple but I cant figure out what.

Body:
Here's one way that will return all rows that have the minimum share amount:

SELECT b.first_name||' '||b.last_name AS broker,
       t.share_amount
FROM   brokers b
       right outer JOIN (SELECT *
                         FROM   (select broker_id,
                                        share_amount,
                                        min(share_amount) over () min_share_amount
                                 from   trades)
                         WHERE  share_amount = min_share_amount) t
         ON b.broker_id = t.broker_id;

This uses the MIN() analytic function to return the minimum share_amount across the whole trades table. Then we can filter the results to only bring back those rows whose share_amount matches the min_share_amount. Finally, we can join the brokers table to this subquery.


问:
Select rows having equal values in one column but not those are alone
This is my SQLfiddle : http://sqlfiddle.com/#!9/6a335/1/0

The result I want is the same like picture but without the 2 red rows, because for id_association_mots_idM 476 and 478, there is no traduction in english in the table.

I tried many requests and many ways.
Is it possible and if yes, how ?

Thanks for your help.

答:
The query below excludes the RED rows.

```<code>SELECT v_all.id_association_mots_idM,
       v_all.id_vocab_idM,
       v_all.id_vocab_idM,
       v_all.mot_v
  FROM (SELECT  ass_m_m.id_association_mots_idM,
                ass_m_m.id_vocab_idM,
                v_a_m.categorie_v ,
                v_a_m.mot_v
        FROM  `association_mots_login` AS ass_m_l,
              `association_mots_id_mot` AS ass_m_m,
              `vocabulaire_a_memoriser` AS v_a_m
        WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
          AND ass_m_l.id_login_mL = '1'
          AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
          AND v_a_m.categorie_v IN ('langue_francais', 'langue_anglais')) v_all,
        (SELECT DISTINCT ass_m_m.id_association_mots_idM
          FROM  `association_mots_login` AS ass_m_l,
                `association_mots_id_mot` AS ass_m_m,
                `vocabulaire_a_memoriser` AS v_a_m
          WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
            AND ass_m_l.id_login_mL = '1'
            AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
            AND v_a_m.categorie_v = 'langue_anglais') v_eng
WHERE v_all.id_association_mots_idM = v_eng.id_association_mots_idM        ;
</code>```

Explanation:

In-line view v_all is same as what you had. Gets all the records for both langue_francais and langue_anglais. Inline view v_eng only gets the records where there is a traduction in english i.e. langue_anglais.
Inner joining the 2 views would give you just the records with english traduction.

Hope this helps!

Body:
The query below excludes the RED rows.

SELECT v_all.id_association_mots_idM,
       v_all.id_vocab_idM,
       v_all.id_vocab_idM,
       v_all.mot_v
  FROM (SELECT  ass_m_m.id_association_mots_idM,
                ass_m_m.id_vocab_idM,
                v_a_m.categorie_v ,
                v_a_m.mot_v
        FROM  `association_mots_login` AS ass_m_l,
              `association_mots_id_mot` AS ass_m_m,
              `vocabulaire_a_memoriser` AS v_a_m
        WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
          AND ass_m_l.id_login_mL = '1'
          AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
          AND v_a_m.categorie_v IN ('langue_francais', 'langue_anglais')) v_all,
        (SELECT DISTINCT ass_m_m.id_association_mots_idM
          FROM  `association_mots_login` AS ass_m_l,
                `association_mots_id_mot` AS ass_m_m,
                `vocabulaire_a_memoriser` AS v_a_m
          WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
            AND ass_m_l.id_login_mL = '1'
            AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
            AND v_a_m.categorie_v = 'langue_anglais') v_eng
WHERE v_all.id_association_mots_idM = v_eng.id_association_mots_idM        ;

Explanation:

In-line view v_all is same as what you had. Gets all the records for both langue_francais and langue_anglais. Inline view v_eng only gets the records where there is a traduction in english i.e. langue_anglais.
Inner joining the 2 views would give you just the records with english traduction.

Hope this helps!


问:
Sending UDP packets on iPhone fails over a fresh new 3G connection, but works otherwise
I'm having a strange problem when sending UDP packets from an iPhone over a 3G. Almost every time my application starts after a longer period of network inactivity (for instance after the phone comes from the sleep mode or it just gets a 3G connection), my application is not able to send any UDP packets. I get a kCFSocketError error status from CFSocketSendData. The application logic then re-tries to send the packet periodically every five seconds, but no matter how long I let it run it keeps failing. However, when I switch the application to background and open, for instance, a web page in Safari (while the application is still failing on background), the application suddenly starts working. Basically, it seems like the other network activity (from Safari, Maps etc.) "kicks off the networking for real". Do I need to do anything special in terms of network initialisation for instance?

This is a simplified snippet of the code I'm using to send the UDP packets:

```<code>CFSocketRef cfSocket = CFSocketCreate(NULL, 0, SOCK_DGRAM, IPPROTO_UDP, kCFSocketNoCallBack, NULL, NULL);
if (!cfSocket)
{
    // snip: some error handling
}

struct sockaddr_in addr;
// snip: init addr

CFDataRef cfAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr));

CFSocketError sendPacketResult = CFSocketSendData(cfSocket, cfAddr, cfPacketData, 0.0);
if (sendPacketResult != kCFSocketSuccess)
{
    // try again in 5 seconds
}
</code>```

It all works fine without any problems over Wi-Fi.

To be fair, I think I've seen sometimes (but very occasionally) the same behaviour in the standard iPhone applications (Safari, Maps, ...) as well. Sometimes they refuse to connect (even thought I see the 3G icon) and I need to close and reopen them. But it's very rare.

Edit: Possibly related question: On iPhone, what does EPERM (errno == 1) mean in reponse to send() of UDP data?.

答:
The 3G TCP/IP network interface can be torn down by IOS at the operating system's pleasure, generally for power-saving reasons if there is no traffic going across it. When using BSD sockets (for example, for UDP, since there is no UDP apple  networking framework) there's no published OS call for ensuring the 3G network interface is up. But internally in Apple's CFSocketStream class there exists private Apple calls that wake up the interface.

So the solution seems to be to open up a CFSocketStream to someplace. That will wake up the interface for some period of time. As long as you send data over the CFSocketStream once a minute or so the connection and the network interface will stay up.

This isn't all that attractive, since it's only working by side effect. But it seems to be the only solution at this point.

Body:
I'm having a strange problem when sending UDP packets from an iPhone over a 3G. Almost every time my application starts after a longer period of network inactivity (for instance after the phone comes from the sleep mode or it just gets a 3G connection), my application is not able to send any UDP packets. I get a kCFSocketError error status from CFSocketSendData. The application logic then re-tries to send the packet periodically every five seconds, but no matter how long I let it run it keeps failing. However, when I switch the application to background and open, for instance, a web page in Safari (while the application is still failing on background), the application suddenly starts working. Basically, it seems like the other network activity (from Safari, Maps etc.) "kicks off the networking for real". Do I need to do anything special in terms of network initialisation for instance?

This is a simplified snippet of the code I'm using to send the UDP packets:

CFSocketRef cfSocket = CFSocketCreate(NULL, 0, SOCK_DGRAM, IPPROTO_UDP, kCFSocketNoCallBack, NULL, NULL);
if (!cfSocket)
{
    // snip: some error handling
}

struct sockaddr_in addr;
// snip: init addr

CFDataRef cfAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr));

CFSocketError sendPacketResult = CFSocketSendData(cfSocket, cfAddr, cfPacketData, 0.0);
if (sendPacketResult != kCFSocketSuccess)
{
    // try again in 5 seconds
}

It all works fine without any problems over Wi-Fi.

To be fair, I think I've seen sometimes (but very occasionally) the same behaviour in the standard iPhone applications (Safari, Maps, ...) as well. Sometimes they refuse to connect (even thought I see the 3G icon) and I need to close and reopen them. But it's very rare.

Edit: Possibly related question: On iPhone, what does EPERM (errno == 1) mean in reponse to send() of UDP data?.


问:
Super slow preflight OPTIONS in Chrome only
I've been struggling recently with a super-weird problem only happening in Chrome: as my API (NodeJS) is on a different subdomain, I need to use CORS to reach it from my front-end (EmberJS).

It's working pretty well but I'm very frequently (95% of the time) having very very slow OPTIONS queries, delaying any API calls by about 3 seconds.

Most of this time is spent downloading an empty content:

It gets even weirder when I'm trying this on another website we made using a similar architecture, experiencing the exact same problem.

A few other things I tried:

I've been trying this with Firefox and Safari, and didn't get any delay.

I've been trying this locally or in production, experimenting the same delay.

I've been trying this with incognito mode (no extensions), and I have the exact same problem.

We're using on the back-end NodeJS with the CORS package.

Now, I have no idea if the problem is on either Chrome 60, NodeJS, the CORS package or EmberJS + jQuery.

Anyone experienced this too?

答:
Just as a note: It seems a chrome bug

I reproduced the issue using a server with two DNS names using a service in a unique domain

```<code>https://domain1.com  --> https://domain1.com (No CORS, no delay)
https://domain2.com  --> https://domain1.com (CORS, delay)
</code>```

It is exactly the same service responding to two names, so I am testing exactly the same request, client and server code (DNS names are interchangeable)

Tested with

Chrome 61.0.3163.100 (Windows) -->DELAY

Chrome 62.0.3202.84 (Android) -->DELAY

Chrome 62.0.3202.84 (iOS-Ipad) -->OK!!!

Firefox-->OK

Edge --> OK

Workaround (in my case). Create a proxy in my host to respond to the same origin DNS and avoid CORS

Body:
Just as a note: It seems a chrome bug

I reproduced the issue using a server with two DNS names using a service in a unique domain

https://domain1.com  --> https://domain1.com (No CORS, no delay)
https://domain2.com  --> https://domain1.com (CORS, delay)

It is exactly the same service responding to two names, so I am testing exactly the same request, client and server code (DNS names are interchangeable)

Tested with

Chrome 61.0.3163.100 (Windows) -->DELAY

Chrome 62.0.3202.84 (Android) -->DELAY

Chrome 62.0.3202.84 (iOS-Ipad) -->OK!!!

Firefox-->OK

Edge --> OK

Workaround (in my case). Create a proxy in my host to respond to the same origin DNS and avoid CORS


问:
How do I catch an rpy2.rinterface.RRuntimeError in Python?
Setup:

Python 3.5.3 |Continuum Analytics, Inc.| (default, Mar  6 2017, 12:15:08)

Mac OSX 10.13.1

Problem:

I have downloaded the following R script https://github.com/daleroberts/heston/blob/master/heston.r
and I repeatedly call one of the functions in there via Python using the package RPy2. Now, for some of my inputs that I feed into the R function, R returns the following error:

rpy2.rinterface.RRuntimeError: Error in integrate(PIntegrand, lower =
  0, upper = Inf, lambda, vbar, eta,  :    roundoff error was detected

How do I go about catching this RuntimeError in Python?

答:
Python makes catching exceptions relatively easy.</p>

```<code>try:
    # some code
except Exception, e:
    # Log the exception.
</code>```

Body:
Python makes catching exceptions relatively easy.

try:
    # some code
except Exception, e:
    # Log the exception.


问:
How to transpose this table in SQL Server 2012

I want to transpose this table which has only 1 row with client id and the response columns as response1, response2 and so on.

I tried with pivot but not able to apply correctly

答:
Try this:

```<code>IF OBJECT_ID('tempdb..#DataSource') IS NOT NULL
BEGIN
    DROP TABLE #DataSource;
END;

CREATE TABLE #DataSource
(
    [ClientID] INT
   ,[Response] VARCHAR(24)
);

INSERT INTO #DataSource ([ClientID], [Response])
VALUES (3316, 'omellette')
      ,(3316, 'mmer')
      ,(3316, 'joy')
      ,(3316, 'gift')
      ,(3316, 'strong')
      ,(3316, 'rrailores')
      ,(3316, 'something else');

SELECT *
FROM
(
    SELECT [ClientID]
          ,[Response]
          ,'Response' + CAST(ROW_NUMBER() OVER (PARTITION BY [ClientID] ORDER BY (SELECT 1)) AS VARCHAR(12)) AS [Col]
    FROM #DataSource
) DS
PIVOT
(
    MAX([Response]) FOR [Col] IN ([Response1], [Response2], [Response3], [Response4], [Response5], [Response6], [Response7])
) PVT;
</code>```

Here is the dynamic version. Note we are first getting unique responses (in case you want to get data for more clients and they share responses, you will get them in one column):

```<code>DECLARE @DynamicTSQLStatement NVARCHAR(MAX)
       ,@DynamicColumns NVARCHAR(MAX);

WITH DataSource AS
(
    SELECT DISTINCT [Response]
    FROM #DataSource
)
SELECT @DynamicColumns = STUFF
(
    (
        SELECT DISTINCT ',[Response' + CAST(ROW_NUMBER() OVER (ORDER BY [Response]) AS VARCHAR(12)) + ']'
        FROM DataSource
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,1
    ,''
);

SET @DynamicTSQLStatement = N'
SELECT *
FROM
(
    SELECT [ClientID]
          ,[Response]
          ,''Response'' + CAST(ROW_NUMBER() OVER (PARTITION BY [ClientID] ORDER BY [Response]) AS VARCHAR(12)) AS [Col]
    FROM #DataSource
) DS
PIVOT
(
    MAX([Response]) FOR [Col] IN ('+@DynamicColumns+')
) PVT;';

EXEC sp_executesql @DynamicTSQLStatement;
</code>```

Body:
Try this:

IF OBJECT_ID('tempdb..#DataSource') IS NOT NULL
BEGIN
    DROP TABLE #DataSource;
END;

CREATE TABLE #DataSource
(
    [ClientID] INT
   ,[Response] VARCHAR(24)
);

INSERT INTO #DataSource ([ClientID], [Response])
VALUES (3316, 'omellette')
      ,(3316, 'mmer')
      ,(3316, 'joy')
      ,(3316, 'gift')
      ,(3316, 'strong')
      ,(3316, 'rrailores')
      ,(3316, 'something else');

SELECT *
FROM
(
    SELECT [ClientID]
          ,[Response]
          ,'Response' + CAST(ROW_NUMBER() OVER (PARTITION BY [ClientID] ORDER BY (SELECT 1)) AS VARCHAR(12)) AS [Col]
    FROM #DataSource
) DS
PIVOT
(
    MAX([Response]) FOR [Col] IN ([Response1], [Response2], [Response3], [Response4], [Response5], [Response6], [Response7])
) PVT;

Here is the dynamic version. Note we are first getting unique responses (in case you want to get data for more clients and they share responses, you will get them in one column):

DECLARE @DynamicTSQLStatement NVARCHAR(MAX)
       ,@DynamicColumns NVARCHAR(MAX);

WITH DataSource AS
(
    SELECT DISTINCT [Response]
    FROM #DataSource
)
SELECT @DynamicColumns = STUFF
(
    (
        SELECT DISTINCT ',[Response' + CAST(ROW_NUMBER() OVER (ORDER BY [Response]) AS VARCHAR(12)) + ']'
        FROM DataSource
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,1
    ,''
);

SET @DynamicTSQLStatement = N'
SELECT *
FROM
(
    SELECT [ClientID]
          ,[Response]
          ,''Response'' + CAST(ROW_NUMBER() OVER (PARTITION BY [ClientID] ORDER BY [Response]) AS VARCHAR(12)) AS [Col]
    FROM #DataSource
) DS
PIVOT
(
    MAX([Response]) FOR [Col] IN ('+@DynamicColumns+')
) PVT;';

EXEC sp_executesql @DynamicTSQLStatement;


问:
Why the code is executing again even after the if condition returning false value?
Consider below code :

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 2) {
      test();
      echo "In last line...".$count."<br>";
    }
    $count--;
    echo "Count Value : ".$count."<br>";
  }
  test();
?>
</code>```

Output is as below :

```<code>1
2
Count Value : 1
In last line...1
Count Value : 0
</code>```

I'm confused about the following part from the above output which is outlined with red colored border.

I want to know after if returning false on becoming $count = 2 the immediately following code line  echo "Count Value : ".$count."
"; gets executed. Then, it is expected to stop the flow as it's the last statement.

Why the program flow is not stopping after printing the line Count
Value : 1?

Then how the last two lines from the output are generating?

Who is calling the test() function again?

How does the static variable getting reset to 0 again and printing the last two lines of the output?

Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

答:
One by one answers.

1.Why the program flow is not stopping after printing the line Count Value : 1?

=> Because printing the line Count Value : 1 is done on the 2nd call of the function test().

2.Then how the last two lines from the output are generating?

=> After finishing the 2nd call, it still needs to complete it's first call which start again at

```<code>    echo "In last line...".$count."<br>";
</code>```

3.Who is calling the test() function again?

=> 2nd line of below code snippet  is calling function again.

```<code>    if($count < 2) {
      test();
      echo "In last line...".$count."<br>";
    }
</code>```

3.How does the static variable getting reset to 0 again and printing the last two lines of the output?

=> static variable does not get reset, static will only initialize the variable once, and once initiated it wont bother with the value.

4.Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

=> Yes

Body:
Consider below code :

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."
";
    if($count < 2) {
      test();
      echo "In last line...".$count."
";
    }
    $count--;
    echo "Count Value : ".$count."
";
  }
  test();
?>

Output is as below :

1
2
Count Value : 1
In last line...1
Count Value : 0

I'm confused about the following part from the above output which is outlined with red colored border.

I want to know after if returning false on becoming $count = 2 the immediately following code line  echo "Count Value : ".$count."
"; gets executed. Then, it is expected to stop the flow as it's the last statement.

Why the program flow is not stopping after printing the line Count
Value : 1?

Then how the last two lines from the output are generating?

Who is calling the test() function again?

How does the static variable getting reset to 0 again and printing the last two lines of the output?

Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

Body:
One by one answers.

1.Why the program flow is not stopping after printing the line Count Value : 1?

=> Because printing the line Count Value : 1 is done on the 2nd call of the function test().

2.Then how the last two lines from the output are generating?

=> After finishing the 2nd call, it still needs to complete it's first call which start again at

    echo "In last line...".$count."<br>";

3.Who is calling the test() function again?

=> 2nd line of below code snippet  is calling function again.

    if($count < 2) {
      test();
      echo "In last line...".$count."<br>";
    }

3.How does the static variable getting reset to 0 again and printing the last two lines of the output?

=> static variable does not get reset, static will only initialize the variable once, and once initiated it wont bother with the value.

4.Does in recursion the remaining code after the function call gets executed as many times as the recursive function got called upon failure of the test condition?

=> Yes


问:
matching rows between dataframes in pandas in python
I have two dataframes,

df1,

```<code> Names
 one two three
 Sri is a good player
 Ravi is a mentor
 Kumar is a cricketer
</code>```

df2,

```<code> values
 sri
 NaN
 sri, is
 kumar,cricketer
</code>```

I am trying to get the row in df1 which contains the all the items in df2

My expected output is,

```<code> values             Names
 sri                Sri is a good player
 NaN
 sri, is            Sri is a good player
 kumar,cricketer    Kumar is a cricketer
</code>```

i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist()))

but I cannot achieve my expected output as it has (","). Please help

答:
```<code>import pandas as pd
names =  [
    'one two three',
    'Sri is a good player',
    'Ravi is a mentor',
    'Kumar is a cricketer'
]
values = [
    'sri',
    'NaN',
    'sri, is',
    'kumar,cricketer',
]

names = pd.Series(names)
values = pd.DataFrame(values, columns=['values'])

def foo(words):
    names_copy = names.copy()

    for word in words.split(','):
        names_copy = names_copy[names_copy.str.contains(word, case=False)]

    return names_copy.values

 values['names'] = values['values'].map(foo)
 values

    values          names
0   sri             [Sri is a good player]
1   NaN             []
2   sri, is         [Sri is a good player]
3   kumar,cricketer [Kumar is a cricketer]
</code>```

Body:
I have two dataframes,

df1,

 Names
 one two three
 Sri is a good player
 Ravi is a mentor
 Kumar is a cricketer

df2,

 values
 sri
 NaN
 sri, is
 kumar,cricketer

I am trying to get the row in df1 which contains the all the items in df2

My expected output is,

 values             Names
 sri                Sri is a good player
 NaN
 sri, is            Sri is a good player
 kumar,cricketer    Kumar is a cricketer

i tried, df1["Names"].str.contains("|".join(df2["values"].values.tolist()))

but I cannot achieve my expected output as it has (","). Please help


问:
SI To DI copy error for reverse
Suppose We have number 321 which si points to offset 1
and temp's offset is in di .

```<code>mov di,offset temp
</code>```

Now we want to copy from si to di by this commands :

```<code>mov cx,3
reverse:
 mov dl,byte ptr [si]
 mov byte ptr[di],dl
 inc di
 dec si
loop reverse
mov byte ptr[di],'$'
</code>```

but outputs me 113 not 123 , it means the integer 2 will be removed.

答:
If the initial conditions really are as you describe, I think your temp storage area must overlap with the original input: I don't see how your loop would result in a duplicate "1" otherwise.

Specifically, I would guess that temp points to the byte immediately after the beginning of the original input (as a really wild guess: perhaps the buffer where "321" is reserved in a data section, and has been accidentally declared as only a single byte, and temp is declared immediately afterwards).

i.e. initially:

```<code>   buffer for original number
     |
     |  temp (== di) actually points here
     |   |
     v   v
---+---+---+---+---+---
   | 3 | 2 | 1 |   |
---+---+---+---+---+---
             ^
             |
        initial si
</code>```

After the first iteration, the "1" has overwritten the "2":

```<code>        temp
         |
         v  di
---+---+---+---+---+---
   | 3 | 1 | 1 |   |
---+---+---+---+---+---
        si
</code>```

After the second iteration, the "1" (which was originally a "2") is copied over the original "1":

```<code>        temp
         |
         v      di
---+---+---+---+---+---
   | 3 | 1 | 1 |   |
---+---+---+---+---+---
    si
</code>```

After the third iteration, the "3" is copied:

```<code>        temp
         |
         v          di
---+---+---+---+---+---
   | 3 | 1 | 1 | 3 |
---+---+---+---+---+---
si
</code>```

...and finally with the $ on the end:

```<code>        temp
         |
         v          di
---+---+---+---+---+---
   | 3 | 1 | 1 | 3 | $
---+---+---+---+---+---
si
</code>```

...so temp now points to "113".

Title: SI To DI copy error for reverse

Body:
Suppose We have number 321 which si points to offset 1
and temp's offset is in di .

mov di,offset temp

Now we want to copy from si to di by this commands :

mov cx,3
reverse:
 mov dl,byte ptr [si]
 mov byte ptr[di],dl
 inc di
 dec si
loop reverse
mov byte ptr[di],'$'

but outputs me 113 not 123 , it means the integer 2 will be removed.

Body:
If the initial conditions really are as you describe, I think your temp storage area must overlap with the original input: I don't see how your loop would result in a duplicate "1" otherwise.

Specifically, I would guess that temp points to the byte immediately after the beginning of the original input (as a really wild guess: perhaps the buffer where "321" is reserved in a data section, and has been accidentally declared as only a single byte, and temp is declared immediately afterwards).

i.e. initially:

   buffer for original number
     |
     |  temp (== di) actually points here
     |   |
     v   v
---+---+---+---+---+---
   | 3 | 2 | 1 |   |
---+---+---+---+---+---
             ^
             |
        initial si

After the first iteration, the "1" has overwritten the "2":

        temp
         |
         v  di
---+---+---+---+---+---
   | 3 | 1 | 1 |   |
---+---+---+---+---+---
        si

After the second iteration, the "1" (which was originally a "2") is copied over the original "1":

        temp
         |
         v      di
---+---+---+---+---+---
   | 3 | 1 | 1 |   |
---+---+---+---+---+---
    si

After the third iteration, the "3" is copied:

        temp
         |
         v          di
---+---+---+---+---+---
   | 3 | 1 | 1 | 3 |
---+---+---+---+---+---
si

...and finally with the $ on the end:

        temp
         |
         v          di
---+---+---+---+---+---
   | 3 | 1 | 1 | 3 | $
---+---+---+---+---+---
si

...so temp now points to "113".


问:
How to get token well retrieved in services into controller (Core 2.0 oAuth 2)?
In ASP.Net MVC Core 2, we are trying to call the Linkedin web API with OAuth authentication.
We are able to declare the OAuth authentication service and retrieve the access token from Linkedin as shown in the code below.
Now we would like to request the API from a controller. To do that, we have to get the access token from the OAuth service we have declared with the AddOAuth method. How can we do that? No way to find an example anywhere.

Thanx for your help, we are really stuck.

```<code>        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie("linkedin_login", options =>
           {
               options.LoginPath = new PathString("/login");
               options.LogoutPath = new PathString("/logout");
           })
           .AddOAuth("LinkedIn", options =>
           {
               options.SignInScheme = "linkedin_login";
               options.ClientId = Configuration["linkedin:clientId"];
               options.ClientSecret = Configuration["linkedin:clientSecret"];
               options.CallbackPath = new PathString("/signin-linkedin");

               options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
               options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
               options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,email-address,picture-url,picture-urls,headline,public-profile-url,industry,three-current-positions,three-past-positions,positions::(original))";

               // To save the tokens to the Authentication Properties we need to set this to true
               // See code in OnTicketReceived event below to extract the tokens and save them as Claims
               options.SaveTokens = true;

               options.Scope.Add("r_basicprofile");
               options.Scope.Add("r_emailaddress");

               options.Events = new OAuthEvents
               {
                   OnCreatingTicket = async context =>
                   {
                       #region OnCreatingTicket
                       // Retrieve user info
                       var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
</code>```

//We have here the token: context.AccessToken
                           request.Headers.Add("x-li-format", "json"); // Tell LinkedIn we want the result in JSON, otherwise it will return XML

答:
the solution is just :

```<code> var AccessToken = await HttpContext.GetTokenAsync("LinkedIn", "access_token");
</code>```

with "LinkedIn" the scheme of the desired oAuth

Body:
In ASP.Net MVC Core 2, we are trying to call the Linkedin web API with OAuth authentication.
We are able to declare the OAuth authentication service and retrieve the access token from Linkedin as shown in the code below.
Now we would like to request the API from a controller. To do that, we have to get the access token from the OAuth service we have declared with the AddOAuth method. How can we do that? No way to find an example anywhere.

Thanx for your help, we are really stuck.

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie("linkedin_login", options =>
           {
               options.LoginPath = new PathString("/login");
               options.LogoutPath = new PathString("/logout");
           })
           .AddOAuth("LinkedIn", options =>
           {
               options.SignInScheme = "linkedin_login";
               options.ClientId = Configuration["linkedin:clientId"];
               options.ClientSecret = Configuration["linkedin:clientSecret"];
               options.CallbackPath = new PathString("/signin-linkedin");

               options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
               options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
               options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,email-address,picture-url,picture-urls,headline,public-profile-url,industry,three-current-positions,three-past-positions,positions::(original))";

               // To save the tokens to the Authentication Properties we need to set this to true
               // See code in OnTicketReceived event below to extract the tokens and save them as Claims
               options.SaveTokens = true;

               options.Scope.Add("r_basicprofile");
               options.Scope.Add("r_emailaddress");

               options.Events = new OAuthEvents
               {
                   OnCreatingTicket = async context =>
                   {
                       #region OnCreatingTicket
                       // Retrieve user info
                       var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

//We have here the token: context.AccessToken
                           request.Headers.Add("x-li-format", "json"); // Tell LinkedIn we want the result in JSON, otherwise it will return XML

Body:
the solution is just :

 var AccessToken = await HttpContext.GetTokenAsync("LinkedIn", "access_token");

with "LinkedIn" the scheme of the desired oAuth


问:
C printf Segmentation fault (core dumped) while mixing with Assembly code
I tried some basic example of mixing C code and x86 Assembly code.
It is simple Find smaller number example.

Here is Assembly code in b.s file (I have to use intel syntax with no prefix and i386 architecture):

```<code>.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            leave
        ret 8

.end
</code>```

Here is the C code in a.c file:

```<code>#include<stdio.h>

extern char out_format;

extern int min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}
</code>```

I compile it with gcc on x64 Arch Linux:

```<code>gcc -m32 -Wall -Werror -g -o p b.s a.c
</code>```

But when I start the executable file p, and insert 2 numbers and hit enter
I get:

```<code>Segmentation fault (core dumped)
</code>```

I researched all previous similar questions, and I tried several things but every time I get the same error.
I also tried to debug it with gdb, and I see that Assembly function min returns the right result, but somehow it always stuck on C printf function.

I tried to not import string out_format from Assembly file, and define it directly in C file (I defined it as simple array of chars, and also as char pointer using malloc and free functions) but it didn't help.

Otherwise the program doesn't give such error if I intialize variable r with some integer instead with result of Assembly function min. But it doesn't have any sense to me as I already checked it with gdb and the Assembly function correctly intialize the variable r with correct smaller number.

Please, can anyone help me with this?

Thanks in advance

答:
if min() works good, check out_format.

following code works.

```<code>printf("%d %d %d\n", x1, x2, r);
</code>```

full code

```<code>#include<stdio.h>

int min(int x, int y)
{
    if (x<y) return x;
    return y;
}

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf("%d %d %d\n", x1, x2, r);
    return 0;
}
</code>```

Body:
I tried some basic example of mixing C code and x86 Assembly code.
It is simple Find smaller number example.

Here is Assembly code in b.s file (I have to use intel syntax with no prefix and i386 architecture):

.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            leave
        ret 8

.end

Here is the C code in a.c file:

#include<stdio.h>

extern char out_format;

extern int min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}

I compile it with gcc on x64 Arch Linux:

gcc -m32 -Wall -Werror -g -o p b.s a.c

But when I start the executable file p, and insert 2 numbers and hit enter
I get:

Segmentation fault (core dumped)

I researched all previous similar questions, and I tried several things but every time I get the same error.
I also tried to debug it with gdb, and I see that Assembly function min returns the right result, but somehow it always stuck on C printf function.

I tried to not import string out_format from Assembly file, and define it directly in C file (I defined it as simple array of chars, and also as char pointer using malloc and free functions) but it didn't help.

Otherwise the program doesn't give such error if I intialize variable r with some integer instead with result of Assembly function min. But it doesn't have any sense to me as I already checked it with gdb and the Assembly function correctly intialize the variable r with correct smaller number.

Please, can anyone help me with this?

Thanks in advance

Body:
if min() works good, check out_format.

following code works.

printf("%d %d %d\n", x1, x2, r);

full code

#include<stdio.h>

int min(int x, int y)
{
    if (x<y) return x;
    return y;
}

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf("%d %d %d\n", x1, x2, r);
    return 0;
}


问:
Why are spring beans validated even if the condition says it should not be loaded into the context?
Given the example below, I would expect MyConfig.getSrvConfig() would not be called and therefore no validation would be executed on the returned object neither.
But for some reason the validation is executed and the test case fails. Is there anything wrong in this setup?

I know the test would pass if I have private MySrvConfigBean srvConfig not initialized at declaration - but I really don't want MySrvConfigBean to be a standalone class with a @ConfigurationProperties(prefix = "cfg.srvConfig") annotation.

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { TestCaseConfiguration.class })
public class ConditionalConfigValidationTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test() {
        assertNotNull(applicationContext);
        assertFalse("srvConfig must NOT be in context", applicationContext.containsBean("srvConfig"));
    }

    @Configuration
    @EnableConfigurationProperties(value = { MyConfig.class })
    public static class TestCaseConfiguration {
    }

    @Component
    @Validated
    @ConfigurationProperties(prefix = "cfg")
    public static class MyConfig {
        private MySrvConfigBean srvConfig = new MySrvConfigBean();

        @Bean
        @Valid
        @Conditional(MyCondition.class)
        public MySrvConfigBean getSrvConfig() {
            return srvConfig;
        }

        public static class MySrvConfigBean {

            @NotNull
            private String name;

            public String getName() {
                return name;
            }
        }
    }

    public static class MyCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return false;
        }
    }
}
</code>```

The reason we would like to have it this way is, because we then are able to structure configuration in code the same way as we have it in the YAML file, e.g.: (cfg and cfgA are the "root" objects for two different configuration hierarchies).

```<code>cfg:
  srvConfig:
    name: Dude
  clientConfig:
    xxx: true
    yyy: Muster
cfgA:
  aaaConfig:
    bbb: false
    ccc: Dundy
  dddConfig:
    fff: 3
</code>```

It feels like the execution of the validation (triggered by @Valid on getSrvConfig()) is a bug in this case.

答:
Apparently this is not supported and should be solved in a different way:</p>

```<code>@Configuration
@Conditional(MyCondition.class)
@EnableConfigurationProperties(value = { MyConfig.class })
public static class TestCaseConfiguration {
}
</code>```

Body:
Given the example below, I would expect MyConfig.getSrvConfig() would not be called and therefore no validation would be executed on the returned object neither.
But for some reason the validation is executed and the test case fails. Is there anything wrong in this setup?

I know the test would pass if I have private MySrvConfigBean srvConfig not initialized at declaration - but I really don't want MySrvConfigBean to be a standalone class with a @ConfigurationProperties(prefix = "cfg.srvConfig") annotation.

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { TestCaseConfiguration.class })
public class ConditionalConfigValidationTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test() {
        assertNotNull(applicationContext);
        assertFalse("srvConfig must NOT be in context", applicationContext.containsBean("srvConfig"));
    }

    @Configuration
    @EnableConfigurationProperties(value = { MyConfig.class })
    public static class TestCaseConfiguration {
    }

    @Component
    @Validated
    @ConfigurationProperties(prefix = "cfg")
    public static class MyConfig {
        private MySrvConfigBean srvConfig = new MySrvConfigBean();

        @Bean
        @Valid
        @Conditional(MyCondition.class)
        public MySrvConfigBean getSrvConfig() {
            return srvConfig;
        }

        public static class MySrvConfigBean {

            @NotNull
            private String name;

            public String getName() {
                return name;
            }
        }
    }

    public static class MyCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return false;
        }
    }
}

The reason we would like to have it this way is, because we then are able to structure configuration in code the same way as we have it in the YAML file, e.g.: (cfg and cfgA are the "root" objects for two different configuration hierarchies).

cfg:
  srvConfig:
    name: Dude
  clientConfig:
    xxx: true
    yyy: Muster
cfgA:
  aaaConfig:
    bbb: false
    ccc: Dundy
  dddConfig:
    fff: 3

It feels like the execution of the validation (triggered by @Valid on getSrvConfig()) is a bug in this case.

Body:
Apparently this is not supported and should be solved in a different way:

@Configuration
@Conditional(MyCondition.class)
@EnableConfigurationProperties(value = { MyConfig.class })
public static class TestCaseConfiguration {
}


问:
docker-machine boot2docker root password
Haven't found an answer anywhere... I created a VM (boot2docker) using docker-machine. I need to edit some files using root.

What is the root password in boot2docker?

答:
Login via ssh as docker user:

```<code>$ ssh docker@<docker-machine-ip>
</code>```

Password: tcuser

Then you can change on root user, just run sudo su root

Body:
Login via ssh as docker user:

$ ssh docker@<docker-machine-ip>

Password: tcuser

Then you can change on root user, just run sudo su root