text:
Q: XSLT - XML Transformation I have the XML in the below format
<?xml version="1.0" encoding="utf-8"?>
<Data Schema="RSXML4.0" xmlns="http://schemas.riversand.com/mdmcenter"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://schemas.riversand.com/mdmcenter/RSXml4.0.xsd">
    <Entities>
<Entity Id="347" ExternalId="SSI1006"
            LongName="School Smart Hand Held Rustproof Carbon Steel Pencil Sharpener, Assorted Color, Pack of 24"
            EntityTypeId="18" EntityTypeName="Parent SKU" ContainerId="2"
            ContainerName="Collaboration Master" OrganizationName="DL" CategoryId="360"
            CategoryName="Sharpners" CategoryLongName="Sharpners"
            CategoryPath="SchoolSupplies»School_Office_Supplies»Sharpners" CategoryLongNamePath=""
            ParentEntityId="360" ParentExternalId="Sharpners" ParentExtensionEntityId="0"
            ParentExtensionEntityExternalId="" ParentExtensionEntityContainerId="0"
            ParentExtensionEntityContainerName="" ParentExtensionEntityCategoryId="0"
            ParentExtensionEntityCategoryPath="" ParentExtensionEntityCategoryLongNamePath=""
            Locale="en_WW" Action="Add">
            <Attributes>
                <Attribute Id="4039" Name="Parent SKU #" LongName="Product Number"
                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[9-07466-030]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4040" Name="Product Name" LongName="Product Name" InstanceRefId="-1"
                    Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[School Smart Hand Held Rustproof Carbon Steel Pencil Sharpener]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4041" Name="SKU Dimensions" LongName="SKU Dimensions"
                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[3/4 in x 1 in x 1/2 in]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4042" Name="MSRP" LongName="MSRP" InstanceRefId="-1" Sequence="-1"
                    AttributeParentId="4000" AttributeParentName="Core Attribute Group"
                    AttributeType="Simple" AttributeDataType="Decimal" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[2.49]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4045" Name="Collection" LongName="Collection" InstanceRefId="-1"
                    Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[School Smart]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4047" Name="UPC" LongName="UPC" InstanceRefId="-1" Sequence="-1"
                    AttributeParentId="4000" AttributeParentName="Core Attribute Group"
                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[892030475006]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4049" Name="Short Description" LongName="Short Description"
                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4001"
                    AttributeParentName="Marketing Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[School Smart hand Pencil Sharpener features plastic housing with hardened and honed rust-proof carbon steel blade.]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4050" Name="Long Description" LongName="Long Description"
                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4001"
                    AttributeParentName="Marketing Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[School Smart hand Pencil Sharpener features plastic housing with hardened and honed rust-proof carbon steel blade. Designed for sharpening of pencils. Hand pencil sharpener comes in assorted colors and is sold as 24 per pack.]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4122" Name="A-Assets" LongName="Assets" InstanceRefId="-1"
                    Sequence="-1" AttributeParentId="4003"
                    AttributeParentName="Media Attribute Group" AttributeType="ComplexCollection"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Attributes>
                        <Attribute Id="4122" Name="A-Assets Instance Record"
                            LongName="Assets Instance Record" InstanceRefId="293" Sequence="0"
                            AttributeParentId="4003" AttributeParentName="Media Attribute Group"
                            AttributeType="Complex" AttributeDataType="String" Locale="en_WW"
                            Action="Add">
                            <Attributes>
                                <Attribute Id="4126" Name="A-AssetDescription"
                                    LongName="AssetDescription" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4127" Name="A-AssetDisplayName"
                                    LongName="AssetDisplayName" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4128" Name="A-AssetFileName" LongName="AssetFileName"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[SSI1006_SchoolSmart Sharpener_1.jpg]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4129" Name="A-AssetID" LongName="AssetID"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[991E8697FD394A17A70C0DA7A73ECE87]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4130" Name="A-AssetImageThumb"
                                    LongName="AssetImageThumb" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4131" Name="A-AssetImageType"
                                    LongName="AssetImageType" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4132" Name="A-AssetKind" LongName="AssetKind"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4133" Name="A-AssetLocalURL" LongName="AssetLocalURL"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[http://smbpoc.riversand.com:8080/MAM76/assets/1/76E608495D23463EA54B253B1FB1D94C/img/991E8697FD394A17A70C0DA7A73ECE87/SSI1006_SchoolSmart_Sharpener_1.jpg]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4134" Name="A-AssetProductDescription"
                                    LongName="AssetProductDescription" InstanceRefId="-1"
                                    Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4135" Name="A-AssetRenditions"
                                    LongName="AssetRenditions" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[<?xml version="1.0" encoding="utf-16"?><Renditions />]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4136" Name="A-AssetSize" LongName="AssetSize"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[93194]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4137" Name="A-AssetThumbnailURL"
                                    LongName="AssetThumbnailURL" InstanceRefId="-1" Sequence="-1"
                                    AttributeParentId="4122" AttributeParentName="A-Assets"
                                    AttributeType="Simple" AttributeDataType="String" Locale="en_WW"
                                    Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[http://smbpoc.riversand.com:8080/MAM76/assets/1/76E608495D23463EA54B253B1FB1D94C/img/991E8697FD394A17A70C0DA7A73ECE87/thumb_991E8697FD394A17A70C0DA7A73ECE87.jpg]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4138" Name="A-AssetType" LongName="AssetType"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[img]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4139" Name="A-AssetPrimary" LongName="AssetPrimary"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="2" Sequence="-1"
                                            DisplayValue="Secondary" HasInvalidValue="False"
                                            Locale="en_WW" Action="Add"
                                            ><![CDATA[Secondary]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4140" Name="A-AssetSequence" LongName="AssetSequence"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="Integer" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"><![CDATA[1]]></Value>
                                    </Values>
                                </Attribute>
                                <Attribute Id="4142" Name="A-FilePath" LongName="AssetFilePath"
                                    InstanceRefId="-1" Sequence="-1" AttributeParentId="4122"
                                    AttributeParentName="A-Assets" AttributeType="Simple"
                                    AttributeDataType="String" Locale="en_WW" Action="Add">
                                    <Values>
                                        <Value Id="-1" Uom="" ValueRefId="0" Sequence="-1"
                                            DisplayValue="" HasInvalidValue="False" Locale="en_WW"
                                            Action="Add"
                                            ><![CDATA[C:\Users\RSAdmin\Documents\Templates\Print Images\SSI1006_SchoolSmart_Sharpener_1.jpg]]></Value>
                                    </Values>
                                </Attribute>
                            </Attributes>
                        </Attribute>
                    </Attributes>
                </Attribute>
                <Attribute Id="4618" Name="ItemQty" LongName="ItemQty" InstanceRefId="-1"
                    Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[Pack of 24]]></Value>
                    </Values>
                </Attribute>
                <Attribute Id="4619" Name="ItemColor" LongName="ItemColor" InstanceRefId="-1"
                    Sequence="-1" AttributeParentId="4000"
                    AttributeParentName="Core Attribute Group" AttributeType="Simple"
                    AttributeDataType="String" Locale="en_WW" Action="Add">
                    <Values>
                        <Value Id="0" Uom="" ValueRefId="-1" Sequence="-1" DisplayValue=""
                            HasInvalidValue="False" Locale="en_WW" Action="Add"
                            ><![CDATA[Assorted]]></Value>
                    </Values>
                </Attribute>
            </Attributes>
            <Relationships/>
        </Entity>
    </Entities>
</Data>

I have multiple such Entity nodes. I need to add an attribute in each 'Entity' node as ProductImage = value of the attribute with the name 'A-AssetFileName'. I need to do this using XSLT. Any help would be appreciated. The below XSLT adds the value of each image value to the same Entity node. I want each Entity node to have their corresponding image value from the attribute with the name 'A-AssetFileName'. For eg:
my first entity node should become:
<Entity Id="347" ExternalId="SSI1006"
            LongName="School Smart Hand Held Rustproof Carbon Steel Pencil Sharpener, Assorted Color, Pack of 24"
            EntityTypeId="18" EntityTypeName="Parent SKU" ContainerId="2"
            ContainerName="Collaboration Master" OrganizationName="DL" CategoryId="360"
            CategoryName="Sharpners" CategoryLongName="Sharpners"
            CategoryPath="SchoolSupplies»School_Office_Supplies»Sharpners" CategoryLongNamePath=""
            ParentEntityId="360" ParentExternalId="Sharpners" ParentExtensionEntityId="0"
            ParentExtensionEntityExternalId="" ParentExtensionEntityContainerId="0"
            ParentExtensionEntityContainerName="" ParentExtensionEntityCategoryId="0"
            ParentExtensionEntityCategoryPath="" ParentExtensionEntityCategoryLongNamePath=""
            Locale="en_WW" Action="Add" ProductImage="SSI1006_SchoolSmart Sharpener_1.jpg">

I am using the below XSLT.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:x="http://schemas.riversand.com/mdmcenter">
    <xsl:output omit-xml-declaration="yes" indent="yes" encoding="UTF-8"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/x:Data/x:Entities/x:Entity">
        <xsl:for-each select = "/x:Data/x:Entities/x:Entity">
        <xsl:copy>

<!--                <xsl:choose>-->
<!--                    <xsl:when test='/x:Data/x:Entities/x:Entity/x:Attributes/x:Attribute/x:Attributes/x:Attribute[@Name = "A-Assets Instance Record"]'>-->
<!--                        <xsl:if test='/x:Data/x:Entities/x:Entity/x:Attributes/x:Attribute/x:Attributes/x:Attribute[@Sequence = "0"]'>-->

                            <xsl:attribute name="ProductImage">
                                <xsl:for-each select = "/x:Data/x:Entities/x:Entity/x:Attributes/x:Attribute/x:Attributes/x:Attribute/x:Attributes/x:Attribute[@Name = 'A-AssetFileName']">
                                <xsl:value-of select="."/>
                                </xsl:for-each>
                            </xsl:attribute>

                        <!--</xsl:if>-->
                    <!--</xsl:when>-->
                <!--</xsl:choose>-->
                <!--            <xsl:apply-templates select="@* | node()"/>-->

        </xsl:copy>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

A: You can start with an identity template that copies the input XML as is to the output.
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>

Since you need to add an attribute to the Entity element, a matching template is used. An attribute Image is created within the template with a value corresponding to the value of element Attribute/value within the Entity template. Function normalize-space() is used to get rid of any leading and trailing spaces.
<xsl:template match="Entity">
    <xsl:copy>
        <xsl:attribute name="Image">
            <xsl:value-of select="normalize-space(Attribute/value)" />
        </xsl:attribute>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>

Complete XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Entity">
        <xsl:copy>
            <xsl:attribute name="Image">
                <xsl:value-of select="normalize-space(Attribute/value)" />
            </xsl:attribute>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output is as below. Since the input XML has abc.jpg as a value of both the value elements, the attribute value is the same for both the Entity elements.
<Data>
    <Entities>
        <Entity Image="abc.jpg">
            <Attribute name="abc">
                <value> abc.jpg
                </value>
            </Attribute>
        </Entity>
        <Entity Image="abc.jpg">
            <Attribute name="def">
                <value> abc.jpg
                </value>
            </Attribute>
        </Entity>
    </Entities>
</Data>

A: You were on the right track, but it seems that you may not quite understand what the context node for a matched template is, and how to use an XPath that is relative from that node.
When the template matches on an /x:Data/x:Entities/x:Entity element, any of the XPath expressions inside of that template will be relative from that element.
If there are multiple x:Entity elements, that template will fire multiple times; once for each of those elements. So, you would not want to use the xs:for-each that selects all of the /x:Data/x:Entities/x:Entity elements with an XPath that "jumps up" to the top of the XML tree to select all of the x:Entity elements. That would have the effect of making a cartesian product.
Similarly, when selecting the value for the attribute, you want to use an XPath that selects the Attribute element relative from the context node (the x:Entity that was matched by the template).
If the structure of those x:Attributes/x:Attribute elements could be vary (sometimes siblings, sometimes descendants), you could use a more generic XPath to select from any of it's descendants with a more generic XPath that filters by the @name: .//x:Attributes/x:Attribute[@Name = 'A-AssetFileName']/x:Values/x:Value
Applying changes to your stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:x="http://schemas.riversand.com/mdmcenter">
    <xsl:output omit-xml-declaration="yes" indent="yes" encoding="UTF-8"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/x:Data/x:Entities/x:Entity">

        <xsl:copy> <!--copy the matched Entity-->
            <xsl:apply-templates select="@*"/> <!--preserve existing attributes-->

            <xsl:attribute name="ProductImage">
                <!--Sele the attribute value using a relative path from the matched Entity -->
                <xsl:value-of select="x:Attributes/x:Attribute/x:Attributes/x:Attribute/x:Attributes/x:Attribute[@Name = 'A-AssetFileName']/x:Values/x:Value"/>
<!--If you aren't sure what the nesting structure of the Attributes will be,
    then just use the descendant axis to look down as many levels as it needs to find it
                <xsl:value-of select=".//x:Attributes/x:Attribute[@Name = 'A-AssetFileName']/x:Values/x:Value"/>
-->
            </xsl:attribute>

            <!--if you don't want to preserve the Attribute elements, remove the line below -->
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


text:
Q: dialog - user input must be alphanumeric and an underscore only I am using dialog to take some inputs from the user to variables, my problem that in my current script users can enter any values which cause problems. So I would like to put rules for the input to have only alphanumeric and an underscore.
#!/bin/sh
# The Dialog Menu
while true; do
  menu="$(dialog --title "bhyve" --backtitle "bhyve, the BSD hypervisor" \
          --stdout --nocancel --menu "Select your OS:" 0 0 0 \
          1 "FreeBSD 12.2" 2 "Exit")"
  if [ "${menu}" -eq 1 ]; then
    while true; do
      if dialog --title "FreeBSD" --stdout --nocancel --inputbox "The VM name:" 0 0 FreeBSD \
          --and-widget --title "FreeBSD" --nocancel --inputbox "RAM (GB):" 0 0 8 \
          --and-widget --title "FreeBSD" --nocancel --inputbox "CPUs:" 0 0 2 \
          --and-widget --title "FreeBSD" --nocancel --inputbox "Disk size (GB):" 0 0 32 > output.txt; then
      name="$(< output.txt awk '{print $1}')"
      ram="$(< output.txt awk '{print $2}')"
      cpu="$(< output.txt awk '{print $3}')"
      disk="$(< output.txt awk '{print $4}')"
      vmd="/zroot/VMs"
      freebsd_iso="/zroot/VMs/ISOs/FreeBSD-12.2-RELEASE-amd64-disc1.iso"
      if [ ! -d "${vmd}" ]; then
        dialog --title "bhyve" --backtitle "bhyve, the BSD hypervisor" \
        --msgbox "/zroot/VMs directory does not exist, please run Setup first" 5 65
        rm output.txt
        exit
      elif [ ! -f "${freebsd_iso}" ]; then
        #pkg install ca_root_nss
        fetch -o /zroot/VMs/ISOs https://download.freebsd.org/ftp/releases/amd64/amd64/ISO-IMAGES/12.2/FreeBSD-12.2-RELEASE-amd64-disc1.iso
      elif [ -f "/usr/local/etc/rc.d/${name}" ]; then
      dialog --title "bhyve" --backtitle "bhyve, the BSD hypervisor" \
        --msgbox "The VM ${name} already exists, please choose another name" 5 65
        break;
      fi
      freebsd > /dev/null 2>&1
      dialog --title "bhyve" --backtitle "bhyve, the BSD hypervisor" \
        --msgbox "The VM ${name} has been created" 0 0
        rm output.txt
      else
        rm output.txt
        break;
      fi
    done
  elif [ "${menu}" -eq 2 ]; then
    dialog --title "bhyve" --backtitle "bhyve, the BSD hypervisor" \
    --no-label "Yes" --yes-label "No" \
      --yesno "Would you like to exit?" 0 0
    if [ $? -eq 1 ]; then
      break;
    fi
  fi
done

redpajama_set_name: RedPajamaStackExchange


text:
Q: Install as root? how to install ".sh" files? what does this mean?

rinka@ThinkCentre-M91-RINKA:~/Downloads/xdm-setup-7.2.11$ '/home/rinka/Downloads/xdm-setup-7.2.11/install.sh'
Only root can do this
rinka@ThinkCentre-M91-RINKA:~/Downloads/xdm-setup-7.2.11$ sudo apt-get updates
[sudo] password for rinka:
E: Invalid operation updates
rinka@ThinkCentre-M91-RINKA:~/Downloads/xdm-setup-7.2.11$ '/home/rinka/Downloads/xdm-setup-7.2.11/install.sh'
Only root can do this

A: here is the answer
need to type:
sudo ./install.sh


text:
Q: What are the limited resources in LaTeX/TeX? I heard, that some resources (or maybe all) are limited. The number of lengths seems to be limited to 2^8 (1 byte). Are there any other limited resources and if yes, which are these or where can this be looked up?

A: all registers have a fixed number, counts, lengths, (dimen and skips) boxes there are 2^8 in classic TeX but almost all formats use etex where this is raised to 2^15. xetex also allows 2^15 and luatex 2^16.
Other fixed allocations are math families (16 in classic tex and etex, 256 in luatex and xetex).
The TeXBook or TeX by topic have the details, along with the manuals for etex, xetex or luatex for the extended behaviour.
there are other fixed resourses (other than luatex which uses dynamic memory) total memory, total number of control sequences, etc but these days these limits rarely affect normal documents.


text:
Q: equidivision partition using breadth first search i was trying to solve a breadth first search problem on spoj.the problem statement is as follows:
An equidivision of an n × n square array of cells is a partition of the n^2 cells in the array in exactly n sets, each one with n contiguous cells. Two cells are contiguous when they have a common side.
the problem link is:http://www.spoj.com/problems/EQDIV/
my code:http://ideone.com/OjluJG
#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<queue>
using namespace std;
#define pii pair< int, int>
int n, m, grid[105][105];
char inp[101 * 101];

bool inRange(int i, int j)
{
    m = n;
    return (i >= 0 && i < n && j >= 0 && j < m);
}

int main()
{
    int i, j, comp;
    scanf("%d", &n);
    while (n != 0)
    {
        if (n == 1)
        {
            printf("good\n");
            scanf("%d", &n);
            continue;
        }
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < n; j++)
            {
                grid[i][j] = 0;
            }
        }
        int a, b, start1[n], start2[n], print = 0, c, d;
        queue< pii > Q;
        pii p;
        getchar();
        for (i = 1; i <= n - 1; i++)
        {
            gets(inp);
            stringstream ss(inp);
            for (j = 1; j <= n; j++)
            {
                ss >> a >> b;
                if (j == 1)
                {
                    start1[i - 1] = a;
                    start2[i - 1] = b;
                    //printf("%d %d\n",start1[i-1],start2[i-1]);
                }
                grid[a - 1][b - 1] = i;
            }
        }
        for (int x = 0; x < n; x++)
        {
            int count = 1;
            if (x == n - 1)
            {
                comp = 0;
                p.first = c;
                p.second = d;
                Q.push(p);
            }
            else
            {
                comp = x + 1;
                p.first = start1[x] - 1;
                p.second = start2[x] - 1;
                Q.push(p);
            }
            while (!Q.empty())
            {
                p = Q.front();
                i = p.first;
                j = p.second;
                Q.pop();
                grid[i][j] = -1;
                if (x != n - 1)
                {
                    if (inRange(i + 1, j) && grid[i + 1][j] == 0)
                    {
                        c = i + 1;
                        d = j;
                    }
                    if (inRange(i - 1, j) && grid[i - 1][j] == 0)
                    {
                        c = i - 1;
                        d = j;
                    }
                    if (inRange(i, j + 1) && grid[i][j + 1] == 0)
                    {
                        c = i;
                        d = j + 1;
                    }
                    if (inRange(i, j - 1) && grid[i][j - 1] == x + 1)
                    {
                        c = i;
                        d = j - 1;
                    }
                }

                if (inRange(i + 1, j) && grid[i + 1][j] == comp)
                {
                    p.first = i + 1;
                    p.second = j;
                    Q.push(p);
                    count += 1;
                }
                if (inRange(i - 1, j) && grid[i - 1][j] == comp)
                {
                    p.first = i - 1;
                    p.second = j;
                    Q.push(p);
                    count += 1;
                }
                if (inRange(i, j + 1) && grid[i][j + 1] == comp)
                {
                    p.first = i;
                    p.second = j + 1;
                    Q.push(p);
                    count += 1;
                }
                if (inRange(i, j - 1) && grid[i][j - 1] == comp)
                {
                    p.first = i;
                    p.second = j - 1;
                    Q.push(p);
                    count += 1;
                }
            }
            if (count != n)
            {
                print = 1;
                printf("wrong\n");
                break;

            }
        }
        if (print == 0)
            printf("good\n");
        //printf("%d %d\n",c,d);
        scanf("%d", &n);
    }
}

i am getting wrong answer ,don't know why?
can someone provide the testcase for which it is wrong?


text:
Q: "Magnetic mnemonics" Over and over I'm getting into the same trouble, so I'd like to ask for some help.

*

*I need to solve some basic electrodynamics problem, involving magnetic fields, moving  charges or currents.

*But I forgot all this rules about "where the magnetic field should go if the current flows up". I vaguely remember that it about hands or fingers or books or guns, and magnetic field should go somewhere along something, while current should flow along something else... But it doesn't help, because I don't remember the details.

*I do find some very nice rule and use it. And I think "that one I will never forget".

*...time passes...

*Go to step 1.

The problem is that you have to remember one choice from a dichotomy: "this way or that way". And all the mnemonics I know have the same problem -- I got to remember "left hand or right hand", "this finger or that finger", "inside the book or outside of the book".
Maybe someone knows some mnemonics, that do not have such problem?

A: To get the right answer, you should use the right hand, which happends to be the right hand, it cannot possibly get simpler

A: Dear Kostya, if the electric field is a vector with an arrow, then the magnetic field is fundamentally not a vector: instead, it is an antisymmetric tensor with two indices, determining an "oriented two-plane".
The latter carries the same information (3 different components) as a vector, and there is a convention given by the right-hand rule to switch from one to the other. A derived and related rule also determines the magnetic field of a solenouid and other things.
Clearly, the convention to switch from the antisymmetric tensors to vectors could have been the other way around, too. So one has to remember something to know the convention; one can derive many things but not conventions. I agree that remembering the right hand operations is simple, especially because the word "right" also means "correct" and because the right-wing political opinions are the right ones while the left-wing political opinions are those that are left over.

A: Three points I'll like to address:
1) Use cross product as much as possible. If I give you a and b make sure you know which direction a cross b is pointing in. This is essential for many things beyond EM. Then you can state a law of physics without referring to your left or right hand: for instance the magnetic force on a moving particle is q (v cross B).
Of course to define cross product you might have to use your hand... try to find a definition that involves your right hand (the reason is given later).
2) To find the B field induced by a current point the thumb of your right hand towards the direction of the current. The fingers of your right hand are now curling in a certain direction (counterclockwise if the current is flowing into your face); this is the B field. This is non-negotiable; I'm sorry, the B field is defined such that this is true. And I am pretty certain there is no way of using your left hand to calculate this easily.
3) To find E field induced by changing B field, read up on Lenz's law. If you're OK with the previous two this should be trivial.
Now you should see why I recommended you use right hand to define cross product; you must use your right hand in step 2, so might as well use it in step 1 too.

A: I actually encounter the same problem all the time, but I just save myself by using my right hand. The mnemonic I have been taught for 2 is very, very simple. Just imagine grabbing a wire with your hand so that your thumb is along the direction of current. Now your fingers are curled around it and that's the direction of the magnetic field!
So, if you need to find the direction of current just see the direction of the field and imagine wrapping something with it using your fingers. The direction your thumb points in is the direction of the current.
Oh and can you remember the cases in which the left hand applies? If you do then just use the above rule with your left hand...

A: I'm just making these up as I go because we "always" use the right hand in the sense that our coordinate system (xyz) is always defined by the right hand rule, but:
For the cross-product, such as E = q(v cross B): ROD - right, out, down. If the first quantity (v) points to the right and the second (B) points out of the page, i.e. toward you, then the third (E) points down. I realize that "out" as out of the page may cause some problem, so you could substitute "at," meaning the vector points at you, and use RAD instead. I'd stick with ROD, though, so you don't think the A means "away" a year from now.
For magnetic fields in wires: RAA (think of the music industry). If the current flows to the Right, the magnetic field Above the wire points Away from you. Since you know the magnetic field is a circle around the wire, this establishes the field direction.
This is all for positive charge/current, since that's the physics standard. In both these cases, use the mnemonic to establish the right hand rule and go from there, since that's probably easier than trying the rotate your problem to match the mnemonic.
As one last note, if ROD (right, out, down) and RAA (right, above, away) slip, if you have a coordinate system drawn, x cross y = z will force you to remember it's your right hand to use.

A: I see you don't like the other answers. I don't think anyone can help you and here's why.
In EM there is no way to get around arbitrariness of defining orientation (because the theory is P, as well as C and T symmetric). So you just have to remember the whole set orientation + hand trick. I assume you learned both your first name and the last name and there the arbitrariness is substantially larger than just choosing left or right. So just pick one and stick it into your brain. I hope you can learn a bit (pun intended).
That being said, there might be a loop-hole. You can pick non-chiral theory (weak interactions) which tells you which orientation is "correct" (similarly like matter is more "correct" than antimatter in our universe). Quoting wikipedia on parity violation: "The Standard Model incorporates parity violation by expressing the weak interaction as a chiral gauge interaction. Only the left-handed components of particles and right-handed components of antiparticles participate in weak interactions in the Standard Model." This is a useful piece of information of and by itself, so I hope you don't mind learning it.

A: As with all mnemonics, you just have to try lots until you find one that resonates with you ... Here's mine, I don't know if it will help.
There are 2 "hand" rules for electromagnetism: the left-hand motor rule, and the right-hand current rule.
Left-hand motor rule
The left-hand motor rule shows what happens when a current-carrying wire moves in a magnetic field. Hold the thumb, first and second fingers mutually perpendicular. Then:

*

*The thuMb gives Movement (or equivalently the THumb gives THrust)

*The First finger is the direction of the magnetic Field

*The seCond finger is the direction of the Current

Together these give you the direction of force on a wire when current flows through it in a magnetic field (motor), or the direction of current induced in a wire when the wire moves in a magnetic field (inductor).
Right-hand rule - direction of magnetic field around a wire
Grab the wire with your right hand; the thumb points in the direction of the current, and the fingers curl around in the direction of the magnetic field.
Left or right hand?
Well, I'm left-handed. So I associate the motor rule with my left hand - I do most stuff with my left, which is controlled by my motor neurones. Then the other rule uses the other hand. I accept that may not help if you're right-handed :-)


text:
Q: Hibernate doesn't generate SET fields I made a new project trying to use Hibernate on netbeans IDE.
I'm following the official guide  at this link:
https://netbeans.org/kb/docs/web/hibernate-webapp.html
in order to configure the project.
So, this is my hibernate.cfg.xml file:
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hdemic?zeroDateTimeBehavior=convertToNull</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

This is my Hibernate.reveng.xml file:
<hibernate-reverse-engineering>
    <schema-selection match-catalog="hdemic"/>
    <table-filter match-name="Users"/>
</hibernate-reverse-engineering>

When I go for generate class from POJO, all of my "entity class db" are created with all fields except "Set fields", I mean collection that are generated through relationships that are specified in hbm.xml file(RELATIONSHIPS MISSING!!!).
I have to add some property to my config or revenge xml file?
I try to do the same things with another computer(linux) and all is fine. I also think is problem of my installation or my computer (mac os).
Both has the same installation.
Please help me, thanks all.


text:
Q: Firebase function finishes 1-2 times successfully, then throws error: Cannot modify a WriteBatch that has been committed I use batches to write into firestore and my firebase-functions code always executes successfully on the first attempt.
i  functions: Beginning execution of "myFunction"
i  functions: Finished "myFunction" in ~1s
i  functions: Beginning execution of "myFunction"
   API fetch ...
   Amount of records to process: 3600
   filled batch (amount of writes: 490)
   filled batch (amount of writes: 490)
   ...
   All batches commited to Firebase
   imported batch
   imported batch
   ...
i  functions: Finished "myFunction" in ~33s

The error always occurs on the second OR third execution of the function with the following error message:
Unhandled error Error: Cannot modify a WriteBatch that has been committed.

My approach to use batches consists of two steps.

*

*I create an array with batches and pass 490 writes into each.

*I execute every commit operation within await Promise.all()
I guess that my mistake is inside step 2. I tried promise chaining and async await:
async/await:
try {
    await Promise.all(batches.map(batch => batch.commit()))
    console.log('All batches commited to Firebase')
} catch (error) {
    console.log(error)
}

promise chaining:
await Promise.all(batches.map(batch => {
    return batch.commit().then(function () {
        console.log("imported batch")
    });
}))
    .then(console.log('All batches commited to Firebase'))
    .catch(err => console.log(err))

The batches array itself is being created like this, I call the following function multiple times in a loop:
function useBatches(collectionRef, action, type, docId, data) {

    const docRef = collectionRef.doc(docId);

    switch(action) {
        case 'delete':
            batches[batchIndex].delete(docRef);
            break;
        case 'update':
            batches[batchIndex].update(docRef, data);
            break;
        case 'set':
            batches[batchIndex].set(docRef, data);
            break;
    }
    batchSizeCounter++;
    totalWritesToDo--

    // create batches
    if (batchSizeCounter === BATCH_SIZE) {
        console.log(`filled batch (amount of writes: ${batchSizeCounter})`)
        batches.push(db.batch());
        batchIndex++;
        batchSizeCounter = 0;
    }

    // inform about last batch was filled
    if (totalWritesToDo === 0) {
        console.log(`filled batch (amount of writes: ${batchSizeCounter})`)
        return;
    }
}

I am very thankful for any help!


text:
Q: Adding custom IFrame to Wordress I am creating a website for my movie theatre. We are using a ticketing system that comes with our point of sale to offer sales online. The link is https://ticketing.useast.veezi.com/sessions/?siteToken=pxbww48zebzhba4e6yzr7f01am
I want to have this display on a page in wordpress. I don't want the scroll bar, and I want the height to fit the height of the linked content, without using a scrollbar. So if the website has 20 films with showtimes, I want the user to just scroll down on the webpage to access the info, without having a second scroll bar for the iframe.
I hope this makes sense. Also, I am hoping that there is a html snippet I can add to the page where I do not need to add code to the header to make it work. I don't want to screw around too much with the theme files themselves and this is only for one page. Thanks everyone!


text:
Q: In mysql-connector-python I get an error "Commands out of sync; you can't run this command now" when I run a second query I have this error : "2014 (HY000): Commands out of sync; you can't run this command now"
I use mysql-connector-python~=8.0.31
I connected to the database (from a docker container mariaDB latest)
I have created the cursor cur
I Created 4 tables, and when I want to execute any other command as simple as "select 1;"
I get the same error
from mysql.connector import connect
conn = connect(
    host="127.0.0.1",
    user="usr",
    password="pawrd",
    database="databse",
    port="3306"
)
with open("create_tables.sql") as query:
        cur.execute(query.read(), multi= True) # the sql file has all the create statements in one string

cur.execute("select 1") #ERROR


text:
Q: How to combine rows / add their values according to information in other (data.)table? I have information stored in two data frames / data.tables and I would like to use the information stored in the second one (my lookup table) to add / collapse rows in my first one.
My first data.table looks something like this:
ID    Sample01    Sample02    Sample03
1        1            2           3
2        0            1           2
3        2            0           1
4        5            2           1

My second data.table (distance matrix) looks something like this:
0    12    4    1
12    0    3    5
4     3    0    6
1     5    6    0

I would like to add the values of rows in my first data.table, if the attribute in the second, which displays distances, is smaller than 2.
It should then look like this (rows 1 and 4 are added, as the distance is <2):
ID    Sample01    Sample02    Sample03
1        6            4           4
2        0            1           2
3        2            0           1

As the data is extremely large, I would prefer to work with data.table, but I can also work with other packages, any help is appreciated!
Edit:
This would be a real-world example of table 1 (dput):
structure(list(v_j_cdr3 = c("TCRBV02-01-TCRBJ01-01-SLGGmhcLFF",
"TCRBV02-01-TCRBJ01-01-SLGhLmhcLFF", "TCRBV02-01-TCRBJ01-01-SLLLGchcLFF",
"TCRBV02-01-TCRBJ01-01-SLLmGmhcLFF"), HIP08805 = c(6.4439e-05,
0, 0, 8.69177e-05), HIP17837 = c(6.01681e-05, 0, 0, 0), Keck0006_MC1 = c(2.48385e-05,
4.96771e-05, 0, 0)), row.names = c(NA, -4L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7ffb190066e0>)

This would be a real-world example of table 2 (dput):
structure(list(`1` = c(0, 2, 3, 2), `2` = c(2, 0, 4, 3), `3` = c(3,
4, 0, 2), `4` = c(2, 3, 2, 0)), row.names = c(NA, -4L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7ffb190066e0>)

Edit2 : solution (without deletion of rows as the comments made me realize that I should not do that).
diag(matrix) <- 99
pos <- which(matrix<2,arr.ind = T,useNames = F)
datasubset_raw <- datasubset
for(j in 1:nrow(pos)){datasubset[pos[j,1],] <- datasubset[pos[j,1],]+datasubset_raw[pos[j,2],]}

A: Obviously you should do a loop for all situations on your dataset, but this idea might help you
df1 <- data.frame("ID"=c(1,2,3,4),"Sample01"=c(1,0,2,5),
              "Sample02"=c(2,1,0,2),"Sample03"=c(3,2,0,1))
# df1
#   ID Sample01 Sample02 Sample03
# 1  1        1        2        3
# 2  2        0        1        2
# 3  3        2        0        0
# 4  4        5        2        1
dist_matrix <- matrix(c(0,12,4,1,
                       12,0,3,5,
                       4,3,0,6,
                       1,5,6,0),nrow = 4,ncol = 4)
#> dist_matrix
#     [,1] [,2] [,3] [,4]
#[1,]    0   12    4    1
#[2,]   12    0    3    5
#[3,]    4    3    0    6
#[4,]    1    5    6    0

Lets assume you are not interested in diagonals for the condition, so it should be > 2
diag(dist_matrix) <- 999

Position with distances < 2 (1 and 4)
pos <- which(dist_matrix<=2,arr.ind = T,useNames = F)
# pos
#      [,1] [,2]
# [1,]    4    1
# [2,]    1    4
for(i in 1:nrow(pos)){pos[i,] <- sort(pos[i,])} # sort
# pos
#     [,1] [,2]
#[1,]    1    4
#[2,]    1    4
pos <- unique(pos) # your final vector
#pos
#     [,1] [,2]
#[1,]    1    4

Sum then up
df1[pos[1],2:4] <- df1[pos[1],2:4]+df1[pos[2],2:4]
#df1
#  ID Sample01 Sample02 Sample03
#1  1        6        4        4
#2  2        0        1        2
#3  3        2        0        0
#4  4        5        2        1

Delete 4th position
df1 <- df1[-pos[2],]
# df1
#   ID Sample01 Sample02 Sample03
# 1  1        6        4        4
# 2  2        0        1        2
# 3  3        2        0        0


text:
Q: Unit Test Error: Methods defined as TestMethod do not support Web service callouts Firstly, I know what this message is trying to tell me:

Methods defined as TestMethod do not support Web service callouts

And I believe I have set up all the HttpCalloutMock's correctly, because the other 40 unit tests which failed are now passing.
I have a class/method  MockFactory.create() which creates StaticResourceCalloutMock for the 4 end points I call out to.
@isTest
public class MockFactory {

    public static HttpCalloutMock create() {

        StaticResourceCalloutMock contactMock = getStaticMock(200, 'ContactsMock');
        StaticResourceCalloutMock invoiceMock = getStaticMock(200, 'InvoicesMock');
        StaticResourceCalloutMock creditNoteMock = getStaticMock(200, 'CreditNotesMock');
        StaticResourceCalloutMock paymentMock = getStaticMock(200, 'PaymentsMock');

        Map<String, HttpCalloutMock> mocksMap = new Map<String, HttpCalloutMock>();

        mocksMap.put('https://api.example.com/api/2.0/Contacts', contactMock);
        mocksMap.put('https://api.example.com/api/2.0/Invoices', invoiceMock);
        mocksMap.put('https://api.example.com/api/2.0/CreditNotes', creditNoteMock);
        mocksMap.put('https://api.example.com/api/2.0/Payments', paymentMock);

        HttpCalloutMock mocks = new MultiRequestMock(mocksMap);

        return mocks;
    }

    private static StaticResourceCalloutMock getStaticMock(Integer statusCode, String staticResourceName) {

        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();

        mock.setStaticResource(staticResourceName);
        mock.setStatusCode(statusCode);
        mock.setHeader('Content-Type', 'application/json');

        return mock;
    }
}

And the MultiRequestMock class should throw an error if it trys to do a callout to an endpoint there isn't a mock setup for:
@isTest
public class MultiRequestMock implements HttpCalloutMock {

    Map<String, HttpCalloutMock> requests;

    public MultiRequestMock(Map<String, HttpCalloutMock> requests) {
        this.requests = requests;
    }

    public HTTPResponse respond(HTTPRequest req) {

        HttpCalloutMock mock = requests.get(req.getEndpoint());

        if (mock != null) {
            return mock.respond(req);
        }

        throw new MultiRequestMockException('Mock for end point not found: ' + req.getEndpoint());
    }

    public void addRequestMock(String url, HttpCalloutMock mock) {
        requests.put(url, mock);
    }

    public class MultiRequestMockException extends Exception {}
}

But one set of tests that relate to testing a Schedulable class are all still failing.
What have I tried?
I've tried bypassing the Schedulable class and calling the child directly, and it still does not work.
Before
@isTest
public static void test_inactivePerson()
{
    Test.setMock(HttpCalloutMock.class, MockFactory.create());

    // arrange
    // create some objects...

    // act
    Test.StartTest();
    System.schedule('Test Schedulable', '0 0 23 * * ?', new StatementSchedulable());
    Test.stopTest();

    // assert
}

After
@isTest
public static void test_inactivePerson()
{
    Test.setMock(HttpCalloutMock.class, MockFactory.create());

    // arrange
    // create some objects...

    // act
    Test.StartTest();
    Statements.generate();
    Test.stopTest();

    // assert
}

QUESTION
What else could be caused the error message to be returned?

A: This issue was caused by test data created within the @testSetup method.
An object was being created with a status which was triggering Process Builder to make the call out.
All of this is running before I was calling on the first line of the test method.
Test.setMock(HttpCalloutMock.class, MockFactory.create());

Respect to @NavalSharma


text:
Q: MQ System w/ brokers - Any way to examine everything I have inherited an IMB MQ (V6) system that has multiple brokers.  Is there a way to explore everything succinctly ?
i.e.  I know what queue managers are running, so without "runmqsc"ing each and every manager, how can i find broker names, listeners, etc ?
There is the Explorer running but again points to knowing the manager and port to have it connect successfully.

A: For MQ, the dmpmqcfg command can be useful to output your configuration info to a file.
For the broker, try the mqsilist command to list installed brokers and their associated resources.
this webpage may be of help to you:
Performing health checks for WebSphere Message Broker
http://www.ibm.com/developerworks/websphere/library/techarticles/0801_cui/0801_cui.html

A: To work out which queue managers are running on your machine, use thedspmq command. Then you'll know each queue manager and can runmqsc to each one, or point MQ Explorer to each one, or whatever you need to do next.


text:
Q: How can I combine two images into one image object? How can I combine two images?
I mean I have two images: one small and another big one. I want to add small image onto big one at a specific point and I need to get an UIImage as the result.
I have tried CGCreateImageFromMask but that makes small image to cover bigger image completely.

A: You'll want to use UIGraphicsBeginImageContext() to generate a CGContextRef, then use UIGraphicsGetCurrentContext() to get a reference to it.
Now draw your current images into the context. When you're done, use UIGraphicsGetImageFromCurrentContext() to generate an UIImage from that context, and UIGraphicsEndImageContext() to clean up.
See Apple's UIKit Function Reference doc.


text:
Q: A word's different meanings in a sentence
The image of God is one thing, and that which is contemplated in the image is another.

I'm not sure but it seems the two "image" in the sentence have different meanings from each other. in my opinion one means 'visual appearance' and the other 'impression'. Am I understanding rightly?

A: No it doesn't.
'Image' very probably means the literal, physical picture of God in both cases. In other words:

A picture of God is one thing, and what you are thinking about while looking at the picture is something else.

A: The word "image" means the same thing both times. You're getting confused with the meaning of the sentence and conflating it with the meaning of words within the sentence. A paraphrase of the sentence in question might be "it is one thing to see the image of god, it is another to contemplate it." Notice how the word "image" was only used once in that sentence, yet it means nearly the same thing.
It's also not necessarily true. That sentence could be a lie or opinion; it has no bearing on the meaning of words in the English language. Such a topic is outside the scope of english.stackexchange.

A: It seems to me,
you mean "aura".
According to Oxford English Dictionary
aura
NOUN
The distinctive atmosphere or quality that seems to surround and be generated by a person, thing, or place.


text:
Q: Get the output from python tests in ruby script I have a Python project with some tests in different folders and files. I wanted to write a script which executes all tests for the project and outputs some results. I want it to be a ruby script (because I know Ruby more than Python and for now I enjoy it more) and I was thinking to get the output from the tests and to parse them with ruby and to output something like "48 tests run in total, all ok" instead of the the output from python.
Long story short - I want I way to get the output from python test_something.py in a variable or in a file and I want nothing from it on the screen.
Here are my tries:
tests = Dir.glob("**/test_*")
wd = Dir.pwd

output = ''
tests.each do |test|
  Dir.chdir(File.dirname(test))
  # output += `python #{File.basename(test)}`
  # system("python #{File.basename(test)} >> f.txt")
  Dir.chdir(wd)
end

I tried both things which are commented, but both of them print the result on the standard exit and in the first one output variable is empty, in the second one the file is created but is empty again :(
Any ideas? Thank you very much in advance! :)

A: Use Open3.capture2 as below:
output, _ = Open3.capture2("python #{File.basename(test)")

To write output to a file do as below:
File.write("f.txt", output)

A: The test framework might have send the result to STDERR. Try use Open3.capture3 to capture the standard error.
require 'open3'

...

stdout, stderr, status = Open3.capture3(%{python "#{File.basename(test)}"})

and write the standard output and standard error to the destination:
File.write("f.txt", stdout + stderr)

You may check status.success? to see if you write the external command right. However, the test framework may return non-zero exit code on failed tests. In that case, you should check the stderr to see the actual error output.


text:
Q: Matplotlib error bar, capsize didn't work? I drew a custom error bar for my seaborn barplot because I need to use within-subject error bar. I used:
plt.errorbar([0, 1], [mean1, mean2], yerr = errBar_value,
             elinewidth = 3, ecolor = "k", capsize = 0.5)

Here is the result

How to increase the capsize? I tried different values of capsize but nothing is changed.
Many thanks
Jiajun

A: plt.errorbar([0, 1], [mean1, mean2], yerr = errBar_value,elinewidth = 3, ecolor = "k", capsize = 0.5,fmt=' ')
The fmt statement gets rid of the line. For me it works to put a larger value for capsize to increase its size. I am using python 3.6.1

A: At the end, I did this:
(_, caps, _) = plt.errorbar([0, 1], [ncv['VisualOnly'].mean(), ncme['Mode Explorer'].mean()], yerr = errBar_vo,
             elinewidth = 3, ecolor = "k", fmt = ' ',capsize = 5)
for cap in caps:
    cap.set_color('k')
    cap.set_markeredgewidth(3)

setting the caps manually seems to solve the issue.


text:
Q: React Native 0.56: bundle doesn't produce .meta file - Is it still needed? Seems that the jsbundle.meta is no longer produced when running a build in 0.56 (though main.jsbundle is fine).
Is it needed? What does it do? There is zero documentation on this file.
My build command:
react-native bundle --platform ios --dev false --entry-file index.js --bundle-
output ios/files/main.jsbundle --assets-dest ios/files/

I ran the app with a Release scheme and it failed due to the meta file being declared in XCode "Build Phases > Copy Bundle Resources." Removing it there also solved the issue when jsbundle.meta was not present, but I'm still unsure about removing it.
Any thoughts/experience appreciated.

A: It looks like this was removed from metro a while back. No mention in the release notes about it though. I think there's no need to worry about it.


text:
Q: JS to hide banner only works Firefox I have a problem in a javascript and css also.
I have a video that will only be displayed when you click on 2 ads in sequence.

Game.of.Thrones.S03E06.HDTV.XviD.Dual.Audio.THESPEEDBR.COM

                    <form method="post">
                        <input type="hidden" value="bar" name="foo">
                        <input name="confirm" type="submit" onClick="habilitar('propaganda2');" value="Start Video Now" class="confirm_button" style="width:250px;">
                    </form>

                    <form method="post">

                        <input name="confirm" type="submit" onClick="closead('ad1','url(uploads/snapshots/374f9c59b58f880c5e68762bde43318a.jpg)');" value="Close Ad and Watch as Free User" class="confirm_button" style="width:250px;">
                    </form>
            or Get Pro Account to get rid of the ads

works perfectly in mozilla but not in other browsers, I could not identify the problem.
this my css if someone want to test
html, body {
    background-color:#000;
    margin:0px;
    padding:0px;
    height: 100%;
    width: 100%;
    overflow: hidden;

    font-family:"Lucida Grande","Lucida Sans Unicode","Lucida Sans",Helvetica,Arial,sans-serif;
    font-size:12px;
    line-height:22px;
    background-color:#000;

}

#container {

}

#file_title {
    color:#FFF;
    text-align:center;
    height:20px;
    padding:5px;

}

#file_title a {
    color:#39C;
    text-decoration:none;
    font-weight:bold;
}

#file_title a:hover {
    color:#FFF;
}

#propaganda1 {
    width:100%;
    height:330px;
    text-align:center;
    font-size:12px;
    color:#CCC;
}

#propaganda2 {
    width:100%;
    height:330px;
    text-align:center;
    font-size:12px;
    color:#CCC;
}

#propaganda1 a {
    color:#fff;
    text-decoration:underline;
}

#propaganda2 a {
    color:#fff;
    text-decoration:underline;
}
#propaganda strong {
    display:block;
    padding:5px;
    font-size:16px;
}

#propaganda strong a {
    color:#F60;
}

#propaganda strong a:hover {
    color:#F00;
}

.confirm_button {
    font-weight:bold;
    padding:4px;
    margin:3px auto;

}

#deleted, #disabled {
    width:400px;
    background-color:#000;
    text-align:center;
    color:#FFF;
    font-size:17px;
    padding:130px 10px 130px 10px;
    margin:30px auto;
    border:#CCC 1px solid;
}

#disabled a {
    color:#C00;
    display:block;
    margin:5px;
}
#disabled a:hover {
    color:#900;
}

#password_box {
    width:400px;
    background-color:#000;
    text-align:center;
    color:#FFF;
    font-size:17px;
    padding:110px 10px 110px 10px;
    border:#CCC 1px solid;
    margin:30px auto;
}
img#bg {
    position:absolute;
    z-index:-1;
}

.play_button {
    color:#FFF;
    font-weight:bold;
    line-height:30px;
}
.play_button strong {
    display:block;
    text-align:center;
    width:100px;
    margin:0px auto;
    color:#FFF;
}

.play_button a {
    width:90px;
    height:90px;
    display:block;
    background-image:url(../images/play_button.gif);
    background-repeat:no-repeat;
    background-position:-90px 0;
    margin:auto auto;
}

.play_button a:hover {
    background-position:0 0;
}
.video_player {
    margin:0px auto;
}

.player_hover_ad {
    width:300px;
    height:250px;
    background-color:#FFF;
    text-align:center;
    padding:5px;
    margin:10px auto 10px auto;
    -moz-border-radius:5px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
}

#playdiv {
    width:100%;
    height:360px;
    text-align:left;
    padding:0px;
    color:#FFF;
    position:relative;
    z-index:1;
}

I managed to fix the css, but the javascript does not work. in Chrome does not close when I click the button

A: It's always a good idea to run your js through jslint or jshint when having problems like this - it points out lots of little errors that can cause cross-broswer issues with your JS.
When I give jshint your js:
function closead(a,background) {

    var e = document.getElementById(a);
    var bg = document.getElementById("background");

    bg.style.background = background + " no-repeat";
    bg.style.backgroundSize = "100% 100%";

    if(e.style.visibility == ""){
    e.style.display = "none";
    e.innerHTML="";

    }
}

function habilitar(id,id2){
    var e = document.getElementById(id);
    var d = document.getElementById("body_logo");

    if(e.style.visibility == ""){
    e.style.visibility="hidden";
    e.innerHTML="";
    e.innerHTML

    d.style.visibility== "";
    d.style.visibility="hidden";
    d.innerHTML="";

    jwplayer("container").setup({

    height: "97%",
    width: "100%",
    primary: "flash",

    allowscriptaccess: "always",
    autostart:true,

  playlist: [{
      image: "uploads/snapshots/374f9c59b58f880c5e68762bde43318a.jpg",
    sources: [{
      file: "uploads/374f9c59b58f880c5e68762bde43318a.mp4",
      label: "360p"
    },{
      file: "uploads/374f9c59b58f880c5e68762bde43318a.flv",
      label: "240p"
    }]
  }],
});

    }

}

it gives me this report back:
Errors:

Line 3: var e = document.getElementById(a);

Missing "use strict" statement.

Line 9: if(e.style.visibility == ""){

Expected '===' and instead saw '=='.

Line 18: var e = document.getElementById(id);

Missing "use strict" statement.

Line 21: if(e.style.visibility == ""){

Expected '===' and instead saw '=='.

Line 24: e.innerHTML

Expected an assignment or function call and instead saw an expression.

Line 24: e.innerHTML

Missing semicolon.

Line 26: d.style.visibility== "";

Expected '===' and instead saw '=='.

Line 26: d.style.visibility== "";

Expected an assignment or function call and instead saw an expression.

Line 30: jwplayer("container").setup({

'jwplayer' is not defined.

Line 1: function closead(a,background) {

'closead' is defined but never used.

Line 17: function habilitar(id,id2){

'habilitar' is defined but never used.

Line 17: function habilitar(id,id2){

'id2' is defined but never used.

I suggest you fix those errors and see if that solves your problem.


text:
Q: Grails v3.3.9 GORM defect - one to many with mappedBy, updates can be made to fail Grails v3.3.9 - impacts live/dev and integration test
My scenario is that I had an integration test that kept failing when building a manually created record and one found from DB, but works if you link two manually created records in the test.
I have been trying a thousand tweaks and make sure GORM was doing what it said in docs.
I've pared my code right back and built something simpler that looks structurally like my real stuff but is based on the Airport/Flights model in the GORM user guide (see section 5.1.2 in user guide)
Declare abstract base class like this
Airport.groovy
abstract class Airport{

    String name
    Collection<? extends Flight> outboundFlights = []
    Collection<? extends Flight>  inboundFlights = []

    static hasMany = [outboundFlights:Flight, inboundFlights:Flight]

    static mappedBy = [outboundFlights: 'departureAirport', inboundFlights: 'arrivalAirport']

    static constraints = {
        outboundFlights nullable:true
        inboundFlights nullable:true
    }

    static mapping = {
        tablePerHierarchy false  //multiple tables+joins
    }
}

The declare a concrete class that extends this, that you can use:
UkAirport.groovy
class UkAirport extends Airport {

    String shortCode = "dont know"

    static constraints = {
    }
}

Declare Flight entity with two properties of essentially the same type
class Flight<A extends Airport> {

    String flightCode = "unassigned"

    A departureAirport
    A arrivalAirport

    //setup belongs to
    static belongsTo = [departureAirport:Airport, arrivalAirport:Airport]

    static constraints = {
    }
}

Now here's the integration test; there's a couple of things to note.
1) I precreate an UkAirport in setup (no flights declared for it)
2) I create two manual UkAirports in the actual test - Gatwick and Stansted and save these
3) I set up two flights - one from Gatwick to Stansted, and flight2 from Gatwick to pre-saved Manchester that I find by doing  UkAirport.get()
Here's the weird thing.  If I run this test as shown here - it will pass because I assert that there are no existing flights to Manchester (assert manchester.inboundFlights.size() == 0).
However if you comment that assert out, and re-run, the test will fail and it will declare that manchester.inboundFlights.size() equals 2 -
It's the same if I'm using the debugger - if stop and look at Manchester before I do the flights2.save() the test will work - if you set the break point after the flights2.save() the manchester.inboundFlights shows 2 entries which is wrong.
class AirportIntegrationSpec extends Specification {

    def setup() {

        Airport manchester = new UkAirport (name:"Manchester", shortCode:"MAN")
        manchester.save(failOnError:true)

    }

    def cleanup() {
    }

    void "two airports and one flight "() {

        given :

        Airport gatwick = new UkAirport (name:"Gatwick", shortCode:"LGW")
        Airport stansted = new UkAirport (name:"Stansted", shortCode:"STN")
        Airport manchester = UkAirport.get(1L)
        assert manchester.shortCode == "MAN"

        gatwick.save ()
        stansted.save ()

        when:
        Flight flight = new Flight<UkAirport>(flightCode:"F123-LGW-STN")
        gatwick.addToOutboundFlights(flight)
        stansted.addToInboundFlights(flight)
        flight.save (failOnError:true)
        assert gatwick.outboundFlights.size() == 1
        assert gatwick.inboundFlights.size() == 0
        assert stansted.outboundFlights.size() == 0
        assert stansted.inboundFlights.size() == 1

        // -all ok until we get to here  - if you evaluate manchester before you use it - test works
        //if you comment out and use before you evaluate it fails !
        assert manchester.inboundFlights.size() == 0  //comment out makes test fail !
        Flight flight2 = new Flight<UkAirport>(flightCode:"F789-LGW-MAN")
        gatwick.addToOutboundFlights(flight2)
        manchester.addToInboundFlights(flight2)
        flight2.save (failOnError:true)
        assert gatwick.outboundFlights.size() == 2
        assert manchester.inboundFlights.size() == 1

        then :""
        flight.id == 1
        flight2.id == 2
        gatwick.inboundFlights.size() == 0
        gatwick.outboundFlights.size() == 2
        stansted.outboundFlights.size() == 0
        stansted.inboundFlights.size() == 1
        flight.departureAirport.name == "Gatwick"
        flight.arrivalAirport.name == "Stansted"

        flight2.departureAirport.name == "Gatwick"
        flight2.arrivalAirport.name == "Manchester"

    }
}

Could someone confirm that this really is a defect and I'll get it raised (the temporary work around in code - is to access the entity selected from the db  - before you then build any relationships around it).
My Github project is here and integration test for all this is here.
This is my previous related Stack Overflow question - which I'll update as its essentially boiled down to the above.


text:
Q: Normalizing product of features Lets say we have two features x1 and x2 . lets say we do following:

*

*x1: Min Max scaling , x2: Min Max scaling

*x1: Min Max scaling , x2: Z score scaling

*x1: Z score scaling , x2: Z score scaling
Now, if we have feature y = x1*x2, what would be the ways to normalize this product feature, based on normalization of individual features. I could treat "y" as a  feature and normalize as needed, but is there some theory/discussion behind normalizing it from knowing the normalization of individual features.

sedy


text:
Q: Valor en concreto dentro de un array Tengo un dilema al imprimir una variable, verán, esta es mi consulta en SQL:
SELECT MONTH(fecha_del_deposito) AS mes, SUM(importe) as monto FROM pago_cliente

Y arroja lo siguiente:

La cual pase a consulta en php:
'cantidadPagos'  => $this->Backend_model->rowCountPagos("pago_cliente"),

public function rowCountPagos($tabla)
{
   $this->db->select("MONTH(fecha_del_deposito) as mes, SUM(importe) as monto");
    $this->db->from($tabla);
    $resultados = $this->db->get();
    return $resultados->result();
}

Si lo imprimo con print_r da como resultado esto:
Array ( [0] => stdClass Object ( [mes] => 3 [monto] => 3484 ) )

Y necesito imprimir solo el valor de "Monto" (en este caso 3484) pero no hallo la forma adecuada, lo que hago hasta el momento es:
<?php echo $cantidadPagos[1]; ?>

Se que esta completamente mal, pero no se como hacerlo, necesito ayuda.
Gracias

A: Como pudistes observar al hacer print_r a tu variable
Array ( [0] => stdClass Object ( [mes] => 3 [monto] => 3484 ) ), esta lo que contiene
es un arreglo de 1 solo elemento y este es un objeto de tipo stdClass, como no indicastes cual era el nombre
de la variable donde tienes asignado el resultado de tu consulta asumire que se llama $result
$result = [
    'cantidadPagos'  => $this->Backend_model->rowCountPagos("pago_cliente"),
]

Ahora si quieres imprimir solo el monto:
$pagos = $result['cantidadPagos'];
echo $pagos[0]->monto;

//O si no te enredas con los []
echo $result['cantidadPagos'][0]->monto;

Los objetos de stdClass en realidad es la manera de representar un arreglo como una instancia de una clase
, para acceder a sus llaves debes usar el operador flecha -> pues se convierten en propiedades


text:
Q: iOS app that checks for duplicate profiles I want to create an iOS app which should load profiles from an XML file on the web, check for duplicates and eliminate them. I use NSXMLParser to parse the profiles from the XML file but now I am confused about how to check for duplicates. The eliminated profiles should be shown in a UITableView.
Any idea or help would be appreciated!
<profiles>

    <profile>
    <firstname>Amin</firstname>
    <lastname>Ziarkash</lastname>
    <address>Melisstokelaan</address>
    <zipcode>2541GH</zipcode>
    <city>DenHaag</city>
    <email>a.ziarkash@hotmail.com</email>
    </profile>

    <profile>
    <firstname>Niko</firstname>
    <lastname>DeVries</lastname>
    <address>Sterrelaan</address>
    <zipcode>3342JH</zipcode>
    <city>Amsterdam</city>
    <email>niko@hotmail.com</email>
    </profile>

    <profile>
    <firstname>Marcel</firstname>
    <lastname>Janssens</lastname>
    <address>Voorhoeveweg</address>
    <zipcode>6006SV</zipcode>
    <city>Weert</city>
    <email>marcel.j@hotmail.com</email>
    </profile>

    <profile>
    <firstname>Amin</firstname>
    <lastname>Ziarkash</lastname>
    <address>Melisstokelaan</address>
    <zipcode>2541GH</zipcode>
    <city>DenHaag</city>
    <email>a.ziarkash@hotmail.com</email>
    </profile>

</profiles>

A: Try like this for parsing your XML, once you parsed then filter it accordingly:-
-(IBAction)test:(id)sender
{
    self.mutableArr=[[NSMutableArray alloc]init];
    NSURL *url = [[NSURL alloc]initWithString:@"file:///Users/XYZ/Desktop/test.xml"];//this is your xml file url
    NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
    [parser setDelegate:self];
    BOOL par=[parser parse];
    NSLog(@"par=%d",par);
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{

          if ([elementName isEqualToString:@"firstname"])
          {
              self.elementNm=elementName;
          }
         if ([elementName isEqualToString:@"lastname"])
         {
             self.elementNm=elementName;
         }
    if ([elementName isEqualToString:@"address"])
    {
        self.elementNm=elementName;
    }
    if ([elementName isEqualToString:@"zipcode"])
    {
        self.elementNm=elementName;
    }
    if ([elementName isEqualToString:@"city"])
    {
        self.elementNm=elementName;
    }
    if ([elementName isEqualToString:@"email"])
    {
        self.elementNm=elementName;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
          {
              if ([elementName isEqualToString:@"profiles"])
              {
                  NSLog(@"rootelement end");
              }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([string rangeOfString:@"\n"].location== NSNotFound)
    {
    if (string.length > 0)
    {
       self.mutableDict=[[NSMutableDictionary alloc]init];
        [self.mutableDict setObject:string forKey:self.elementNm];
        [self.mutableArr addObject:self.mutableDict];

    }
    }
}

//Now filtered you array after parsing xml
-(IBAction)filterArray:(id)sender
{
    for (NSMutableDictionary *dict in self.mutableArr)
    {
        if ([dict objectForKey:@"zipcode"])
        {
        NSPredicate *pd=[NSPredicate predicateWithFormat:@"(zipcode == %@)", [dict objectForKey:@"zipcode"]];
         [self.mutableArr filterUsingPredicate:pd];
        }
    }
}

A: you can use this nice class extension
https://github.com/nicklockwood/XMLDictionary
NSDictionary *dict = [NSDictionary dictionaryWithXMLData:data];

You can then map those dictionaries into your own custom class


text:
Q: Where is the java.security file located on Windows? I need to locate and edit the java.security file on a Windows 7 host.  Where is it located in a default Oracle JRE installation?

A: For the Oracle JRE, on my Windows 7 system java.security is in the following location:
C:\Program Files\Java\jre7\lib\security

By the way for the JDK, should you need it, it's in:
C:\Program Files\Java\<jdk_version>\jre\lib\security

e.g. C:\Program Files\Java\jdk1.7.0_40\jre\lib\security

A: You should find it in JRE_HOME\lib\security knowing that by default JRE_HOME should be c:\Program Files\Java\jre${version-id}

A: https://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html
Policy file locations are specified in the security properties file, which is located at
    java.home/lib/security/java.security  (Solaris/Linux)
    java.home\lib\security\java.security  **(Windows)**


text:
Q: Publish custom web-service on JBoss SOA I'm hitting a wall with this, currently I have two web-service endpoints configured and running in JBoss Soa 5 and as in ESB standard every endpoint is published as an individual operation.
One end-point for transaction submission:
<service description="writes Transactions to DB." name="TransactionsSubmit">
      <listeners>
        <jms-listener busidref="transactionSubmitChannel" name="transactionSubmit" />
            </listeners>
    <actions faultXsd="/resources/xsd/transactions-fault.xsd"
        inXsd="/resources/xsd/ws-submit-trx.xsd"
        mep="RequestResponse"
        outXsd="/resources/xsd/ws-trx-response.xsd">
        <action     class="org.timo.service.SubmitTransaction">
        </action>
    </actions>
</service>

and other for error submission:
<service description="writes errors to DB." name="ErrorsSubmit">
      <listeners>
        <jms-listener busidref="errorSubmitChannel" name="errorSubmit" />
            </listeners>
    <actions faultXsd="/resources/xsd/transactions-fault.xsd"
        inXsd="/resources/xsd/ws-errorsubmit-trx.xsd"
        mep="RequestResponse"
        outXsd="/resources/xsd/ws-errorsubmit-response.xsd">
        <action     class="org.timo.service.SubmitError">
        </action>
    </actions>
</service>

What I want to do is to create a custom web-service using my own WSDL file to publish these two operations in a single proxy service redirecting the flows to the already defined services ErrorsSubmit and TransactionsSubmit.
It's possible to do this?
Note: I could deploy my own WSDL service by adding a WAR application to the ESB package, but I can't redirect the flow to the internal services.

A: I believe all you need is a content based router with soap clients.

A: After several weeks I could find the way to do it. By default there is not a configurable way to redirect from a WS-operation to an ESB-service, but you can do it programmatically.
This is the WS-operation:
public Response submitTransaction(final TransactionRequest request) throws CommonFault {
        log.info("submitTransaction : "+ request.getId());
        JAXBElement<TransactionResponse> response = invokeService("TransactionsSubmit", objectFactory.createSubmitTransactionRequest(request));
        return response.getValue();
    }

private <T> JAXBElement<T> invokeService(final String serviceName, final JAXBElement<?> request) {
        log.info("Invoking service : " + serviceName + "()");
        JAXBElement<T> response = null;
        try {
            ServiceInvoker serviceInvoker = new ServiceInvoker("myservice", serviceName);
            Message message = org.jboss.soa.esb.message.format.MessageFactory.getInstance().getMessage();

            message.getBody().add(jaxbHandler.serialize(request));
            Message esbResponse = serviceInvoker.deliverSync(message, 5000);
            log.info("Response : " + esbResponse.getBody().get().toString());

            response = deserialize(esbResponse.getBody().get().toString());
        } catch (Exception e) {
            log.error(e, e);
        }
        return response;
}


text:
Q: Convert MySQL to pdo statement with json I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error.  I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/**  Function to Add Product  **/

function add_product() {
    $data = json_decode(file_get_contents("php://input"));
    $prod_name      = $data->prod_name;
    $prod_desc      = $data->prod_desc;
    $prod_price     = $data->prod_price;
    $prod_quantity  = $data->prod_quantity;

    print_r($data);

    $qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
   $qry_res = mysql_query($qry);
    if ($qry_res) {

     $arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
        $jsn = json_encode($arr);
        // print_r($jsn);
    }
    else {
        $arr = array('msg' => "", 'error' => 'Error In inserting record');
        $jsn = json_encode($arr);
        // print_r($jsn);
    }
}

/**  Function to Get Product  **/

function get_product() {
    $qry = mysql_query('SELECT * from product');
    $data = array();
    while($rows = mysql_fetch_array($qry))
    {
        $data[] = array(
                    "id"            => $rows['id'],
                    "prod_name"     => $rows['prod_name'],
                    "prod_desc"     => $rows['prod_desc'],
                    "prod_price"    => $rows['prod_price'],
                    "prod_quantity" => $rows['prod_quantity']
                    );
    }
    print_r(json_encode($data));
    return json_encode($data);
}

what I tried and I get no data inserting
/**  Function to Add Product  **/

function add_product() {
    $data = json_decode(file_get_contents("php://input"));
    $prod_name      = $data->prod_name;
    $prod_desc      = $data->prod_desc;
    $prod_price     = $data->prod_price;
    $prod_quantity  = $data->prod_quantity;

    print_r($data);

$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";

$q = $conn->prepare($qry);

$q->execute(array(':prod_name'=>$prod_name,
                  ':prod_desc'=>$prod_desc,
                  ':prod_price'=>$prod_price,
                  ':prod_quantity'=>$prod_quantity,
));

 $qry_res = mssql_query($qry);
    if ($qry_res) {

     $arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
        $jsn = json_encode($arr);
        // print_r($jsn);
    }
    else {
        $arr = array('msg' => "", 'error' => 'Error In inserting record');
        $jsn = json_encode($arr);
        // print_r($jsn);
    }
}

db setup
    <?php

      /****** Database Details *********/

        $host      = "localhost";
        $user      = "root";
        $pass      = "";
        $database  = "shopping";
        $con       = mysql_connect($host,$user,$pass);

        if (!$con) {
            die('Could not connect: ' . mysql_error());
        }

        //echo 'Connected successfully';

        mysql_select_db($database,$con);

        /*******************************/

?>


text:
Q: SCNText Not Displaying I have the following code in my SceneKit application but for some reason the text never shows up on the screen.
 let text = SCNText(string: item.label, extrusionDepth: 4.0)
            text.firstMaterial?.diffuse.contents = UIColor.white
            text.font = UIFont(name: "Arial", size: 35)

            let textNode = SCNNode(geometry: text)
            textNode.position = SCNVector3(-0.2 + x, -0.9 + delta, -1)

            self.node.addChildNode(textNode)

A: Instead of using .font, try using .scale. Even a 1 for font is still a meter tall, so scaling it down might be needed. This worked for me: textNode.scale = SCNVector3(0.01,0.01,0.01)

A: With a size of 35, that text will be huge. It's not 35 points tall, but 35 SceneKit units tall. It's quite possible that the text is visible, but your camera is peering through a hole in a letter, or the Z limit on your camera is stopping it from rendering.

A: I think there's a bug in how ARKit is transforming SCNText nodes. See these for reference:

*

*https://forums.developer.apple.com/message/235611#235611

*https://forums.developer.apple.com/thread/79715


text:
Q: Error with sharepoint client object model I got the following error while running SharePoint ClientObject Model. I went through my code and checked if I missed any thing to load, but didn't see.
"Process is Terminated: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."
I am not sure what I am missing after searching about this for a couple of hour.
The following is my code. Hope any one can help.
    public static void UpdatePackageStatus(string Teamsite, string Libname, string Packagename, string User, string Password, string Domain, string PackageStatus, string DeploymentSucceeded, string query)
        {
            using(clientOM.ClientContext Ctx = new clientOM.ClientContext(Teamsite))
            {

                Ctx.Credentials = new System.Net.NetworkCredential(User, Password, Domain);
                clientOM.Web Web = Ctx.Web;
                Ctx.Load(Web);
                Ctx.ExecuteQuery();

                clientOM.List list = Web.Lists.GetByTitle(Libname);
                Ctx.Load(list);
                Ctx.ExecuteQuery();

                clientOM.CamlQuery CamlQuery = new clientOM.CamlQuery();
                CamlQuery.ViewXml = query;

                clientOM.ListItemCollection Items = list.GetItems(CamlQuery);
                Ctx.Load(Items);
                Ctx.ExecuteQuery();

                if(Items.Count > 0)
                {
                    clientOM.ListItem Item = Items.GetById(Items[0].Id);;
                    Ctx.Load(Item);
                    Ctx.ExecuteQuery();
                    if(Item.DisplayName == Packagename)
                    {
                    Item[PackageStatus] = DeploymentSucceeded;
                    Item.Update();
                    Ctx.ExecuteQuery();
                    }
                }
            }
        }

A: All used fields like DisplayName, Id and PackageStatus should be specified manually. You can use CAML query and write something like this:
string queryText = @"<View>
    <Query>
        <Where>
        <Eq>
            <FieldRef Name='{0}'/>
            <Value Type='Text'>{1}</Value>
        </Eq>
        </Where>
    </Query>
    </View>";
CamlQuery query = new CamlQuery();
query.ViewXml = string.Format(queryText, 'DisplayName', Packagename); //FieldRef = internal field name
ListItemCollection listItems = list.GetItems(query);
Ctx.Load(listItems, items => items.Include(item => item[PackageStatus]);
Ctx.ExecuteQuery();
if (listItems.Count > 0)
{
    listItems[0][PackageStatus] = DeploymentSucceeded;
    Item.Update();
    Ctx.ExecuteQuery();
}

A: I see a fix.
Instead of using Item.DisplayName, I can use File object. It works when I use File and instantiating it by load(File) like other  property.
    clientOM.File file = Item.File;
    Ctx.Load(file);
    Ctx.ExecuteQuery();

    if(file.Name == Packagename)
    {
    Item[PackageStatus] = DeploymentSucceeded;
    Item.Update();
    Ctx.ExecuteQuery();
    }


text:
Q: knife(chef) - is it possible to get the instructions for a recipe in a specific format? thanks in advance for the help!
when I use the following knife command:
knife cookbook show my_cookbook its_version recipes recipe_name -F json/yaml

I just get the raw data, not in a json/yaml format.
I was wondering if there was a way for me to get this data in a specific format without having to write a script to convert everything...
And, if there's no way to do that through command line, do you guys know any python script/library that would help me convert this data in json/yaml?
Thanks again!

A: The instructions are the Ruby source code of the recipe, that's all there is. Chef does actually run that code as part of the execution, you cannot convert a Chef recipe to static data in the general case.


text:
Q: Programmatically discover which columns in excel sheet are raw data and which a function of other columns I have an excel sheet, which has different tabs, and each one different columns. Some of the columns are raw data, and some are functions combining other columns, either from the same tab or different tabs. I was wondering if there is a programmatic way of obtaining which columns are raw data and which are functions of other columns. In this way I can be able to extract a computation graph for every column in the excel sheet.
Thanks in advance,
Alejandro


text:
Q: skypeFailed to execute Skype backend request CreateThreadRequest: Can't create new Teams Channel via I've created many Teams channels with Graph without any problems. Now after a few weeks of successful use, my application stopped working at this feature. I called the API with Graph Explorer and it comes up with the same error:
POST:
/beta/groups/{groupid}/team/channels

REQUEST:
{
  "displayName": "Test112",
  "description": "Test1142"
}

RESPONSE:
{
  "error": {
    "code": "GeneralException",
    "message":
      "Channel thread creation failed for team thread id 19:7f795d63412840318ead600f45dd4dac@thread.skypeFailed to execute Skype backend request CreateThreadRequest.",
    "innerError": {
      "request-id": "a56cd318-87bf-4393-994f-bcd46e0c00b3",
      "date": "2018-06-18T06:12:35"
    }
  }
}

I am member and owner of the team/group. I tried it for many other teams. The behavior is very irregular: Sometimes it works, sometimes it works only after waiting some time and trying again.
Has anyone an idea, why this happens? Currently, I can't understand the problem or the pattern behind this issue.


text:
Q: How to get the state of a Checkbutton in python? I am working on my school project and I am stuck with one thing that is how to get the states of the checkbuttons. I used for loop to create the checkbuttons as there are many checkbuttons. I just don't know how to get the state of the checkbuttons.
Here 'entry1' refers to a list which is needed to input by the user and active_state will store the active state of the checkbuttons.
        active_state=[]
        for i in range (0,len(entry1)):
                    var=IntVar()
                    check_btn=ttk.Checkbutton(update_record_window,text=entry1[i])
                    check_btn.grid(column=0,row=1+i)
                    active_state.append(var)
        print(active_state)

Please if anybody can tell me what I am doing wrong, it would be very grateful of you. Thanks in advance for the help.

A: You need to associate the variable created in the loop with the checkbutton. Then it's just a matter of iterating over the variables and getting the values.
var=tk.IntVar()
check_btn=ttk.Checkbutton(..., variable=var)
...
print([var.get() for var in active_state])

Of course, you need to wait until the user has had a chance to interact with the checkbuttons before printing. Usually that means to put the print statement in a function that is called in response to an event.