问:
XSLT - using or in xsl:apply-templates
We have incoming JSON data from Source which has data and column in same payload. Using json-to-xml in XSLT I was able to generate XML like following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
      <map key="T!T">
         <array key="rows">
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">1A</string>
                     <string key="value">1A</string>
                  </map>
                  <map>
                     <string key="label">1B</string>
                     <string key="value">1B</string>
                  </map>
                  <map>
                     <string key="label">1C</string>
                     <string key="value">1C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">2A</string>
                     <null key="value"/>
                  </map>
                  <map>
                     <string key="label">2B</string>
                     <string key="value">2B</string>
                  </map>
                  <map>
                     <string key="label">2C</string>
                     <string key="value">2C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">3A</string>
                     <string key="value">3A</string>
                  </map>
                  <map>
                     <string key="label">3B</string>
                     <string key="value">3B</string>
                  </map>
                  <map>
                     <string key="label">3C</string>
                     <string key="value">3C</string>
                  </map>
               </array>
            </map>
         </array>
      </map>
   </map>
   <map key="detailColumnInfo">
      <map key="Product_vod__c.F1">
         <string key="dataType">string</string>
         <string key="label">F1</string>
      </map>
      <map key="Product_vod__c.F2">
         <string key="dataType">string</string>
         <string key="label">F2</string>
      </map>
      <map key="Product_vod__c.F3">
         <string key="dataType">string</string>
         <string key="label">F3</string>
      </map>
   </map>
</map>
</code>```

Here each row is available under dataCells tag as label and value. Value under dataCells represents value of field however label does not represent field name. Field names and field order is part of detailColumnInfo tag. Order and number of fields/data in is not fixed however target XML shall remain fixed. E.g. incoming data can have 10 fields and data in any order however target XML shall have only 2 fields. To implement this, I believe, on run time we have to figure out the order of F1 field and have to pick corresponding data from dataCells. E.g. if F1 is field is first field in detailColumnInfo then I have to pick first value from all dataCells (1A, 2A, 3A)and generate target XML with value of F1 field and so on.

Detailcolumninfo tag represents the column details. Position of value field in Detailcolumninfo will determine the position of fields in Datacells. For input code snippet posted in query, if F1 is the 1st label in Detailcolumninfo then first value in Datacells (1A,2A,3A) represents the value of F1. Similarly 1B,2B,3B represents value of F2. Target XML should look like following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2>2B</F2>
         <F3>2C</F3>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>
</code>```

Thanks to following XSLT from Martin Honnen, output was achieved:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math fn"
    expand-text="yes"
    version="3.0">

    <xsl:param name="json-xml">
        <map xmlns="http://www.w3.org/2005/xpath-functions">
            <boolean key="allData">true</boolean>
            <map key="factMap">
                <map key="T!T">
                    <array key="rows">
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">1A</string>
                                    <string key="value">1A</string>
                                </map>
                                <map>
                                    <string key="label">1B</string>
                                    <string key="value">1B</string>
                                </map>
                                <map>
                                    <string key="label">1C</string>
                                    <string key="value">1C</string>
                                </map>
                            </array>
                        </map>
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">2A</string>
                                    <string key="value">2A</string>
                                </map>
                                <map>
                                    <string key="label">2B</string>
                                    <string key="value">2B</string>
                                </map>
                                <map>
                                    <string key="label">2C</string>
                                    <string key="value">2C</string>
                                </map>
                            </array>
                        </map>
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">3A</string>
                                    <string key="value">3A</string>
                                </map>
                                <map>
                                    <string key="label">3B</string>
                                    <string key="value">3B</string>
                                </map>
                                <map>
                                    <string key="label">3C</string>
                                    <string key="value">3C</string>
                                </map>
                            </array>
                        </map>
                    </array>
                </map>
            </map>
            <map key="detailColumnInfo">
                <map key="Product_vod__c.F1">
                    <string key="dataType">string</string>
                    <string key="label">F1</string>
                </map>
                <map key="Product_vod__c.F2">
                    <string key="dataType">string</string>
                    <string key="label">F2</string>
                </map>
                <map key="Product_vod__c.F3">
                    <string key="dataType">string</string>
                    <string key="label">F3</string>
                </map>
            </map>
        </map>
    </xsl:param>

    <xsl:variable name="label-names" as="xs:string*" select="$json-xml//fn:map[@key = 'detailColumnInfo']/fn:map/fn:string[@key = 'label']/string()"/>

    <xsl:output indent="yes"/>

    <xsl:template match="/" name="xsl:initial-template">
        <xsl:apply-templates select="$json-xml//fn:map[@key = 'factMap']"/>
    </xsl:template>

    <xsl:template match="fn:map[@key = 'factMap']">
        <Root>
            <Rows>
                <xsl:apply-templates select="$json-xml//fn:array[@key = 'rows']/fn:map/fn:array"/>
            </Rows>
        </Root>
    </xsl:template>

    <xsl:template match="fn:array[@key = 'rows']/fn:map/fn:array">
        <Row>
            <xsl:apply-templates select="fn:map/fn:string[@key = 'value']"/>
        </Row>
    </xsl:template>

    <xsl:template match="fn:string[@key = 'value']">
        <xsl:element name="{let $pos := position() return $label-names[$pos]}">{.}</xsl:element>
    </xsl:template>

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

Problem occurs as my source system is representing null in strange fashion. If field value is null then incoming data is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
      <map key="T!T">
         <array key="rows">
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">1A</string>
                     <string key="value">1A</string>
                  </map>
                  <map>
                     <string key="label">1B</string>
                     <string key="value">1B</string>
                  </map>
                  <map>
                     <string key="label">1C</string>
                     <string key="value">1C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">2A</string>
                     <string key="value">2A</string>

                  </map>
                  <map>
                     <string key="label">2B</string>
                     <null key="value"/>
                  </map>
                  <map>
                     <string key="label">2C</string>
                     <string key="value">2C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">3A</string>
                     <string key="value">3A</string>
                  </map>
                  <map>
                     <string key="label">3B</string>
                     <string key="value">3B</string>
                  </map>
                  <map>
                     <string key="label">3C</string>
                     <string key="value">3C</string>
                  </map>
               </array>
            </map>
         </array>
      </map>
   </map>
   <map key="detailColumnInfo">
      <map key="Product_vod__c.F1">
         <string key="dataType">string</string>
         <string key="label">F1</string>
      </map>
      <map key="Product_vod__c.F2">
         <string key="dataType">string</string>
         <string key="label">F2</string>
      </map>
      <map key="Product_vod__c.F3">
         <string key="dataType">string</string>
         <string key="label">F3</string>
      </map>
   </map>
</map>
</code>```

Script is scrambling values like following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2>2C</F2>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>
</code>```

In above example, value of F2 is null. In output F3 element disappears and value of F3 field jumps as the value of F2 field. Expected output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2/>
        <F3>2C</F3>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>
</code>```

As solution, I tried including null values in apply-templates by changing original statement from

```<code>    <xsl:apply-templates select="fn:map/fn:string[@key = 'value']"/>
</code>```

to

```<code><xsl:apply-templates select="fn:map/fn:string[@key = 'value'] | fn:map/fn:null[@key = 'value']"/>
</code>```

But changing this does not include     element <null key="value"/>.
I am new to XSLT and XPath and requires help in solving this.

答:
```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:fn="http://www.w3.org/2005/xpath-functions"
        xmlns:math="http://www.w3.org/2005/xpath-functions/math"
        exclude-result-prefixes="xs math fn"
        expand-text="yes"
        version="3.0">

        <xsl:param name="json-xml">
            <map xmlns="http://www.w3.org/2005/xpath-functions">
                <boolean key="allData">true</boolean>
                <map key="factMap">
                    <map key="T!T">
                        <array key="rows">
                            <map>
                                <array key="dataCells">
                                    <map>
                                        <string key="label">1A</string>
                                        <string key="value">1A</string>
                                    </map>
                                    <map>
                                        <string key="label">1B</string>
                                        <string key="value">1B</string>
                                    </map>
                                    <map>
                                        <string key="label">1C</string>
                                        <string key="value">1C</string>
                                    </map>
                                </array>
                            </map>
                            <map>
                                <array key="dataCells">
                                    <map>
                                        <string key="label">2A</string>
                                        <string key="value">2A</string>
                                    </map>
                                    <map>
                                        <string key="label">2B</string>
                                        <string key="value">2B</string>
                                    </map>
                                    <map>
                                        <string key="label">2C</string>
                                        <string key="value">2C</string>
                                    </map>
                                </array>
                            </map>
                            <map>
                                <array key="dataCells">
                                    <map>
                                        <string key="label">3A</string>
                                        <string key="value">3A</string>
                                    </map>
                                    <map>
                                        <string key="label">3B</string>
                                        <string key="value">3B</string>
                                    </map>
                                    <map>
                                        <string key="label">3C</string>
                                        <string key="value">3C</string>
                                    </map>
                                </array>
                            </map>
                        </array>
                    </map>
                </map>
                <map key="detailColumnInfo">
                    <map key="Product_vod__c.F1">
                        <string key="dataType">string</string>
                        <string key="label">F1</string>
                    </map>
                    <map key="Product_vod__c.F2">
                        <string key="dataType">string</string>
                        <string key="label">F2</string>
                    </map>
                    <map key="Product_vod__c.F3">
                        <string key="dataType">string</string>
                        <string key="label">F3</string>
                    </map>
                </map>
            </map>
        </xsl:param>

    <xsl:variable name="label-names" as="xs:string*" select="$json-xml//fn:map[@key = 'detailColumnInfo']/fn:map/fn:string  [@key = 'label']/translate(normalize-

space(string()),' ','')"/>
    <xsl:output indent="yes"/>

    <xsl:template match="/" name="xsl:initial-template">
        <xsl:apply-templates select="$json-xml//fn:map[@key = 'factMap']"/>
    </xsl:template>

    <xsl:template match="fn:map[@key = 'factMap']">
        <Root>
            <Rows>
                <xsl:apply-templates select="$json-xml//fn:array[@key = 'rows']/fn:map/fn:array"/>
            </Rows>
        </Root>
    </xsl:template>

    <xsl:template match="fn:array[@key = 'rows']/fn:map/fn:array">
        <Row>
            <xsl:apply-templates select="fn:map/fn:string[@key = 'value'] | fn:map/fn:null[@key = 'value']"/>
        </Row>
    </xsl:template>

<xsl:template match="fn:string[@key = 'value'] |fn:map/fn:null[@key = 'value']">

        <xsl:element name="{let $pos := position() return $label-names[$pos]}">{.}</xsl:element>
    </xsl:template>

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

Title: XSLT - using or in xsl:apply-templates

Body:
We have incoming JSON data from Source which has data and column in same payload. Using json-to-xml in XSLT I was able to generate XML like following:

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
      <map key="T!T">
         <array key="rows">
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">1A</string>
                     <string key="value">1A</string>
                  </map>
                  <map>
                     <string key="label">1B</string>
                     <string key="value">1B</string>
                  </map>
                  <map>
                     <string key="label">1C</string>
                     <string key="value">1C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">2A</string>
                     <null key="value"/>
                  </map>
                  <map>
                     <string key="label">2B</string>
                     <string key="value">2B</string>
                  </map>
                  <map>
                     <string key="label">2C</string>
                     <string key="value">2C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">3A</string>
                     <string key="value">3A</string>
                  </map>
                  <map>
                     <string key="label">3B</string>
                     <string key="value">3B</string>
                  </map>
                  <map>
                     <string key="label">3C</string>
                     <string key="value">3C</string>
                  </map>
               </array>
            </map>
         </array>
      </map>
   </map>
   <map key="detailColumnInfo">
      <map key="Product_vod__c.F1">
         <string key="dataType">string</string>
         <string key="label">F1</string>
      </map>
      <map key="Product_vod__c.F2">
         <string key="dataType">string</string>
         <string key="label">F2</string>
      </map>
      <map key="Product_vod__c.F3">
         <string key="dataType">string</string>
         <string key="label">F3</string>
      </map>
   </map>
</map>

Here each row is available under dataCells tag as label and value. Value under dataCells represents value of field however label does not represent field name. Field names and field order is part of detailColumnInfo tag. Order and number of fields/data in is not fixed however target XML shall remain fixed. E.g. incoming data can have 10 fields and data in any order however target XML shall have only 2 fields. To implement this, I believe, on run time we have to figure out the order of F1 field and have to pick corresponding data from dataCells. E.g. if F1 is field is first field in detailColumnInfo then I have to pick first value from all dataCells (1A, 2A, 3A)and generate target XML with value of F1 field and so on.

Detailcolumninfo tag represents the column details. Position of value field in Detailcolumninfo will determine the position of fields in Datacells. For input code snippet posted in query, if F1 is the 1st label in Detailcolumninfo then first value in Datacells (1A,2A,3A) represents the value of F1. Similarly 1B,2B,3B represents value of F2. Target XML should look like following:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2>2B</F2>
         <F3>2C</F3>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>

Thanks to following XSLT from Martin Honnen, output was achieved:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math fn"
    expand-text="yes"
    version="3.0">

    <xsl:param name="json-xml">
        <map xmlns="http://www.w3.org/2005/xpath-functions">
            <boolean key="allData">true</boolean>
            <map key="factMap">
                <map key="T!T">
                    <array key="rows">
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">1A</string>
                                    <string key="value">1A</string>
                                </map>
                                <map>
                                    <string key="label">1B</string>
                                    <string key="value">1B</string>
                                </map>
                                <map>
                                    <string key="label">1C</string>
                                    <string key="value">1C</string>
                                </map>
                            </array>
                        </map>
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">2A</string>
                                    <string key="value">2A</string>
                                </map>
                                <map>
                                    <string key="label">2B</string>
                                    <string key="value">2B</string>
                                </map>
                                <map>
                                    <string key="label">2C</string>
                                    <string key="value">2C</string>
                                </map>
                            </array>
                        </map>
                        <map>
                            <array key="dataCells">
                                <map>
                                    <string key="label">3A</string>
                                    <string key="value">3A</string>
                                </map>
                                <map>
                                    <string key="label">3B</string>
                                    <string key="value">3B</string>
                                </map>
                                <map>
                                    <string key="label">3C</string>
                                    <string key="value">3C</string>
                                </map>
                            </array>
                        </map>
                    </array>
                </map>
            </map>
            <map key="detailColumnInfo">
                <map key="Product_vod__c.F1">
                    <string key="dataType">string</string>
                    <string key="label">F1</string>
                </map>
                <map key="Product_vod__c.F2">
                    <string key="dataType">string</string>
                    <string key="label">F2</string>
                </map>
                <map key="Product_vod__c.F3">
                    <string key="dataType">string</string>
                    <string key="label">F3</string>
                </map>
            </map>
        </map>
    </xsl:param>

    <xsl:variable name="label-names" as="xs:string*" select="$json-xml//fn:map[@key = 'detailColumnInfo']/fn:map/fn:string[@key = 'label']/string()"/>

    <xsl:output indent="yes"/>

    <xsl:template match="/" name="xsl:initial-template">
        <xsl:apply-templates select="$json-xml//fn:map[@key = 'factMap']"/>
    </xsl:template>

    <xsl:template match="fn:map[@key = 'factMap']">
        <Root>
            <Rows>
                <xsl:apply-templates select="$json-xml//fn:array[@key = 'rows']/fn:map/fn:array"/>
            </Rows>
        </Root>
    </xsl:template>

    <xsl:template match="fn:array[@key = 'rows']/fn:map/fn:array">
        <Row>
            <xsl:apply-templates select="fn:map/fn:string[@key = 'value']"/>
        </Row>
    </xsl:template>

    <xsl:template match="fn:string[@key = 'value']">
        <xsl:element name="{let $pos := position() return $label-names[$pos]}">{.}</xsl:element>
    </xsl:template>

</xsl:stylesheet>

Problem occurs as my source system is representing null in strange fashion. If field value is null then incoming data is:

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
      <map key="T!T">
         <array key="rows">
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">1A</string>
                     <string key="value">1A</string>
                  </map>
                  <map>
                     <string key="label">1B</string>
                     <string key="value">1B</string>
                  </map>
                  <map>
                     <string key="label">1C</string>
                     <string key="value">1C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">2A</string>
                     <string key="value">2A</string>

                  </map>
                  <map>
                     <string key="label">2B</string>
                     <null key="value"/>
                  </map>
                  <map>
                     <string key="label">2C</string>
                     <string key="value">2C</string>
                  </map>
               </array>
            </map>
            <map>
               <array key="dataCells">
                  <map>
                     <string key="label">3A</string>
                     <string key="value">3A</string>
                  </map>
                  <map>
                     <string key="label">3B</string>
                     <string key="value">3B</string>
                  </map>
                  <map>
                     <string key="label">3C</string>
                     <string key="value">3C</string>
                  </map>
               </array>
            </map>
         </array>
      </map>
   </map>
   <map key="detailColumnInfo">
      <map key="Product_vod__c.F1">
         <string key="dataType">string</string>
         <string key="label">F1</string>
      </map>
      <map key="Product_vod__c.F2">
         <string key="dataType">string</string>
         <string key="label">F2</string>
      </map>
      <map key="Product_vod__c.F3">
         <string key="dataType">string</string>
         <string key="label">F3</string>
      </map>
   </map>
</map>

Script is scrambling values like following:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2>2C</F2>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>

In above example, value of F2 is null. In output F3 element disappears and value of F3 field jumps as the value of F2 field. Expected output is:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
   <Rows>
      <Row>
         <F1>1A</F1>
         <F2>1B</F2>
         <F3>1C</F3>
      </Row>
      <Row>
         <F1>2A</F1>
         <F2/>
        <F3>2C</F3>
      </Row>
      <Row>
         <F1>3A</F1>
         <F2>3B</F2>
         <F3>3C</F3>
      </Row>
   </Rows>
</Root>

As solution, I tried including null values in apply-templates by changing original statement from

    <xsl:apply-templates select="fn:map/fn:string[@key = 'value']"/>

to

<xsl:apply-templates select="fn:map/fn:string[@key = 'value'] | fn:map/fn:null[@key = 'value']"/>

But changing this does not include     element <null key="value"/>.
I am new to XSLT and XPath and requires help in solving this.


来源: stackexchange

问:
diff comparison operation in moment.js
This is Duplicate of this question. I don't know how to compare the diff. For example if the diff equal to greater than 14 days then the text box should be red. if 7 to 13 days it would be yellow and below 6 days it would be green.

code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}</code>```

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

```

答: This is not a valid condition: else if(7 < diff =< 9), it shoud be else if(diff > 7 && diff <= 9)

ContentLicense: CC BY-SA 3.0

Title: diff comparison operation in moment.js

Body:
This is Duplicate of this question. I don't know how to compare the diff. For example if the diff equal to greater than 14 days then the text box should be red. if 7 to 13 days it would be yellow and below 6 days it would be green.

code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });

.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>


问:
Match route only if query param exists
I want to match this route if url is /test?x=5 and don't match if param x is not provided (/test):

```<code>stateProvider.state({
    name: 'someState',
    url: '/test?x',
    template: '<div>matched</div>'
});
</code>```

This configuration does not work, route is matched in both cases. I need required query param.

I was expecting clean solution like this:

```<code>stateProvider.state({
    name: 'someState',
    url: '/test',
    params: {
        x: {
            required: true
        }
    },
    template: '<div>matched</div>'
});
</code>```

答:
You could write resolve on the current route and from that resolve function whether the parameter is exists or not

```<code>stateProvider.state({
    name: 'someState',
    url: '/test?x',
    template: '<div>matched</div>',
    resolve: {
      xExists: ['$stateParams', '$state',
         function($stateParams, $state){
            if(!$stateParams.x) $state.go('someotherstate');
         }
      ]
    }
});
</code>```

Other better solution would be changing the route pattern to /test/:x which will make your pattern unique. If it doesn't match the route pattern, ui-router will take care of navigating to default route(if you have configured it with $urlRouter.otherwise).

```<code>url: '/test/:x',
</code>```

Title: Match route only if query param exists

Body:
I want to match this route if url is /test?x=5 and don't match if param x is not provided (/test):

stateProvider.state({
    name: 'someState',
    url: '/test?x',
    template: '
matched
'
});

This configuration does not work, route is matched in both cases. I need required query param.

I was expecting clean solution like this:

stateProvider.state({
    name: 'someState',
    url: '/test',
    params: {
        x: {
            required: true
        }
    },
    template: '
matched
'
});

Body:
You could write resolve on the current route and from that resolve function whether the parameter is exists or not

stateProvider.state({
    name: 'someState',
    url: '/test?x',
    template: '<div>matched</div>',
    resolve: {
      xExists: ['$stateParams', '$state',
         function($stateParams, $state){
            if(!$stateParams.x) $state.go('someotherstate');
         }
      ]
    }
});

Other better solution would be changing the route pattern to /test/:x which will make your pattern unique. If it doesn't match the route pattern, ui-router will take care of navigating to default route(if you have configured it with $urlRouter.otherwise).

url: '/test/:x',


问:
oracle db exception when start jar as service
In my program I have connection to oracle DB:

```<code>public static Connection getConnection() throws SQLException {
    String dbURL = "jdbc:oracle:oci:<username>/<password>@TNS_NAME";
    return DriverManager.getConnection(dbURL);
}
</code>```

When I start jar file on linux using "java -jar myprog.jar" - all works correctly

When I start it as service, using service wrapper (Run a Java Application as a Service on Linux)
it fails with exception:

java.lang.UnsatisfiedLinkError: no ocijdbc12 in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)

The same error I see, when I start it using sudo: "sudo java -jar myprog.jar"

LD_LIBRARY_PATH = /usr/lib/oracle/12.2/client64/lib

OS - CentOS; java version - 1.8; oracle version - 12.2

答:
Problem was, that some ENV paths not available from "sudo" or "nohup".

Solution is add env to command, like this:

nohup env "LD_LIBRARY_PATH=/usr/lib/oracle/12.2/client64/lib" "ORACLE_HOME=/usr/lib/oracle/12.2/client64" "TNS_ADMIN=/usr/lib/oracle/12.2/client64/network/admin" java -jar $PATH_TO_JAR

Body:
In my program I have connection to oracle DB:

public static Connection getConnection() throws SQLException {
    String dbURL = "jdbc:oracle:oci:<username>/<password>@TNS_NAME";
    return DriverManager.getConnection(dbURL);
}

When I start jar file on linux using "java -jar myprog.jar" - all works correctly

When I start it as service, using service wrapper (Run a Java Application as a Service on Linux)
it fails with exception:

java.lang.UnsatisfiedLinkError: no ocijdbc12 in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)

The same error I see, when I start it using sudo: "sudo java -jar myprog.jar"

LD_LIBRARY_PATH = /usr/lib/oracle/12.2/client64/lib

OS - CentOS; java version - 1.8; oracle version - 12.2


问:
Stack array of structures
I'm trying to figure our how implement an array of structures into stacks in this machine problem that i have. Here is the problem:

Make a program that will allow the user to perform the following activities stated below through array approach.  Car Park Station offers 10 park lanes and each lanes can accommodate 5 cars.

a. Entry.  It must be able to register new car and assign an available parking lane.  Registration requires plate number, brand name, car color, owner and telephone number.

b. Release.  It must be able to release car from an identified lane

c. Search.  It must be able to identify the car location based on plate number.

d. Vacancy. It must be able to display available parking space.

From what i understand, i have to make a 2 dimensional array of structures containing various data types and i have to make a lifo code out of it. But my problem is, i know how to simulate an array approach lifo code with just a single data type but not with multiple data types. The part where i have to implement the 2 dimensional array of structure into a stack is where i got me stuck and confused. I've searched online to look for problems similar to mine but i couldn't find any. I tried to make a code shown below:

```<code>struct Car
{
    string brand, color, owner;
    int plate, phone;
};

class Stack
{
private:
    Car * pointer = new Car[10][5];
    int top;
public:
    Stack() // Constructor
    {...}

    void Push(int plate, string brand, string color, string color, string owner, int number)
    {...}

    Pop()
    {...}

}
</code>```

答:
Try to analyze your problem further before choosing an actual implementation solution (like 2-dim array).

In your task you have the following abstract entities:

CarParkStation with attributes: NumberOfParkLanes, which should be able to do something like: FindFreeLane, FindCar(plateNum), RegisterACar(car), ReleaseACar(car)

Lane with attributes: NumberOfPlaces, and with actions like: IsFull(), and maybe also: FindACar(plateNum), AddACar(car), RemoveACar(car)

Car with attributes: PlateNumber, Brand, Color, Owner, which should be able to do: GetPlateNumber(), and maybe also provide access to other parameters

Below is a very general example of possible CarParkStation class declaration:

```<code>class CarParkStation
{
public:
    CarParkStation() = delete;
    explicit CarParkStation(int numParkLanes);
    ~CarParkStation() = default;

    std::shared_ptr<const Lane> FindFreeLane();
    std::shared_ptr<const Car> FindCar(const PlateNumber& pNumber);
    std::pair<std::shared_ptr<const Lane>, int position> FindWhereMyCarIsParked(const PlateNumber& pNumber);
    bool RegisterACar(const Car& car);
    bool ReleaseACar(const Car& car);

private:
    std::vector<std::shared_ptr<const Lane> > lanes_;
    std::set<std::shared_ptr<Car>, CustomCompareFunction > cars_;
};
</code>```

Don't forget to write the tests along with your implementation. This will help you to verify your requirements and overall design. For example:

```<code>TEST_F(CarParkStationShould, returnCorrectFreeLane)
{
    ASSERT_EQ(expectedFreeLane, carParkStation->FindFreeLane());
}
</code>```

In general, focus on what should your application do first, and then think about how to implement it.

Title: Stack array of structures

Body:
I'm trying to figure our how implement an array of structures into stacks in this machine problem that i have. Here is the problem:

Make a program that will allow the user to perform the following activities stated below through array approach.  Car Park Station offers 10 park lanes and each lanes can accommodate 5 cars.

a. Entry.  It must be able to register new car and assign an available parking lane.  Registration requires plate number, brand name, car color, owner and telephone number.

b. Release.  It must be able to release car from an identified lane

c. Search.  It must be able to identify the car location based on plate number.

d. Vacancy. It must be able to display available parking space.

From what i understand, i have to make a 2 dimensional array of structures containing various data types and i have to make a lifo code out of it. But my problem is, i know how to simulate an array approach lifo code with just a single data type but not with multiple data types. The part where i have to implement the 2 dimensional array of structure into a stack is where i got me stuck and confused. I've searched online to look for problems similar to mine but i couldn't find any. I tried to make a code shown below:

struct Car
{
    string brand, color, owner;
    int plate, phone;
};

class Stack
{
private:
    Car * pointer = new Car[10][5];
    int top;
public:
    Stack() // Constructor
    {...}

    void Push(int plate, string brand, string color, string color, string owner, int number)
    {...}

    Pop()
    {...}

}

Body:
Try to analyze your problem further before choosing an actual implementation solution (like 2-dim array).

In your task you have the following abstract entities:

CarParkStation with attributes: NumberOfParkLanes, which should be able to do something like: FindFreeLane, FindCar(plateNum), RegisterACar(car), ReleaseACar(car)

Lane with attributes: NumberOfPlaces, and with actions like: IsFull(), and maybe also: FindACar(plateNum), AddACar(car), RemoveACar(car)

Car with attributes: PlateNumber, Brand, Color, Owner, which should be able to do: GetPlateNumber(), and maybe also provide access to other parameters

Below is a very general example of possible CarParkStation class declaration:

class CarParkStation
{
public:
    CarParkStation() = delete;
    explicit CarParkStation(int numParkLanes);
    ~CarParkStation() = default;

    std::shared_ptr<const Lane> FindFreeLane();
    std::shared_ptr<const Car> FindCar(const PlateNumber& pNumber);
    std::pair<std::shared_ptr<const Lane>, int position> FindWhereMyCarIsParked(const PlateNumber& pNumber);
    bool RegisterACar(const Car& car);
    bool ReleaseACar(const Car& car);

private:
    std::vector<std::shared_ptr<const Lane> > lanes_;
    std::set<std::shared_ptr<Car>, CustomCompareFunction > cars_;
};

Don't forget to write the tests along with your implementation. This will help you to verify your requirements and overall design. For example:

TEST_F(CarParkStationShould, returnCorrectFreeLane)
{
    ASSERT_EQ(expectedFreeLane, carParkStation->FindFreeLane());
}

In general, focus on what should your application do first, and then think about how to implement it.


问:
How to update after "php bin/console security:check"
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

```
/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)
```

答:
NicoHaase mentioned the anwser I'd say: https://github.com/akeneo/pim-community-dev/issues/7146#issuecomment-344206254

No one should edit composer.lock. Just read the bug report linked in
  my former comment: the maintainers of Akeneo know about these outdated
  packages and plan to fix them anytime in the future

The bug report https://github.com/akeneo/pim-community-dev/issues/5233 was created on 17 Nov 2016, but unfortunately still nothing. Devs said to wait.

Body:
Symfony write on how to check for security updates: https://symfony.com/doc/current/security/security_checker.html and it works, in Akeneo it shows me one vulnerability.
But how to update? I tried ../composer.phar update and ../composer.phar update symfony/symfony but unfortunately the vulnerability is still there when I check again. (https://github.com/akeneo/pim-community-dev/issues/7146)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why dompdf/dompdf:0.6.1
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)

/var/www/html/akeneo/pim-community-standard# ../composer.phar why-not dompdf/dompdf:0.6.2
Do not run Composer as root/super user! See https://getcomposer.org/root for details
akeneo/pim-community-dev  v2.0.6  requires  dompdf/dompdf (0.6.1)


问:
validateDOMNesting warning React
I have a React component that is clickable as a whole, but also contains buttons inside.

So something like

```<code><Link to={'/path1'}>
  ...
  <Link to={'path2'} />
  ...
</Link>
</code>```

This is the behaviour I want, but I get this warning:

```<code>Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>. See SearchResult > Link > a > ... > Link > a.
</code>```

How seriously should I take this and what would be the workaround?

答:
Nesting anchor tags (which is what <Link /> transpiles to) is forbidden in HTML. Even if you get the desired result, it is only because your browser is clever and has its own work-arounds. However, that behavior cannot be guaranteed across all browsers and platforms.

How seriously should I take this?

As per the above, I'd say quite seriously.

What would be the workaround?

The following isn't a workaround, but what I consider to be the "proper" implementation.

I'd programatically implement the navigation for the wrapping element and use the <Link /> for the buttons. So something like:

navigate = () => {
  //push "path1" to history
}

render() {
  return(

      <Link to="path2">Some button</Link>
      <Link to="path3">Some button</Link>

  );
}
```

For more info about programatically navigating in React Router see one of the links below:

For React Router v1-v3: Link

For React Router v4: Link

Title: validateDOMNesting warning React

Body:
I have a React component that is clickable as a whole, but also contains buttons inside.

So something like

<Link to={'/path1'}>
  ...
  <Link to={'path2'} />
  ...
</Link>

This is the behaviour I want, but I get this warning:

Warning: validateDOMNesting(...):  cannot appear as a descendant of . See SearchResult > Link > a > ... > Link > a.

How seriously should I take this and what would be the workaround?

Body:
Nesting anchor tags (which is what <Link /> transpiles to) is forbidden in HTML. Even if you get the desired result, it is only because your browser is clever and has its own work-arounds. However, that behavior cannot be guaranteed across all browsers and platforms.

How seriously should I take this?

As per the above, I'd say quite seriously.

What would be the workaround?

The following isn't a workaround, but what I consider to be the "proper" implementation.

I'd programatically implement the navigation for the wrapping element and use the <Link /> for the buttons. So something like:

navigate = () => {
  //push "path1" to history
}

render() {
  return(
    <div onClick={this.navigate}>
      <Link to="path2">Some button</Link>
      <Link to="path3">Some button</Link>
    </div>
  );
}

For more info about programatically navigating in React Router see one of the links below:

For React Router v1-v3: Link

For React Router v4: Link


问:
VBA prevent closing of UserForm with "End" in code
In my spreadsheet, I have a UserForm that is supposed to be open at all times.

Once in a while, my code will contain an "End" where I exit the code based on some if statement.

The problem is that this closes the UserForm, is there a way to prevent this from happening?

EDIT:

```<code>Sub Test1()
    'Random code
    Call Test2(Variable)
    'Random code
End Sub

Sub Test2(ByVal Variable as Double)
    If Variable = 0 then
        'Random code
    End If
    If Variable = 1 then
        Call Test3
        End 'Original placement of End
    End If
End Sub

Sub Test3()
    'Random code
End Sub
</code>```

This is a rough example of how the code is build (its rather long at this point). So depending on the "variable" different things happen in Test2. But if the Variable is 1, then the "random code" back in Test1 can't be executed thus, so I have to stop the code. I tried replace "End" with "Exit Sub" this only stops the code in Test2 from running, is it will give me an error when it goes back to Test1.

EDIT2:
Test1() is actually four different subs (at this point, more will be added) that all call Test2(). That is why I choose to split it up into so many subs and call them from within the subs.

答:
No, not if you insist on using End. This will essentially have the same effect as clicking the "Stop" button in the developer window. You should (most likely) not be using End. I cannot tell you what you should be using, since I do not know what you are trying to achieve.

Update:

Based on your code, I don't see any reason for Test3() to be nested within Test2(), since it runs either the random code or Test3() (never both). Is there anything preventing you from splitting all the different cases into different subs, and then doing the If statement in the main sub?

```<code>Sub Main()
    If Variable = 0 Then
        'Random code from before Test2()
        'Random code from Test2()
        'Random code from after Test2()

    ElseIf Variable = 1 Then
        Call Test3()

    Else
        MsgBox "Variable must be 0 or 1!"

End Sub
</code>```

Body:
In my spreadsheet, I have a UserForm that is supposed to be open at all times.

Once in a while, my code will contain an "End" where I exit the code based on some if statement.

The problem is that this closes the UserForm, is there a way to prevent this from happening?

EDIT:

Sub Test1()
    'Random code
    Call Test2(Variable)
    'Random code
End Sub

Sub Test2(ByVal Variable as Double)
    If Variable = 0 then
        'Random code
    End If
    If Variable = 1 then
        Call Test3
        End 'Original placement of End
    End If
End Sub

Sub Test3()
    'Random code
End Sub

This is a rough example of how the code is build (its rather long at this point). So depending on the "variable" different things happen in Test2. But if the Variable is 1, then the "random code" back in Test1 can't be executed thus, so I have to stop the code. I tried replace "End" with "Exit Sub" this only stops the code in Test2 from running, is it will give me an error when it goes back to Test1.

EDIT2:
Test1() is actually four different subs (at this point, more will be added) that all call Test2(). That is why I choose to split it up into so many subs and call them from within the subs.

Body:
No, not if you insist on using End. This will essentially have the same effect as clicking the "Stop" button in the developer window. You should (most likely) not be using End. I cannot tell you what you should be using, since I do not know what you are trying to achieve.

Update:

Based on your code, I don't see any reason for Test3() to be nested within Test2(), since it runs either the random code or Test3() (never both). Is there anything preventing you from splitting all the different cases into different subs, and then doing the If statement in the main sub?

Sub Main()
    If Variable = 0 Then
        'Random code from before Test2()
        'Random code from Test2()
        'Random code from after Test2()

    ElseIf Variable = 1 Then
        Call Test3()

    Else
        MsgBox "Variable must be 0 or 1!"

End Sub


问:
how to capture Build Info using Gradle and Spring Boot
I am trying to get access to build info values such as version in my Java main application using Spring Boot and Gradle.

I can't find any documentation / examples of how to configure the

build.gradle

application.yml (if required)

Java main class

could someone please help with a small code example for the above files.

In my build.gradle file I will have the version entry, so how to get this into Java main class using Spring Boot and Gradle.

build.gradle

```<code>version=0.0.1-SNAPSHOT
</code>```

I've tried adding

build.gradle

```<code>apply plugin: 'org.springframework.boot'

springBoot {
    buildInfo()
}
</code>```

but the buildInfo() isn't recognised as a keyword in Intellij

In my Java main class I have the following:

```<code>public class MyExampleApplication implements CommandLineRunner {
    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(MyExampleApplication.class, args);
    }

    @Override
    public void run(String[] args) throws Exception{
        Environment env = (Environment) context.getBean("environment");
        displayInfo(env);
    }

    private static void displayInfo(Environment env) {
       log.info("build version is <" + env.getProperty("version")
    }
</code>```

But when I run this - the output from env.getProperty("version") is showing as null.

答:
add following to your Gradle script.It inserts the version into the jar manifest correctly, as shown here:

```<code>version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}
</code>```

Your code will be able to pick up the version from that jar manifest file:

```<code>public class BuildVersion {
    public static String getBuildVersion(){
        return BuildVersion.class.getPackage().getImplementationVersion();
    }
}
</code>```

Refer the link below for more details: https://github.com/akhikhl/wuff/wiki/Manifest-attributes-in-build.gradle

Body:
I am trying to get access to build info values such as version in my Java main application using Spring Boot and Gradle.

I can't find any documentation / examples of how to configure the

build.gradle

application.yml (if required)

Java main class

could someone please help with a small code example for the above files.

In my build.gradle file I will have the version entry, so how to get this into Java main class using Spring Boot and Gradle.

build.gradle

version=0.0.1-SNAPSHOT

I've tried adding

build.gradle

apply plugin: 'org.springframework.boot'

springBoot {
    buildInfo()
}

but the buildInfo() isn't recognised as a keyword in Intellij

In my Java main class I have the following:

public class MyExampleApplication implements CommandLineRunner {
    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(MyExampleApplication.class, args);
    }

    @Override
    public void run(String[] args) throws Exception{
        Environment env = (Environment) context.getBean("environment");
        displayInfo(env);
    }

    private static void displayInfo(Environment env) {
       log.info("build version is <" + env.getProperty("version")
    }

But when I run this - the output from env.getProperty("version") is showing as null.

Body:
add following to your Gradle script.It inserts the version into the jar manifest correctly, as shown here:

version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}

Your code will be able to pick up the version from that jar manifest file:

public class BuildVersion {
    public static String getBuildVersion(){
        return BuildVersion.class.getPackage().getImplementationVersion();
    }
}

Refer the link below for more details: https://github.com/akhikhl/wuff/wiki/Manifest-attributes-in-build.gradle


问:
How does Order by affect assignment when used along with COALESCE
I have a T-SQL variable to which I am assigning a value using SELECT operation. Since the "SELECT" query might return multiple rows therefore I am using COALESCE function which appends all the values separated by a comma. So far all good and query is behaving as intended. But when I try to order my values using order by clause only one row is appended to variable.

Why adding Order By clause in Query 2 produces so different result then Query 1?

[Results 1]:

Ball 1,Ball 2,Bat 3,Bat 1,Bat 2

[Results 2]:

Bat 1

JS Fiddle link : http://sqlfiddle.com/#!6/8dad1/15

[SQL Fiddle][1]

MS SQL Server 2014 Schema Setup:

```<code>CREATE TABLE tbl_Trans
([Id] int, [Instrument] varchar(20), [Trans_Type] int, [Quantity] int);

CREATE TABLE tbl_Trans_Type
([Id] int, [Trans_Type] varchar(20));

INSERT INTO tbl_Trans  ([Id], [Instrument], [Trans_Type], [Quantity])

VALUES
(1,'Ball 1', 121, 50),
(2,'Ball 2', 121, 20),
(3,'Bat 3', 122, 1000),
(4,'Bat 1', 124, 400),
(5,'Bat 2', 121, 300);

INSERT INTO tbl_Trans_Type  ([Id], [Trans_Type])

VALUES
(121,'Buy'),
(122,'Sell'),
(123,'ReSell'),
(124,'Rent')

**Query 1**:

DECLARE @ST VARCHAR(500) = NULL
SELECT @ST = COALESCE(@ST+ ',' , '')+Instrument
FROM tbl_Trans a
LEFT JOIN tbl_Trans_Type b on a.Trans_Type = b.Id

SELECT @ST
</code>```

[Results 1]:

```<code>| Ball 1,Ball 2,Bat 3,Bat 1,Bat 2 |
</code>```

Query 2:

```<code>DECLARE @ST2 VARCHAR(500) = NULL
SELECT  @ST2 = COALESCE(@ST2+ ',' , '')+Instrument
FROM tbl_Trans a
LEFT JOIN tbl_Trans_Type b on a.Trans_Type = b.Id
ORDER BY IIF(b.Trans_Type='Buy',1,2)

SELECT  @ST2
</code>```

[Results 2]:

```<code>| Bat 1 |
</code>```

答:
Try this if you want to concatenate but with ordering:</p>

```<code>SELECT STUFF
(
    (
        SELECT ',' +Instrument
        FROM tbl_Trans a
        LEFT JOIN tbl_Trans_Type b
            on a.Trans_Type = b.Id
        ORDER BY IIF(b.Trans_Type='Buy',1,2)
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)')
    ,1
    ,1
    ,''
);
</code>```

Body:
I have a T-SQL variable to which I am assigning a value using SELECT operation. Since the "SELECT" query might return multiple rows therefore I am using COALESCE function which appends all the values separated by a comma. So far all good and query is behaving as intended. But when I try to order my values using order by clause only one row is appended to variable.

Why adding Order By clause in Query 2 produces so different result then Query 1?

[Results 1]:

Ball 1,Ball 2,Bat 3,Bat 1,Bat 2

[Results 2]:

Bat 1

JS Fiddle link : http://sqlfiddle.com/#!6/8dad1/15

[SQL Fiddle][1]

MS SQL Server 2014 Schema Setup:

CREATE TABLE tbl_Trans
([Id] int, [Instrument] varchar(20), [Trans_Type] int, [Quantity] int);

CREATE TABLE tbl_Trans_Type
([Id] int, [Trans_Type] varchar(20));

INSERT INTO tbl_Trans  ([Id], [Instrument], [Trans_Type], [Quantity])

VALUES
(1,'Ball 1', 121, 50),
(2,'Ball 2', 121, 20),
(3,'Bat 3', 122, 1000),
(4,'Bat 1', 124, 400),
(5,'Bat 2', 121, 300);

INSERT INTO tbl_Trans_Type  ([Id], [Trans_Type])

VALUES
(121,'Buy'),
(122,'Sell'),
(123,'ReSell'),
(124,'Rent')

**Query 1**:

DECLARE @ST VARCHAR(500) = NULL
SELECT @ST = COALESCE(@ST+ ',' , '')+Instrument
FROM tbl_Trans a
LEFT JOIN tbl_Trans_Type b on a.Trans_Type = b.Id

SELECT @ST

[Results 1]:

| Ball 1,Ball 2,Bat 3,Bat 1,Bat 2 |

Query 2:

DECLARE @ST2 VARCHAR(500) = NULL
SELECT  @ST2 = COALESCE(@ST2+ ',' , '')+Instrument
FROM tbl_Trans a
LEFT JOIN tbl_Trans_Type b on a.Trans_Type = b.Id
ORDER BY IIF(b.Trans_Type='Buy',1,2)

SELECT  @ST2

[Results 2]:

| Bat 1 |

Body:
Try this if you want to concatenate but with ordering:

SELECT STUFF
(
    (
        SELECT ',' +Instrument
        FROM tbl_Trans a
        LEFT JOIN tbl_Trans_Type b
            on a.Trans_Type = b.Id
        ORDER BY IIF(b.Trans_Type='Buy',1,2)
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)')
    ,1
    ,1
    ,''
);


问:
Consider the following code
```<code>import sys
n = input()
a = []
for i in range(n):
    temp = input()
    a[i].append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]
</code>```

code is running without any error but is giving error after the input

```<code>2
2 2
Traceback (most recent call last):
  File "1.py", line 5, in ?
    temp = input()
  File "<string>", line 1
    2 2
     ^
SyntaxError: unexpected EOF while parsing
</code>```

why is it not working and giving EOF error?

答:
I think you have to remove [i] from a[i].append(temp)

```<code>import sys
n = input('Please input n: ')
a = []
for i in range(n):
    temp = input('Please input temp: ')
    a.append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] == 0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]
</code>```

and result is:

```<code>Please input n: 5
Please input temp: 1
Please input temp: 2
Please input temp: 3
Please input temp: 4
Please input temp: 5
NO
YES
0
2
3
4
5
</code>```

if I understand correctly your task.

Title: Consider the following code

Body:
import sys
n = input()
a = []
for i in range(n):
    temp = input()
    a[i].append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]

code is running without any error but is giving error after the input

2
2 2
Traceback (most recent call last):
  File "1.py", line 5, in ?
    temp = input()
  File "<string>", line 1
    2 2
     ^
SyntaxError: unexpected EOF while parsing

why is it not working and giving EOF error?

Body:
I think you have to remove [i] from a[i].append(temp)

import sys
n = input('Please input n: ')
a = []
for i in range(n):
    temp = input('Please input temp: ')
    a.append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] == 0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]

and result is:

Please input n: 5
Please input temp: 1
Please input temp: 2
Please input temp: 3
Please input temp: 4
Please input temp: 5
NO
YES
0
2
3
4
5

if I understand correctly your task.


问:
If statement operator as a variable in ruby
I am trying to do something like this in ruby:

```<code>x = 0
y = 1
z = "!="

if x #{z} y
  puts "True"
end
#True
#=> nil

x = 1
if x #{z} y
  puts "True"
end
#True
#=> nil
</code>```

Using a operator as a variable is not evaluating the expression. Any way to do this.

答:
To reiterate the answer above, I'd suggest using send.

However, it is possible to write the code in your original style - you just need to eval (i.e. execute) it:

```<code>x = 0
y = 1
z = "!="

if eval("x #{z} y")
  puts "True"
end
</code>```

Generally speaking, the use of eval is strongly discouraged. It can lead to major security issues (e.g. if you're evaluating arbitrary user input!), and is quite a slow operation.

Body:
I am trying to do something like this in ruby:

x = 0
y = 1
z = "!="

if x #{z} y
  puts "True"
end
#True
#=> nil

x = 1
if x #{z} y
  puts "True"
end
#True
#=> nil

Using a operator as a variable is not evaluating the expression. Any way to do this.

Body:
To reiterate the answer above, I'd suggest using send.

However, it is possible to write the code in your original style - you just need to eval (i.e. execute) it:

x = 0
y = 1
z = "!="

if eval("x #{z} y")
  puts "True"
end

Generally speaking, the use of eval is strongly discouraged. It can lead to major security issues (e.g. if you're evaluating arbitrary user input!), and is quite a slow operation.


问:
Clearing a subplot in Matplotlib
I have a number of subplots in a figure fig1, created via

```<code>ax = fig1.add_subplot(221)
</code>```

I then plot stuff in each of the subplots via

```<code>im=ax.plot(x,y)
</code>```

and add some axis labels via

```<code>ax.set_xlabel('xlabel')
</code>```

I would then like to clear a specific subplot completely, as described in When to use cla(), clf() or close() for clearing a plot in matplotlib?. However the problem is that ax.cla()and ax.clear() seem to only clear the data from the plot, without removing the axes, axis tick labels etc. On the other hand plt.clf() clears the entire figure. Is there something in between? A clf-like command that clears everything in a subplot, including axis labels? Or have I simply used the commands in a wrong way?

答:
ax.clear() clears the axes. That is, it removes all settings and data from the axes such that you are left with an axes, just as it had been just created.

ax.axis("off") turns the axes off, such that all axes spines and ticklabels are hidden.

ax.set_visible(False) turns the complete axes invisible, including the data that is in it.

ax.remove() removes the axes from the figure.

Complete example:

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

fig,axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot([2,3,1])

axes[0,1].clear()
axes[1,0].axis("off")
axes[1,1].set_visible(False)
axes[0,2].remove()

plt.show()
</code>```

Title: Clearing a subplot in Matplotlib

Body:
I have a number of subplots in a figure fig1, created via

ax = fig1.add_subplot(221)

I then plot stuff in each of the subplots via

im=ax.plot(x,y)

and add some axis labels via

ax.set_xlabel('xlabel')

I would then like to clear a specific subplot completely, as described in When to use cla(), clf() or close() for clearing a plot in matplotlib?. However the problem is that ax.cla()and ax.clear() seem to only clear the data from the plot, without removing the axes, axis tick labels etc. On the other hand plt.clf() clears the entire figure. Is there something in between? A clf-like command that clears everything in a subplot, including axis labels? Or have I simply used the commands in a wrong way?

Body:
ax.clear() clears the axes. That is, it removes all settings and data from the axes such that you are left with an axes, just as it had been just created.

ax.axis("off") turns the axes off, such that all axes spines and ticklabels are hidden.

ax.set_visible(False) turns the complete axes invisible, including the data that is in it.

ax.remove() removes the axes from the figure.

Complete example:

import matplotlib.pyplot as plt

fig,axes = plt.subplots(2,3)
for ax in axes.flat:
    ax.plot([2,3,1])

axes[0,1].clear()
axes[1,0].axis("off")
axes[1,1].set_visible(False)
axes[0,2].remove()

plt.show()


问:
You have requested a non-existent service "Users_Users". Symfony3
When I try to access at my service, got this error :

You have requested a non-existent service "Users_Users".

But the namespace, the name of the class, name of the file, name of folder is ok. I have already copy paste the name to be sure.

Controller ->

```<code><?php

namespace UsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use UsersBundle\Form\UsersForm;
use Symfony\Component\HttpFoundation\Request;

class UsersController extends Controller
{
    public function UsersAction($Id)
    {
        $Users = $this->container->get('Users_Users')->ListeUsers($Id);
        return $this->render('UsersBundle:Users:users.html.twig', array('Users' => $Users));
    }
</code>```

Service :

```<code><?php

namespace UsersBundle\Services;

class Users
{
    public function __construct($ldap,$Core_ConnexionsBDD,$MySql_ConnexionsBDD, $session)
    {
        $this->ldap = $ldap;
        $this->Core_ConnexionsBDD = $Core_ConnexionsBDD;
        $this->MySql_ConnexionsBDD = $MySql_ConnexionsBDD;
        $this->session = $session;
    }

    public function ListeUsers($Id)
    {
        $lists = $this->MySql_ConnexionsBDD->getUsers();
        return $lists->Liste($Id);
    }

}
</code>```

Un the service file, no problem, it's a copy paste of the

get('Users_Users')

Where is the problem? I use the same method for my 4 other bundle :/

答:
Can you please provide the service definition ? You know in a yaml or an xml file.

Then, please check the name of your service is really Users_Users (which is, in my mind a weird name).

If you named your service like the best practice encourages to do (with the Full Qualified Class Name (FQCN) -> Read):

```<code>#app/config/services.yml
services:
    UsersBundle\Services\Users:
        class: Acme\TwitterClient
        arguments: ["@someLdapServiceName", "@Another/Good/Named/Service", "@..."]
</code>```

then your service will be able by its name:

```<code><?php
    $this->get('UsersBundle\Services\Users');
</code>```

From Symfony 2.8 and in Symfony v3.3 by default, a great new feature is the Service autowiring. You can use it to ease the service definition but you need to pay attention because since the 3.3 version, the default service auto-configuration comes with default private services:

services:
    _defaults:
        public: false

Please note also that in the next LTS 3.4 version and in 4.0, the services are private by default, no more need this configuration line.

So if you want to access your service directly from your container's get method, you'll need to add this to your Users_Users service definition:

services:
    Users_Users:
        ...
        public: true

Body:
When I try to access at my service, got this error :

You have requested a non-existent service "Users_Users".

But the namespace, the name of the class, name of the file, name of folder is ok. I have already copy paste the name to be sure.

Controller ->

<?php

namespace UsersBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use UsersBundle\Form\UsersForm;
use Symfony\Component\HttpFoundation\Request;

class UsersController extends Controller
{
    public function UsersAction($Id)
    {
        $Users = $this->container->get('Users_Users')->ListeUsers($Id);
        return $this->render('UsersBundle:Users:users.html.twig', array('Users' => $Users));
    }

Service :

<?php

namespace UsersBundle\Services;

class Users
{
    public function __construct($ldap,$Core_ConnexionsBDD,$MySql_ConnexionsBDD, $session)
    {
        $this->ldap = $ldap;
        $this->Core_ConnexionsBDD = $Core_ConnexionsBDD;
        $this->MySql_ConnexionsBDD = $MySql_ConnexionsBDD;
        $this->session = $session;
    }

    public function ListeUsers($Id)
    {
        $lists = $this->MySql_ConnexionsBDD->getUsers();
        return $lists->Liste($Id);
    }

}

Un the service file, no problem, it's a copy paste of the

get('Users_Users')

Where is the problem? I use the same method for my 4 other bundle :/

Body:
Can you please provide the service definition ? You know in a yaml or an xml file.

Then, please check the name of your service is really Users_Users (which is, in my mind a weird name).

If you named your service like the best practice encourages to do (with the Full Qualified Class Name (FQCN) -> Read):

#app/config/services.yml
services:
    UsersBundle\Services\Users:
        class: Acme\TwitterClient
        arguments: ["@someLdapServiceName", "@Another/Good/Named/Service", "@..."]

then your service will be able by its name:

<?php
    $this->get('UsersBundle\Services\Users');

From Symfony 2.8 and in Symfony v3.3 by default, a great new feature is the Service autowiring. You can use it to ease the service definition but you need to pay attention because since the 3.3 version, the default service auto-configuration comes with default private services:

services:
    _defaults:
        public: false

Please note also that in the next LTS 3.4 version and in 4.0, the services are private by default, no more need this configuration line.

So if you want to access your service directly from your container's get method, you'll need to add this to your Users_Users service definition:

services:
    Users_Users:
        ...
        public: true


问:
Redefining functions defined in standard libc header files?
Is there any gcc trick that lets me redefine the signature of libc functions (e.g. fsetpos) defined in standard headers (e.g. stdio.h)? As of now if I do that, I receive duplicate declaration error message.

答:
Declarations in standard headers are decorated with many additional attributes to help optimizations, improve portability, etc. (and sometimes even defined as macros). If your declaration is even slightly incompatible to those you are guaranteed to get many interesting messages from compiler.

So if you try to overload some standard function, do not include standard headers in its file.


问:
MongoDB: Does findOne retrieve the whole collection from the database to the server
I am trying to make a website and I'm using mongoDB to store my database. I have a question about the performance about the query findOne which I've used widely. Does this query take the whole collection from the database to the server and then perform the iteration over it or does it perform the iteration on the database and just return the document to the server? Picking up the whole collection from the server will be an issue because transferring such a huge chunk of data will take time. </p>

答:
Understanding how mongodb uses indexes would help you answer this question.  If you pass in parameters to the findOne query, and those parameters match an index on the collection then mongodb will use the index to find your results.  Without the index mongodb will need to scan the collection till it finds a match.

For example if you run a query like:

```<code>db.coll.findOne({"_id": ObjectId("5a0a0e6f29642fd7a970420c")})
</code>```

then mongodb will know exactly which document you want since the _id field is unique and contains an index.  If you query on another field which isn't indexed then mongodb will need to do a COLLSCAN to find the document(s) to return.

Body:
Understanding how mongodb uses indexes would help you answer this question.  If you pass in parameters to the findOne query, and those parameters match an index on the collection then mongodb will use the index to find your results.  Without the index mongodb will need to scan the collection till it finds a match.

For example if you run a query like:

db.coll.findOne({"_id": ObjectId("5a0a0e6f29642fd7a970420c")})

then mongodb will know exactly which document you want since the _id field is unique and contains an index.  If you query on another field which isn't indexed then mongodb will need to do a COLLSCAN to find the document(s) to return.

ContentLicense: CC BY-SA 4.0


问:
How to add spaces between values in xml?
I have to create an xml out of other xml. I already have the answer to that, but then I'm facing another problem. The output of the xml is quite messy in the  tag.

The xml is this:

```<code><rss>
  <item id="12907">
    <g:productname>Black Bag</g:productname>
      <g:detailed_images>
          <g:detailed_image>Image1.jpg</g:detailed_image>
          <g:detailed_image>Image2.jpg</g:detailed_image>
          <g:detailed_image>Image3.jpg</g:detailed_image>
          <g:detailed_image>Image4.jpg</g:detailed_image>
          <g:detailed_image>Image5.jpg</g:detailed_image>
          <g:detailed_image>Image6.jpg</g:detailed_image>
          <g:detailed_image>Image7.jpg</g:detailed_image>
          <g:detailed_image>Image8.jpg</g:detailed_image>
          <g:detailed_image>Image9.jpg</g:detailed_image>
          <g:detailed_image>Image10.jpg</g:detailed_image>
          <g:detailed_image>Image11.jpg</g:detailed_image>
          <g:detailed_image>Image12.jpg</g:detailed_image>
      </g:detailed_images>
  </item>
  <item id="12906">
    <g:productname>Yellow Bag</g:productname>
      <g:detailed_images>
          <g:detailed_image>Image1.jpg</g:detailed_image>
          <g:detailed_image>Image2.jpg</g:detailed_image>
          <g:detailed_image>Image3.jpg</g:detailed_image>
          <g:detailed_image>Image4.jpg</g:detailed_image>
          <g:detailed_image>Image5.jpg</g:detailed_image>
          <g:detailed_image>Image6.jpg</g:detailed_image>
          <g:detailed_image>Image7.jpg</g:detailed_image>
          <g:detailed_image>Image8.jpg</g:detailed_image>
          <g:detailed_image>Image9.jpg</g:detailed_image>
          <g:detailed_image>Image10.jpg</g:detailed_image>
          <g:detailed_image>Image11.jpg</g:detailed_image>
          <g:detailed_image>Image12.jpg</g:detailed_image>
      </g:detailed_images>
  </item>
</rss>
</code>```

The php code that I'm using to create another xml file is this

```<code><?php
    $document = new DOMDocument;
    $document->formatOutput = true;
    $document->preserveWhiteSpace = false;
    $document->load('xml_feeds.xml');
    $xpath = new DOMXPath($document);

    $fields = [
        'productname' => 'string(g:productname)',
        'detailed_images' => 'string(g:detailed_images)'
    ];

    $xml = new DOMDocument;
    $xml->formatOutput = true;
    $xml->preserveWhiteSpace = false;
    $rss = $xml->appendChild($xml->createElement('rss'));

    foreach ($xpath->evaluate('//item') as $item) {
        //create tag item
        $createItem = $rss->appendChild($xml->createElement('item'));

        //getting item's attribute value
        $valueID = $item->getAttribute('id');

        //create attribute
        $itemAttribute = $xml->createAttribute('id');
        $itemAttribute->value = $valueID;
        $createItem->appendChild($itemAttribute);

        foreach ($fields as $caption => $expression) {
            $value = $xpath->evaluate($expression, $item);
            $createItem->appendChild($xml->createElement($caption, $value));
        }
    }

    $xml->save('new_createxml2.xml');
?>
</code>```

The result of the new_createxml2.xml is this

```<code><?xml version="1.0"?>
<rss>
  <item id="12907">
    <productname>Black Bag</productname>
    <detailed_images>Image1.jpgImage2.jpgImage3.jpgImage4.jpgImage3.jpgImage4.jpgImage5.jpgImage6.jpgImage7.jpgImage8.jpgImage9.jpgImage10.jpgImage11.jpgImage12.jpg</detailed_images>
  </item>
  <item id="12906">
    <productname>Yellow Bag</productname>
    <detailed_images>Image1.jpgImage2.jpgImage3.jpgImage4.jpgImage3.jpgImage4.jpgImage5.jpgImage6.jpgImage7.jpgImage8.jpgImage9.jpgImage10.jpgImage11.jpgImage12.jpg</detailed_images>
  </item>
</rss>
</code>```

I really wonder how can I create the xml tidier than what I've made. I want it to display like this actually:

```<code><?xml version="1.0"?>
<rss>
  <item id="12907">
    <productname>Black Bag</productname>
    <detailed_images>Image1.jpg, Image2.jpg, Image3.jpg, Image4.jpg, Image3.jpg, Image4.jpg, Image5.jpg, Image6.jpg, Image7.jpg, Image8.jpg, Image9.jpg, Image10.jpg, Image11.jpg, Image12.jpg</detailed_images>
  </item>
  <item id="12906">
    <productname>Yellow Bag</productname>
    <detailed_images>Image1.jpg, Image2.jpg, Image3.jpg, Image4.jpg, Image3.jpg, Image4.jpg, Image5.jpg, Image6.jpg, Image7.jpg, Image8.jpg, Image9.jpg, Image10.jpg, Image11.jpg, Image12.jpg</detailed_images>
  </item>
</rss>
</code>```

Thank you for your help

答:
The way you've tried it is quite simple for some things, but as you've found out that this method fails when you want processing for each individual piece of data.  When you use 'string(g:detailed_images)' - this is the text content of all of the subnodes in your document, which is why you have all of the values stuck together.  You could then process this string with some form of regular expression - but as you have no control of the content it's difficult to know what you are going to find.

Changing it to a more traditional - get values using a specific XPath call and processing the values allows you more control over the result.

```<code>foreach ($xpath->evaluate('//item') as $item) {
    //create tag item
    $createItem = $rss->appendChild($xml->createElement('item'));

    //getting item's attribute value
    $valueID = $item->getAttribute('id');

    //create attribute
    $itemAttribute = $xml->createAttribute('id');
    $itemAttribute->value = $valueID;
    $createItem->appendChild($itemAttribute);

    $prodName = $xpath->evaluate("string(g:productname)", $item);
    $createItem->appendChild($xml->createElement('productname', $prodName));
    $images = [];
    foreach ( $xpath->query("descendant::g:detailed_image", $item) as $image )    {
        $images[] = $image->nodeValue;
    }
    $createItem->appendChild($xml->createElement('detailed_images',
            implode(",", $images)));
}
</code>```

Body:
I have to create an xml out of other xml. I already have the answer to that, but then I'm facing another problem. The output of the xml is quite messy in the  tag.

The xml is this:

<rss>
  <item id="12907">
    <g:productname>Black Bag</g:productname>
      <g:detailed_images>
          <g:detailed_image>Image1.jpg</g:detailed_image>
          <g:detailed_image>Image2.jpg</g:detailed_image>
          <g:detailed_image>Image3.jpg</g:detailed_image>
          <g:detailed_image>Image4.jpg</g:detailed_image>
          <g:detailed_image>Image5.jpg</g:detailed_image>
          <g:detailed_image>Image6.jpg</g:detailed_image>
          <g:detailed_image>Image7.jpg</g:detailed_image>
          <g:detailed_image>Image8.jpg</g:detailed_image>
          <g:detailed_image>Image9.jpg</g:detailed_image>
          <g:detailed_image>Image10.jpg</g:detailed_image>
          <g:detailed_image>Image11.jpg</g:detailed_image>
          <g:detailed_image>Image12.jpg</g:detailed_image>
      </g:detailed_images>
  </item>
  <item id="12906">
    <g:productname>Yellow Bag</g:productname>
      <g:detailed_images>
          <g:detailed_image>Image1.jpg</g:detailed_image>
          <g:detailed_image>Image2.jpg</g:detailed_image>
          <g:detailed_image>Image3.jpg</g:detailed_image>
          <g:detailed_image>Image4.jpg</g:detailed_image>
          <g:detailed_image>Image5.jpg</g:detailed_image>
          <g:detailed_image>Image6.jpg</g:detailed_image>
          <g:detailed_image>Image7.jpg</g:detailed_image>
          <g:detailed_image>Image8.jpg</g:detailed_image>
          <g:detailed_image>Image9.jpg</g:detailed_image>
          <g:detailed_image>Image10.jpg</g:detailed_image>
          <g:detailed_image>Image11.jpg</g:detailed_image>
          <g:detailed_image>Image12.jpg</g:detailed_image>
      </g:detailed_images>
  </item>
</rss>

The php code that I'm using to create another xml file is this

<?php
    $document = new DOMDocument;
    $document->formatOutput = true;
    $document->preserveWhiteSpace = false;
    $document->load('xml_feeds.xml');
    $xpath = new DOMXPath($document);

    $fields = [
        'productname' => 'string(g:productname)',
        'detailed_images' => 'string(g:detailed_images)'
    ];

    $xml = new DOMDocument;
    $xml->formatOutput = true;
    $xml->preserveWhiteSpace = false;
    $rss = $xml->appendChild($xml->createElement('rss'));

    foreach ($xpath->evaluate('//item') as $item) {
        //create tag item
        $createItem = $rss->appendChild($xml->createElement('item'));

        //getting item's attribute value
        $valueID = $item->getAttribute('id');

        //create attribute
        $itemAttribute = $xml->createAttribute('id');
        $itemAttribute->value = $valueID;
        $createItem->appendChild($itemAttribute);

        foreach ($fields as $caption => $expression) {
            $value = $xpath->evaluate($expression, $item);
            $createItem->appendChild($xml->createElement($caption, $value));
        }
    }

    $xml->save('new_createxml2.xml');
?>

The result of the new_createxml2.xml is this

<?xml version="1.0"?>
<rss>
  <item id="12907">
    <productname>Black Bag</productname>
    <detailed_images>Image1.jpgImage2.jpgImage3.jpgImage4.jpgImage3.jpgImage4.jpgImage5.jpgImage6.jpgImage7.jpgImage8.jpgImage9.jpgImage10.jpgImage11.jpgImage12.jpg</detailed_images>
  </item>
  <item id="12906">
    <productname>Yellow Bag</productname>
    <detailed_images>Image1.jpgImage2.jpgImage3.jpgImage4.jpgImage3.jpgImage4.jpgImage5.jpgImage6.jpgImage7.jpgImage8.jpgImage9.jpgImage10.jpgImage11.jpgImage12.jpg</detailed_images>
  </item>
</rss>

I really wonder how can I create the xml tidier than what I've made. I want it to display like this actually:

<?xml version="1.0"?>
<rss>
  <item id="12907">
    <productname>Black Bag</productname>
    <detailed_images>Image1.jpg, Image2.jpg, Image3.jpg, Image4.jpg, Image3.jpg, Image4.jpg, Image5.jpg, Image6.jpg, Image7.jpg, Image8.jpg, Image9.jpg, Image10.jpg, Image11.jpg, Image12.jpg</detailed_images>
  </item>
  <item id="12906">
    <productname>Yellow Bag</productname>
    <detailed_images>Image1.jpg, Image2.jpg, Image3.jpg, Image4.jpg, Image3.jpg, Image4.jpg, Image5.jpg, Image6.jpg, Image7.jpg, Image8.jpg, Image9.jpg, Image10.jpg, Image11.jpg, Image12.jpg</detailed_images>
  </item>
</rss>

Thank you for your help

Body:
The way you've tried it is quite simple for some things, but as you've found out that this method fails when you want processing for each individual piece of data.  When you use 'string(g:detailed_images)' - this is the text content of all of the subnodes in your document, which is why you have all of the values stuck together.  You could then process this string with some form of regular expression - but as you have no control of the content it's difficult to know what you are going to find.

Changing it to a more traditional - get values using a specific XPath call and processing the values allows you more control over the result.

foreach ($xpath->evaluate('//item') as $item) {
    //create tag item
    $createItem = $rss->appendChild($xml->createElement('item'));

    //getting item's attribute value
    $valueID = $item->getAttribute('id');

    //create attribute
    $itemAttribute = $xml->createAttribute('id');
    $itemAttribute->value = $valueID;
    $createItem->appendChild($itemAttribute);

    $prodName = $xpath->evaluate("string(g:productname)", $item);
    $createItem->appendChild($xml->createElement('productname', $prodName));
    $images = [];
    foreach ( $xpath->query("descendant::g:detailed_image", $item) as $image )    {
        $images[] = $image->nodeValue;
    }
    $createItem->appendChild($xml->createElement('detailed_images',
            implode(",", $images)));
}


问:
List containing lists (matrix) as input() with python 3
I'm trying to convert a given input to a list containing lists as shown in the command-line code below:

```<code>matrix = input('asking')
asking[[2, 0, 4],[1, 2, 4],[4, 4, 2]]
matrix
'[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
</code>```

desired output:

```<code>[[2,0,4],[1,2,4],[4,4,2]]
</code>```

Attempts

```<code>list(matrix)
['[', '[', '2', ',', ' ', '0', ',', ' ', '4', ']', ',', ' ', '[', '1', ',', ' ', '2', ',', ' ', '4', ']', ',', ' ', '[', '4', ',', ' ', '4', ',', ' ', '2', ']', ']']

x = [int(a) for a in matrix]
builtins.TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

matrix.split(',')
['[[2', '0', '4]', '[1', '2', '4]', '[4', '4', '2]]']
</code>```

Code:

```<code>fin_result = 0

def perform_check():
    print("Enter form \n [[a,b,c] \n [d,e,f] \n [g,h,i]]")
    #ask_for_input = [[4,-1,1],[4,5,3],[-2,0,0]]
    ask_for_input = [[2,0,4],[1,2,4],[4,4,2]]
    print(type(ask_for_input))

    #call function to cont
    calculate_determinate_matrix(ask_for_input)

def calculate_determinate_matrix(matrix3x3):
    matrix_list2x2 = []

    matrix_list2x2.append([[matrix3x3[1][1], matrix3x3[1][2]], [matrix3x3[2][1], matrix3x3[2][2]]])

    matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][2]],[matrix3x3[2][0], matrix3x3[2][2]]])

    matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][1]],[matrix3x3[2][0], matrix3x3[2][1]]])

    count = 0
    for count, matrix_2x2 in enumerate(matrix_list2x2):
        if count % 2 == 1:
            calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count] * -1)
        else:
            calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count])

def calculate_2x2_matrix(matrix, mult):
    global fin_result
    result = matrix[0][0] * matrix[1][1]
    result_2 = matrix[0][1] * matrix[1][0]
    fin_result += mult * (result - result_2)

def main():
    perform_check()
    print(fin_result)

if __name__ == "__main__":
    main()
</code>```

Clearly this code needs work, but I can't figure this in terms of list comprehension.

答:
Use json loads() method:

```<code>matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = json.loads(matrix)
type(matrix)
<type 'list'>
</code>```

And in case you want to check for errors in input you can wrap it in try-except:

```<code>try:
    matrix = json.loads(matrix)
except ValueError:
    #code goes here
</code>```

Body:
I'm trying to convert a given input to a list containing lists as shown in the command-line code below:

matrix = input('asking')
asking[[2, 0, 4],[1, 2, 4],[4, 4, 2]]
matrix
'[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'

desired output:

[[2,0,4],[1,2,4],[4,4,2]]

Attempts

list(matrix)
['[', '[', '2', ',', ' ', '0', ',', ' ', '4', ']', ',', ' ', '[', '1', ',', ' ', '2', ',', ' ', '4', ']', ',', ' ', '[', '4', ',', ' ', '4', ',', ' ', '2', ']', ']']

x = [int(a) for a in matrix]
builtins.TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

matrix.split(',')
['[[2', '0', '4]', '[1', '2', '4]', '[4', '4', '2]]']

Code:

fin_result = 0

def perform_check():
    print("Enter form \n [[a,b,c] \n [d,e,f] \n [g,h,i]]")
    #ask_for_input = [[4,-1,1],[4,5,3],[-2,0,0]]
    ask_for_input = [[2,0,4],[1,2,4],[4,4,2]]
    print(type(ask_for_input))

    #call function to cont
    calculate_determinate_matrix(ask_for_input)

def calculate_determinate_matrix(matrix3x3):
    matrix_list2x2 = []

    matrix_list2x2.append([[matrix3x3[1][1], matrix3x3[1][2]], [matrix3x3[2][1], matrix3x3[2][2]]])

    matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][2]],[matrix3x3[2][0], matrix3x3[2][2]]])

    matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][1]],[matrix3x3[2][0], matrix3x3[2][1]]])

    count = 0
    for count, matrix_2x2 in enumerate(matrix_list2x2):
        if count % 2 == 1:
            calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count] * -1)
        else:
            calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count])

def calculate_2x2_matrix(matrix, mult):
    global fin_result
    result = matrix[0][0] * matrix[1][1]
    result_2 = matrix[0][1] * matrix[1][0]
    fin_result += mult * (result - result_2)

def main():
    perform_check()
    print(fin_result)

if __name__ == "__main__":
    main()

Clearly this code needs work, but I can't figure this in terms of list comprehension.

Body:
Use json loads() method:

matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = json.loads(matrix)
type(matrix)
<type 'list'>

And in case you want to check for errors in input you can wrap it in try-except:

try:
    matrix = json.loads(matrix)
except ValueError:
    #code goes here


问:
hibernate named queries
In hibernate, when we do, session.getNamedQuery(QUERY_NAME), we do not need to pass in the name of the hbm.xml file where the named query is stored. The name of the hbm.xml is mentioned in the cfg file.

The question is, if there are 5 hbm.xml files for named queries, and there is a name conflict with respect to the query name(i.e. same QUERY_NAME in all 5 files), how hibernate will resolve it?

Intuitively, it appears before doing session.getNamedQuery(QUERY_NAME), one should need to explicitly load the particular hbm.xml file where the query is written.

答: In addition to Pangea's answer: if you want to have different version of the same query in different .hbm.xml files and choose between them, you can do it by calling Configuration.addFile()/Configuration.addInputStream() when constructing the SessionFactory (though it can be done only once during SessionFactory initialization, so that you can't change them on the fly).

ContentLicense: CC BY-SA 2.5

Title: hibernate named queries


问:
Geocoding in python get Latitude and Longitude from addresses using API key
I currently have a data frame that has address details of certain place. I want to use Google geocode API key to find the coordinates - Latitude and Longitude in order to plot a map. Does anybody know how to do this? I have tried the below code but it is returning 'Error, skipping address...' on all the lines of addresses.

I would greatly appreciate any help!

```<code>import pandas as pd
import os
from geopy import geocoders
from geopy.geocoders import GoogleV3

API_KEY = os.getenv("API1234")
g = GoogleV3(api_key=API_KEY)

loc_coordinates = []
loc_address = []

for address in df.Address:
    try:
        inputAddress = Address
        location = g.geocode(inputAddress, timeout=15)
        loc_coordinates.append((location.latitude, location.longitude))
        loc_Address.append(inputAddress)
    except:
        print('Error, skipping address...')

df_geocodes = pd.DataFrame({'coordinate':loc_coordinates,'address':loc_address})
</code>```

答:
You had some typos: Address instead of address, loc_Address instead of loc_address.

But what is df.Address ?

Try this:

```<code>import pandas as pd
import os
from geopy import geocoders
from geopy.geocoders import GoogleV3

API_KEY = os.getenv("API1234")
g = GoogleV3(api_key=API_KEY)

loc_coordinates = []
loc_address = []
for address in df.Address:
    try:
        inputAddress = address
        location = g.geocode(inputAddress, timeout=15)
        loc_coordinates.append((location.latitude, location.longitude))
        loc_address.append(inputAddress)
    except Exception as e:
        print('Error, skipping address...', e)

df_geocodes = pd.DataFrame({'coordinate':loc_coordinates,'address':loc_address})
</code>```

Body:
I currently have a data frame that has address details of certain place. I want to use Google geocode API key to find the coordinates - Latitude and Longitude in order to plot a map. Does anybody know how to do this? I have tried the below code but it is returning 'Error, skipping address...' on all the lines of addresses.

I would greatly appreciate any help!

import pandas as pd
import os
from geopy import geocoders
from geopy.geocoders import GoogleV3

API_KEY = os.getenv("API1234")
g = GoogleV3(api_key=API_KEY)

loc_coordinates = []
loc_address = []

for address in df.Address:
    try:
        inputAddress = Address
        location = g.geocode(inputAddress, timeout=15)
        loc_coordinates.append((location.latitude, location.longitude))
        loc_Address.append(inputAddress)
    except:
        print('Error, skipping address...')

df_geocodes = pd.DataFrame({'coordinate':loc_coordinates,'address':loc_address})

Body:
You had some typos: Address instead of address, loc_Address instead of loc_address.

But what is df.Address ?

Try this:

import pandas as pd
import os
from geopy import geocoders
from geopy.geocoders import GoogleV3

API_KEY = os.getenv("API1234")
g = GoogleV3(api_key=API_KEY)

loc_coordinates = []
loc_address = []
for address in df.Address:
    try:
        inputAddress = address
        location = g.geocode(inputAddress, timeout=15)
        loc_coordinates.append((location.latitude, location.longitude))
        loc_address.append(inputAddress)
    except Exception as e:
        print('Error, skipping address...', e)

df_geocodes = pd.DataFrame({'coordinate':loc_coordinates,'address':loc_address})


问:
Cronjob not redirecting output
I have created one test.sh shell script which I have scheduled using crontab -e to execute after every 1 minutes and redirecting output to a file.

test.sh

```<code>echo "Printing all Environment Var"
env
echo "Bye Bye"
</code>```

Below is how my crontab look like

```<code>#crontab
0,1,2,3,4,5,6,7,8,9,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 * * * * sudo su - admiir -c /u01/users/admiir/test.sh > /u01/app/iir/InformaticaIR/iirlog/crontab_launchsh.log
</code>```

When I run ls -ltr the timestamp is getting updated but nothing is getting printed in the output file.

答:
To run the cron every minute and to save to a file the current environment used this could be used:

```<code>* * * * * env > ~/cronenv
</code>```

Next, you can start a shell like it will be run within cron by doing:

```<code>env - `cat ~/cronenv` /bin/sh
</code>```

Here you could try something like:

```<code>su - admiir -c "/u01/users/admiir/test.sh > /u01/app/iir/InformaticaIR/iirlog/crontab_launchsh.log"
</code>```

You can omit the sudo su and only use su

Once your script is working you could then update your cron with:

```<code>* * * * * su - admiir -c "/path/to/test.sh > /path/to/out.txt"
</code>```

You could also run the cron as the specific user by doing:

```<code>sudo crontab -u username -e
</code>```

Title: Cronjob not redirecting output

Body:
I have created one test.sh shell script which I have scheduled using crontab -e to execute after every 1 minutes and redirecting output to a file.

test.sh

echo "Printing all Environment Var"
env
echo "Bye Bye"

Below is how my crontab look like

#crontab
0,1,2,3,4,5,6,7,8,9,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 * * * * sudo su - admiir -c /u01/users/admiir/test.sh > /u01/app/iir/InformaticaIR/iirlog/crontab_launchsh.log

When I run ls -ltr the timestamp is getting updated but nothing is getting printed in the output file.

Body:
To run the cron every minute and to save to a file the current environment used this could be used:

* * * * * env > ~/cronenv

Next, you can start a shell like it will be run within cron by doing:

env - `cat ~/cronenv` /bin/sh

Here you could try something like:

su - admiir -c "/u01/users/admiir/test.sh > /u01/app/iir/InformaticaIR/iirlog/crontab_launchsh.log"

You can omit the sudo su and only use su

Once your script is working you could then update your cron with:

* * * * * su - admiir -c "/path/to/test.sh > /path/to/out.txt"

You could also run the cron as the specific user by doing:

sudo crontab -u username -e