问:
reading REALLY complex XML (up to 10 level)
First off, sorry for my English, it's not my first language. So basically I'm developing a web application for our e-commerce company. I'm using Amazon API to get data. And these are in XML files.. I have never really worked with XML before, so I've been trying to learn but everything I found on the internet is for basic xml documents. Like 2-3 level deep and can be read easily by using simple foreach. I have tried to use foreach for this kind of document and I got lost in the code. I want to create an instance of a class by using this data. This example has only one product(product tag) and 10 offers(LowestOfferListings tag) for this product.

What should I use in my code to read every element and create instances?

I'm using C#

One response (GetLowestOfferListingsForASINResponse) can have up to 20 result (GetLowestOfferListingsForASINResponse)

a product (Product) may or may NOT have an offer (LowestOfferListings) but it has (Identifiers) for sure.

P.S. Closing tag for GetLowestOfferListingsForASINResponsedoes not show up in the codeblock below. I have no idea why. But there is a closing tag at the end

Here is a basic response using amazon API;

```<code><GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <GetLowestOfferListingsForASINResult ASIN="ASIN_VALUE" status="Success">
    <AllOfferListingsConsidered>False</AllOfferListingsConsidered>
    <Product>
        <Identifiers>
            <MarketplaceASIN>
                <MarketplaceId>MARKETPLACE_ID_VALUE</MarketplaceId>
                <ASIN>ASIN_VALUE</ASIN>
            </MarketplaceASIN>
        </Identifiers>
        <LowestOfferListings>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>80-89%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>190758</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.74</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.74</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Amazon</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>98-100%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>226962</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.50</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.50</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>90-94%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>3</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>827887</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.68</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.68</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>False</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>9606</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>34.53</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.54</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>80-89%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>457149</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.04</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>36.05</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>473643</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.05</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.05</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>90-94%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>127</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>41.99</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>38.00</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>1141</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>42.38</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>38.39</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>359758</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>43.09</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>43.09</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>98-100%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>5876</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>46.18</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>46.18</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>Unknown</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
        </LowestOfferListings>
    </Product>
</GetLowestOfferListingsForASINResult>
</code>```

答:
I going to try to give you the complete answer.  There are many ways of parsing xml.  The best method depends on a lot of factors including number of tags in the xml file.  You have a standard xml response from amazon that contains lots of tags.  In this case writing a custom parse doesn't make a lot of sense.

So best method in this case is to use existing info from amazon.  So see amazon webpages

1) Documentation for response
https://docs.developer.amazonservices.com/en_UK/products/Products_GetLowestOfferListingsForASIN.html

2) Schema

http://g-ecx.images-amazon.com/images/G/01/mwsportal/doc/en_US/products/ProductsAPI_Response.xsd

Since there is an existing schema for response there are tools that will take the schema and create c# classes.  One you have the classes you can use xml serialization/de-serialization to read/write xml data.

MSDN has a tool see : https://learn.microsoft.com/en-us/dotnet/framework/serialization/xml-schema-definition-tool-xsd-exe

Here is sample code I wrote to serialize and de-serialize xml

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.IO;

namespace XMLSerialize
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            AppConfig config = new AppConfig();
            config.Charts = new List<ChartGeneric>();
            Pie newPie = new Pie();
            config.Charts.Add(newPie);
            newPie.Attribute3 = "abc";

            StackedBar newStack = new StackedBar();
            config.Charts.Add(newStack);
            newStack.Attribute1 = "ghi";
            newStack.Attribute2 = "jkl";

            XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));

            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, config);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            GetConfig(FILENAME);
        }
        public static AppConfig GetConfig(String filepath)
        {
            XmlSerializer xs = new XmlSerializer(typeof(AppConfig));
            XmlTextReader reader = new XmlTextReader(filepath);
            AppConfig configData = (AppConfig)xs.Deserialize(reader);
            return configData;
        }
    }
    [Serializable, XmlRoot("Configuration")]
    public class AppConfig
    {

        [XmlArray("Charts")]
        public List<ChartGeneric> Charts;

        [XmlElement("AnotherElement", Form = XmlSchemaForm.Unqualified)]
        public XmlElement[] AnotherElement { get; set; }

        [XmlElement("OneElement", Form = XmlSchemaForm.Unqualified)]
        public XmlElement[] OneElement { get; set; }
    }

    [XmlInclude(typeof(Pie))]
    [XmlInclude(typeof(StackedBar))]
    [Serializable]
    public class ChartGeneric
    {
        public string Attribute1 { get; set; }

        public string Attribute2 { get; set; }
    }
    [Serializable]
    [XmlRoot(ElementName = "Pie")]
    public class Pie : ChartGeneric
    {
        [XmlAttribute]
        public string Attribute3 { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "StackedBar")]
    public class StackedBar : ChartGeneric
    {
        [XmlAttribute]
        public string Attribute4 { get; set; }
    }

}
</code>```

Here is simplified solution for actual xml

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication64
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string xml = File.ReadAllText(FILENAME);
            StringReader reader = new StringReader(xml);

            XmlSerializer xs = new XmlSerializer(typeof(GetLowestOfferListingsForASINResponse));
            GetLowestOfferListingsForASINResponse response = (GetLowestOfferListingsForASINResponse)xs.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "GetLowestOfferListingsForASINResponse", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class GetLowestOfferListingsForASINResponse
    {
        [XmlElement("GetLowestOfferListingsForASINResult")]
        public List<GetLowestOfferListingsForASINResult> getLowestOfferListingsForASINResult { get; set; }
    }
    [XmlRoot(ElementName = "GetLowestOfferListingsForASINResult", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class GetLowestOfferListingsForASINResult
    {
        [XmlAttribute("ASIN")]
        public string ASIN { get; set;}
        [XmlAttribute("status")]
        public string status { get; set; }

        [XmlElement("AllOfferListingsConsidered")]
        public string AllOfferListingsConsidered { get; set; }

        [XmlElement("Product")]
        public Product product { get; set; }
    }
    [XmlRoot(ElementName = "Product", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class  Product
    {
        [XmlElement("Identifiers")]
        public Identifiers identifiers { get; set; }
    }
    [XmlRoot(ElementName = "Identifiers", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class Identifiers
    {
    }
}
</code>```

Body:
First off, sorry for my English, it's not my first language. So basically I'm developing a web application for our e-commerce company. I'm using Amazon API to get data. And these are in XML files.. I have never really worked with XML before, so I've been trying to learn but everything I found on the internet is for basic xml documents. Like 2-3 level deep and can be read easily by using simple foreach. I have tried to use foreach for this kind of document and I got lost in the code. I want to create an instance of a class by using this data. This example has only one product(product tag) and 10 offers(LowestOfferListings tag) for this product.

What should I use in my code to read every element and create instances?

I'm using C#

One response (GetLowestOfferListingsForASINResponse) can have up to 20 result (GetLowestOfferListingsForASINResponse)

a product (Product) may or may NOT have an offer (LowestOfferListings) but it has (Identifiers) for sure.

P.S. Closing tag for GetLowestOfferListingsForASINResponsedoes not show up in the codeblock below. I have no idea why. But there is a closing tag at the end

Here is a basic response using amazon API;

<GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <GetLowestOfferListingsForASINResult ASIN="ASIN_VALUE" status="Success">
    <AllOfferListingsConsidered>False</AllOfferListingsConsidered>
    <Product>
        <Identifiers>
            <MarketplaceASIN>
                <MarketplaceId>MARKETPLACE_ID_VALUE</MarketplaceId>
                <ASIN>ASIN_VALUE</ASIN>
            </MarketplaceASIN>
        </Identifiers>
        <LowestOfferListings>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>80-89%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>190758</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.74</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.74</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Amazon</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>98-100%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>226962</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.50</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.50</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>90-94%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>3</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>827887</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.68</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>31.68</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>False</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>9606</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>34.53</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>30.54</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>80-89%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>457149</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.04</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>36.05</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>473643</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.05</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>40.05</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>90-94%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>2</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>127</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>41.99</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>38.00</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>3-7 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>1141</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>42.38</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>38.39</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>3.99</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>True</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>359758</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>43.09</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>43.09</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
            <LowestOfferListing>
                <Qualifiers>
                    <ItemCondition>New</ItemCondition>
                    <ItemSubcondition>New</ItemSubcondition>
                    <FulfillmentChannel>Merchant</FulfillmentChannel>
                    <ShipsDomestically>Unknown</ShipsDomestically>
                    <ShippingTime>
                        <Max>0-2 days</Max>
                    </ShippingTime>
                    <SellerPositiveFeedbackRating>98-100%</SellerPositiveFeedbackRating>
                </Qualifiers>
                <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
                <SellerFeedbackCount>5876</SellerFeedbackCount>
                <Price>
                    <LandedPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>46.18</Amount>
                    </LandedPrice>
                    <ListingPrice>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>46.18</Amount>
                    </ListingPrice>
                    <Shipping>
                        <CurrencyCode>USD</CurrencyCode>
                        <Amount>0.00</Amount>
                    </Shipping>
                </Price>
                <MultipleOffersAtLowestPrice>Unknown</MultipleOffersAtLowestPrice>
            </LowestOfferListing>
        </LowestOfferListings>
    </Product>
</GetLowestOfferListingsForASINResult>

Body:
I going to try to give you the complete answer.  There are many ways of parsing xml.  The best method depends on a lot of factors including number of tags in the xml file.  You have a standard xml response from amazon that contains lots of tags.  In this case writing a custom parse doesn't make a lot of sense.

So best method in this case is to use existing info from amazon.  So see amazon webpages

1) Documentation for response
https://docs.developer.amazonservices.com/en_UK/products/Products_GetLowestOfferListingsForASIN.html

2) Schema

http://g-ecx.images-amazon.com/images/G/01/mwsportal/doc/en_US/products/ProductsAPI_Response.xsd

Since there is an existing schema for response there are tools that will take the schema and create c# classes.  One you have the classes you can use xml serialization/de-serialization to read/write xml data.

MSDN has a tool see : https://learn.microsoft.com/en-us/dotnet/framework/serialization/xml-schema-definition-tool-xsd-exe

Here is sample code I wrote to serialize and de-serialize xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.IO;

namespace XMLSerialize
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            AppConfig config = new AppConfig();
            config.Charts = new List<ChartGeneric>();
            Pie newPie = new Pie();
            config.Charts.Add(newPie);
            newPie.Attribute3 = "abc";

            StackedBar newStack = new StackedBar();
            config.Charts.Add(newStack);
            newStack.Attribute1 = "ghi";
            newStack.Attribute2 = "jkl";

            XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));

            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, config);
            writer.Flush();
            writer.Close();
            writer.Dispose();

            GetConfig(FILENAME);
        }
        public static AppConfig GetConfig(String filepath)
        {
            XmlSerializer xs = new XmlSerializer(typeof(AppConfig));
            XmlTextReader reader = new XmlTextReader(filepath);
            AppConfig configData = (AppConfig)xs.Deserialize(reader);
            return configData;
        }
    }
    [Serializable, XmlRoot("Configuration")]
    public class AppConfig
    {

        [XmlArray("Charts")]
        public List<ChartGeneric> Charts;

        [XmlElement("AnotherElement", Form = XmlSchemaForm.Unqualified)]
        public XmlElement[] AnotherElement { get; set; }

        [XmlElement("OneElement", Form = XmlSchemaForm.Unqualified)]
        public XmlElement[] OneElement { get; set; }
    }

    [XmlInclude(typeof(Pie))]
    [XmlInclude(typeof(StackedBar))]
    [Serializable]
    public class ChartGeneric
    {
        public string Attribute1 { get; set; }

        public string Attribute2 { get; set; }
    }
    [Serializable]
    [XmlRoot(ElementName = "Pie")]
    public class Pie : ChartGeneric
    {
        [XmlAttribute]
        public string Attribute3 { get; set; }
    }

    [Serializable]
    [XmlRoot(ElementName = "StackedBar")]
    public class StackedBar : ChartGeneric
    {
        [XmlAttribute]
        public string Attribute4 { get; set; }
    }

}

Here is simplified solution for actual xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication64
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string xml = File.ReadAllText(FILENAME);
            StringReader reader = new StringReader(xml);

            XmlSerializer xs = new XmlSerializer(typeof(GetLowestOfferListingsForASINResponse));
            GetLowestOfferListingsForASINResponse response = (GetLowestOfferListingsForASINResponse)xs.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "GetLowestOfferListingsForASINResponse", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class GetLowestOfferListingsForASINResponse
    {
        [XmlElement("GetLowestOfferListingsForASINResult")]
        public List<GetLowestOfferListingsForASINResult> getLowestOfferListingsForASINResult { get; set; }
    }
    [XmlRoot(ElementName = "GetLowestOfferListingsForASINResult", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class GetLowestOfferListingsForASINResult
    {
        [XmlAttribute("ASIN")]
        public string ASIN { get; set;}
        [XmlAttribute("status")]
        public string status { get; set; }

        [XmlElement("AllOfferListingsConsidered")]
        public string AllOfferListingsConsidered { get; set; }

        [XmlElement("Product")]
        public Product product { get; set; }
    }
    [XmlRoot(ElementName = "Product", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class  Product
    {
        [XmlElement("Identifiers")]
        public Identifiers identifiers { get; set; }
    }
    [XmlRoot(ElementName = "Identifiers", Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")]
    public class Identifiers
    {
    }
}


来源: stackexchange

问:
Heroku Postgresql pg:psql No Route to host
For now I am just trying to make the heroku pg:psql command work but my final purpose is to copy a database that I have on my computer (localhost) to the heroku postgresql database with the pg:push command.

For now when I simply try to access the database that I created on heroku, the heroku pg:psql command returns:

```<code>psql: could not connect to server: No route to host
    Is the server running on host "ec*-**-***-***-**.eu-west-1.compute.amazonaws.com" (**.***.***.**) and accepting
    TCP/IP connections on port 5432?
</code>```

postgresql.conf: (the lines are not commented)

```<code>listen_address ='*'
port = 5432
ssl = true
</code>```

and host all all **.***.***.** trust in pg_hba.conf

I also tried to add rules to iptables in order to give access to the database from the host IP address provided by heroku.

I am on a Debian computer, how can I solve this?

答:
psql: could not connect to server: No route to host

It means your PostgreSQL server is not starting up or is starting up on a different port.

Solutions you may try:

Check PostgreSQL service by command ps -ef | grep Postgres.

Check the port which PostgreSQL is listening to by command netstat -tupln | grep Postgres.

Make sure your server enables UDP port because PostgreSQL needs UDP port loopback for stats collector service.

Check the startup logs or database logs at pg_log about the problem.

ContentLicense: CC BY-SA 3.0

Body:
For now I am just trying to make the heroku pg:psql command work but my final purpose is to copy a database that I have on my computer (localhost) to the heroku postgresql database with the pg:push command.

For now when I simply try to access the database that I created on heroku, the heroku pg:psql command returns:

psql: could not connect to server: No route to host
    Is the server running on host "ec*-**-***-***-**.eu-west-1.compute.amazonaws.com" (**.***.***.**) and accepting
    TCP/IP connections on port 5432?

postgresql.conf: (the lines are not commented)

listen_address ='*'
port = 5432
ssl = true

and host all all **.***.***.** trust in pg_hba.conf

I also tried to add rules to iptables in order to give access to the database from the host IP address provided by heroku.

I am on a Debian computer, how can I solve this?


问:
How to remove an element found in an array and shift the array elements to the left?
```<code>int search(int a[]) {

   int i,V,index;
   printf("Enter the element (V),That you want to find:>");
   scanf("%d",&V);

   for (i=0;i<N;i++) {
       if(a[i]==V) {
           V=a[i];
           index=i;
       }
   }
   printf("%d is located in a[%d].",V,index
)
</code>```

答:
If I needed to move everything down the array, I'd use memmove(), carefully.  And zap the vacated element with 0 or some other appropriate value.

```<code>if (index < N-1)
    memmove(&a[index], &a[index+1], ((N-1)-index) * sizeof(a[0]));
array[N-1] = 0;
</code>```

Body:
If I needed to move everything down the array, I'd use memmove(), carefully.  And zap the vacated element with 0 or some other appropriate value.

if (index < N-1)
    memmove(&a[index], &a[index+1], ((N-1)-index) * sizeof(a[0]));
array[N-1] = 0;


问:
How to make a div scrollable using jquery
I have only one list div and I want to make it scrollable. I have seen scrollpane examples, it's great but I am looking for an smaller simpler alternative.

I appreciate any help.

Thanks.

答:
For Future readers ...

If jQuery is must then you can do this by :

```<code>// Any one accordingly ...

$('#yourIdForDiv').attr('overflow','auto');
$('#yourIdForDiv').attr('overflowy','scroll');
$('#yourIdForDiv').attr('overflowx','auto');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For Future readers ...

If jQuery is must then you can do this by :

// Any one accordingly ...

$('#yourIdForDiv').attr('overflow','auto');
$('#yourIdForDiv').attr('overflowy','scroll');
$('#yourIdForDiv').attr('overflowx','auto');


问:
What is the inverse of dctmtx() in matlab
During the stage of compressing an image, the following code is used.

```<code>img = imread('frm001.png');
img=imresize(img,[256 256]);
ycbcr = rgb2ycbcr(img);
y = ycbcr(:,:,1);
proc = dctmtx(8);
</code>```

After this stage, the regular process of quantization, zigzag ordering , RLE and huffman encoding continues.
While decompressing the code, what is the inverse function for dctmtx() used here?

答:
The DCT is calculated as:

```<code>B = D*A*D'
</code>```

where A is the image to be transformed, and D is the result of dctmtx(). The inverse of this is just

```<code>A = D'*B*D
</code>```

Body:
During the stage of compressing an image, the following code is used.

img = imread('frm001.png');
img=imresize(img,[256 256]);
ycbcr = rgb2ycbcr(img);
y = ycbcr(:,:,1);
proc = dctmtx(8);

After this stage, the regular process of quantization, zigzag ordering , RLE and huffman encoding continues.
While decompressing the code, what is the inverse function for dctmtx() used here?

Body:
The DCT is calculated as:

B = D*A*D'

where A is the image to be transformed, and D is the result of dctmtx(). The inverse of this is just

A = D'*B*D


问:
Why my Laravel Application still finding the older database name?
For example, I have DB_DATABASE=new_db in my .env file and the same as the config/database.php file but still showing error of Unknown database: 'older_database_name'. Please help. Thanks.

Anyway I migrated from MAMP to XAMPP..

答:
restart the server if any changes on .env

try php artisan config:cache and php artisan cache:clear


问:
How to get retrieve firebase list based on another observable
I'm still quite confused with observables. They're very complicated.

I'm trying to write a service class that can be used to monitor the logged in user's addresses as an observable list. The problem is I guess the list reference itself changes when a user logs in or logs out.

```<code>export class AddressService {
  user: any;
  addresses$: FirebaseListObservable<Address[]>;

  constructor(private db: AngularFireDatabase, private authService: AuthService) {
    authService.user$.subscribe((user) => {
      this.user = user;
      if (this.user) {
        this.addresses$ = this.db.list(`/users/${this.user.uid}/addresses`);
      } else {
        this.addresses$ = undefined;
      }
    });
  }
}
</code>```

When I try to add a subscriber to the list I'm getting null, because I guess the addresses$ is not defined when it's added because it depends on the logged in user first resolving.

```<code>// in a UI component
ngOnInit() {
  this.addresses = this.addressService.addresses$;
}
</code>```

It's like I need a new observable that emits a new observable list when the user logs in! Was looking at http://reactivex.io/documentation/operators/switch.html - perhaps this could work somehow?

Edited update here
This is what I came up with (just extracted from the class)

```<code>// users can monitor this to get the latest address book.
  addresses$: Observable<FirebaseListObservable<any>>;

  // keeps a reference to the address subject.
  private addressSubject = new BehaviorSubject<any>(Observable.empty());

  constructor(private db: AngularFireDatabase, private authService: AuthService) {
    this.addresses$ = this.addressSubject.asObservable();
    authService.user$.subscribe((user) => {
      this.user = user;
      if (this.user) {
        this.addressSubject.next(this.db.list(`/users/${this.user.uid}/addresses`));
      } else {
        this.addressSubject.next(Observable.empty());
      }
    });
  }
</code>```

答:
So what you want to do, in pseudocode, is this:

First call authService to retrieve the user id.

If the user exist, go and retrieve the addresses in database.

If not, simply return nothing.

Assign the result to addresses$, expose it as an observable.

If you break down the steps like this, then you won't find Observables confusing. As long as you know the method to do each task listed, you are good.

Here is the code:

```<code>export class AddressService {
    user: any;
    addresses$: FirebaseListObservable<Address[]>;

    constructor(private db: AngularFireDatabase, private authService: AuthService) {
        //Step 4: assign the observable back to addresses$
        this.addresses$ =
            //Step 1: first call the auth service
            this.authService.user$.switchMap(user => {
                this.user = user;
                //Step 2: if user exist, call DB service
                if (this.user) {
                    return this.db.list(`/users/${this.user.uid}/addresses`);
                }
                //Step 3: else just return nothing
                else {
                    return Obsevable.empty()
                }
            })
    }
}
</code>```

I have made some inline commments in the code, so that you can compare with the pseudocode.

Body:
I'm still quite confused with observables. They're very complicated.

I'm trying to write a service class that can be used to monitor the logged in user's addresses as an observable list. The problem is I guess the list reference itself changes when a user logs in or logs out.

export class AddressService {
  user: any;
  addresses$: FirebaseListObservable<Address[]>;

  constructor(private db: AngularFireDatabase, private authService: AuthService) {
    authService.user$.subscribe((user) => {
      this.user = user;
      if (this.user) {
        this.addresses$ = this.db.list(`/users/${this.user.uid}/addresses`);
      } else {
        this.addresses$ = undefined;
      }
    });
  }
}

When I try to add a subscriber to the list I'm getting null, because I guess the addresses$ is not defined when it's added because it depends on the logged in user first resolving.

// in a UI component
ngOnInit() {
  this.addresses = this.addressService.addresses$;
}

It's like I need a new observable that emits a new observable list when the user logs in! Was looking at http://reactivex.io/documentation/operators/switch.html - perhaps this could work somehow?

Edited update here
This is what I came up with (just extracted from the class)

// users can monitor this to get the latest address book.
  addresses$: Observable<FirebaseListObservable<any>>;

  // keeps a reference to the address subject.
  private addressSubject = new BehaviorSubject<any>(Observable.empty());

  constructor(private db: AngularFireDatabase, private authService: AuthService) {
    this.addresses$ = this.addressSubject.asObservable();
    authService.user$.subscribe((user) => {
      this.user = user;
      if (this.user) {
        this.addressSubject.next(this.db.list(`/users/${this.user.uid}/addresses`));
      } else {
        this.addressSubject.next(Observable.empty());
      }
    });
  }

Body:
So what you want to do, in pseudocode, is this:

First call authService to retrieve the user id.

If the user exist, go and retrieve the addresses in database.

If not, simply return nothing.

Assign the result to addresses$, expose it as an observable.

If you break down the steps like this, then you won't find Observables confusing. As long as you know the method to do each task listed, you are good.

Here is the code:

export class AddressService {
    user: any;
    addresses$: FirebaseListObservable<Address[]>;

    constructor(private db: AngularFireDatabase, private authService: AuthService) {
        //Step 4: assign the observable back to addresses$
        this.addresses$ =
            //Step 1: first call the auth service
            this.authService.user$.switchMap(user => {
                this.user = user;
                //Step 2: if user exist, call DB service
                if (this.user) {
                    return this.db.list(`/users/${this.user.uid}/addresses`);
                }
                //Step 3: else just return nothing
                else {
                    return Obsevable.empty()
                }
            })
    }
}

I have made some inline commments in the code, so that you can compare with the pseudocode.


问:
How can client send a value to server using SignalR and the server update a model?
If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)

So say we have a simple Model

```<code>public class User
{
    public int UserID { get; set; }

    public string UserName { get; set; }

}
</code>```

And the corresponding View has an input field for the name. The hub is something like

```<code>public class UserHub : Hub
{
    public void UpdateName(string value)
    {
        // now what?

        Clients.All.updateTheViewIfNecessary(string newValue);

    }
}
</code>```

Edit
How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller

```<code>db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
</code>```

答:
For the purpose of this example we will use a JS client to send a model to the Hub and references official documentation at

ASP.NET SignalR Hubs API Guide - JavaScript Client: How to call server methods from the client

Assuming a User Hub on the server

```<code>public interface IUserService {
    bool UpdateName(string userName);
    // Other methods not shown.
}

public class UserHub : Hub {
    private readonly IUserService service;

    public UserHob(IUserService service) {
        this.service = service;
    }

    public void UpdateName(string value) {
        if(value != null) {
            var newValue = value;
            if(service.UpdateName(newValue) == true) {
                Clients.All.updateTheViewIfNecessary(newValue);
            }
        }
    }
}
</code>```

Reference documentation at Dependency Injection in SignalR to understand how to inject dependencies into the hub. In the above UserHub when the message is received, it uses the data in the model to update/persist data via the injected dependency and notifies clients based on the result of that operation. This could allow for long running processes that could later update clients as needed.

A JavaScript client code that invokes the server method (assuming with the generated proxy) would look something like this.

```<code>//This assumes View has an input field for the name
var message = "Test Name";
userHubProxy.server.updateName(message).done(function () {
    console.log ('Invocation of UpdateName succeeded');
}).fail(function (error) {
    console.log('Invocation of UpdateName failed. Error: ' + error);
});
</code>```

The framework will handle whatever model binding needs to be done on the server.

The hub in effect acts as a service endpoint and sends the response of calling the service to all clients connected to it.

ContentLicense: CC BY-SA 4.0

Body:
If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)

So say we have a simple Model

public class User
{
    public int UserID { get; set; }

    public string UserName { get; set; }

}

And the corresponding View has an input field for the name. The hub is something like

public class UserHub : Hub
{
    public void UpdateName(string value)
    {
        // now what?

        Clients.All.updateTheViewIfNecessary(string newValue);

    }
}

Edit
How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller

db.Entry(user).State = EntityState.Modified;
db.SaveChanges();

Body:
For the purpose of this example we will use a JS client to send a model to the Hub and references official documentation at

ASP.NET SignalR Hubs API Guide - JavaScript Client: How to call server methods from the client

Assuming a User Hub on the server

public interface IUserService {
    bool UpdateName(string userName);
    // Other methods not shown.
}

public class UserHub : Hub {
    private readonly IUserService service;

    public UserHob(IUserService service) {
        this.service = service;
    }

    public void UpdateName(string value) {
        if(value != null) {
            var newValue = value;
            if(service.UpdateName(newValue) == true) {
                Clients.All.updateTheViewIfNecessary(newValue);
            }
        }
    }
}

Reference documentation at Dependency Injection in SignalR to understand how to inject dependencies into the hub. In the above UserHub when the message is received, it uses the data in the model to update/persist data via the injected dependency and notifies clients based on the result of that operation. This could allow for long running processes that could later update clients as needed.

A JavaScript client code that invokes the server method (assuming with the generated proxy) would look something like this.

//This assumes View has an input field for the name
var message = "Test Name";
userHubProxy.server.updateName(message).done(function () {
    console.log ('Invocation of UpdateName succeeded');
}).fail(function (error) {
    console.log('Invocation of UpdateName failed. Error: ' + error);
});

The framework will handle whatever model binding needs to be done on the server.

The hub in effect acts as a service endpoint and sends the response of calling the service to all clients connected to it.


问:
I want to get all data in elasticsearch 5.4
I used size :0 in Elasticsearch 2.x but now in Elasticsearch 5.4 this can not be used.

How do I get the same effect as size: 0 in Elasticsearch 5.4 ?

答: The size:0 was deprecated in Elasticsearch 5.x aggregations. You can check https://github.com/elastic/elasticsearch/issues/22136 for workarounds.</p>


问:
Python pandas: pad rows with missing/skipped date
I have the following data frame:

```<code> date        my_count
--------------------------
2017-01-01         6
2017-01-04         5
2017-01-05         3
2017-01-08         8
</code>```

I would like to pad the skipped date with my_count = 0, so the padded data frame will look like:

```<code> date        my_count
--------------------------
2017-01-01         6
2017-01-02         0
2017-01-03         0
2017-01-04         5
2017-01-05         3
2017-01-06         0
2017-01-07         0
2017-01-08         8
</code>```

Except checking the data frame line by line, is there a more elegant way to do this? Thanks!

答:
If values of DatetimeIndex are unique use:

You can use asfreq or reindex by min or max value of index or by first and last (if DatetimeIndex is sorted):

```<code>df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

print(df.asfreq('D', fill_value=0).reset_index())
        date  my_count
0 2017-01-01         6
1 2017-01-02         0
2 2017-01-03         0
3 2017-01-04         5
4 2017-01-05         3
5 2017-01-06         0
6 2017-01-07         0
7 2017-01-08         8

rng = pd.date_range(df.index.min(), df.index.max())
#alternative
#rng = pd.date_range(df.index[0], df.index[-1])
print(df.reindex(rng, fill_value=0).rename_axis('date').reset_index())
        date  my_count
0 2017-01-01         6
1 2017-01-02         0
2 2017-01-03         0
3 2017-01-04         5
4 2017-01-05         3
5 2017-01-06         0
6 2017-01-07         0
7 2017-01-08         8
</code>```

If DatetimeIndex are not unique get:

ValueError: cannot reindex from a duplicate axis

Then need resample with some aggregate function like mean or groupby with Grouper and last replace NaNs by  fillna:

```<code>print (df)
         date  my_count
0  2017-01-01         4 <-duplicate date
1  2017-01-01         6 <-duplicate date
2  2017-01-04         5
3  2017-01-05         3
4  2017-01-08         8

df['date'] = pd.to_datetime(df['date'])

print(df.resample('D', on='date')['my_count'].mean().fillna(0).reset_index())
        date  my_count
0 2017-01-01       5.0
1 2017-01-02       0.0
2 2017-01-03       0.0
3 2017-01-04       5.0
4 2017-01-05       3.0
5 2017-01-06       0.0
6 2017-01-07       0.0
7 2017-01-08       8.0

df = df.set_index('date')
print(df.groupby(pd.Grouper(freq='D'))['my_count'].mean().fillna(0).reset_index())
        date  my_count
0 2017-01-01       5.0
1 2017-01-02       0.0
2 2017-01-03       0.0
3 2017-01-04       5.0
4 2017-01-05       3.0
5 2017-01-06       0.0
6 2017-01-07       0.0
7 2017-01-08       8.0
</code>```

Body:
I have the following data frame:

 date        my_count
--------------------------
2017-01-01         6
2017-01-04         5
2017-01-05         3
2017-01-08         8

I would like to pad the skipped date with my_count = 0, so the padded data frame will look like:

 date        my_count
--------------------------
2017-01-01         6
2017-01-02         0
2017-01-03         0
2017-01-04         5
2017-01-05         3
2017-01-06         0
2017-01-07         0
2017-01-08         8

Except checking the data frame line by line, is there a more elegant way to do this? Thanks!

Body:
If values of DatetimeIndex are unique use:

You can use asfreq or reindex by min or max value of index or by first and last (if DatetimeIndex is sorted):

df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

print(df.asfreq('D', fill_value=0).reset_index())
        date  my_count
0 2017-01-01         6
1 2017-01-02         0
2 2017-01-03         0
3 2017-01-04         5
4 2017-01-05         3
5 2017-01-06         0
6 2017-01-07         0
7 2017-01-08         8

rng = pd.date_range(df.index.min(), df.index.max())
#alternative
#rng = pd.date_range(df.index[0], df.index[-1])
print(df.reindex(rng, fill_value=0).rename_axis('date').reset_index())
        date  my_count
0 2017-01-01         6
1 2017-01-02         0
2 2017-01-03         0
3 2017-01-04         5
4 2017-01-05         3
5 2017-01-06         0
6 2017-01-07         0
7 2017-01-08         8

If DatetimeIndex are not unique get:

ValueError: cannot reindex from a duplicate axis

Then need resample with some aggregate function like mean or groupby with Grouper and last replace NaNs by  fillna:

print (df)
         date  my_count
0  2017-01-01         4 <-duplicate date
1  2017-01-01         6 <-duplicate date
2  2017-01-04         5
3  2017-01-05         3
4  2017-01-08         8

df['date'] = pd.to_datetime(df['date'])

print(df.resample('D', on='date')['my_count'].mean().fillna(0).reset_index())
        date  my_count
0 2017-01-01       5.0
1 2017-01-02       0.0
2 2017-01-03       0.0
3 2017-01-04       5.0
4 2017-01-05       3.0
5 2017-01-06       0.0
6 2017-01-07       0.0
7 2017-01-08       8.0

df = df.set_index('date')
print(df.groupby(pd.Grouper(freq='D'))['my_count'].mean().fillna(0).reset_index())
        date  my_count
0 2017-01-01       5.0
1 2017-01-02       0.0
2 2017-01-03       0.0
3 2017-01-04       5.0
4 2017-01-05       3.0
5 2017-01-06       0.0
6 2017-01-07       0.0
7 2017-01-08       8.0


问:
preventing double clicks on button with ajax call
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.

What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...

答:
If they are clicking fast enough to fire the double click event, return false.

```<code>ondblclick="return false"
</code>```

EDIT: This will not cancel the single click event so problem would still exist.

Body:
If they are clicking fast enough to fire the double click event, return false.

ondblclick="return false"

EDIT: This will not cancel the single click event so problem would still exist.


问:
Xcode 8 Table View Cells to Different Views
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

```<code>import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}
</code>```

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

答:
Create a segue for each of the 4 view controllers by ctrl+right click and dragging from table view controller to each of the view controllers. Give an identifier to the segues (e.g. "TableToViewController1", "TableToViewController2", etc)

Then in your didSelectRowAt do something like:

```<code>var segueIdentifier = ""

switch(indexPath.row) {
case 0: // first cell is selected
    segueIdentifier = "TableToViewController1"
case 1:
    segueIdentifier = "TableToViewController2"
case 2:
    segueIdentifier = "TableToViewController3"
case 3:
    segueIdentifier = "TableToViewController4"
}

performSegue(withIdentifier: segueIdentifier, sender: self)
</code>```

Body:
I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells.
storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!

Body:
Create a segue for each of the 4 view controllers by ctrl+right click and dragging from table view controller to each of the view controllers. Give an identifier to the segues (e.g. "TableToViewController1", "TableToViewController2", etc)

Then in your didSelectRowAt do something like:

var segueIdentifier = ""

switch(indexPath.row) {
case 0: // first cell is selected
    segueIdentifier = "TableToViewController1"
case 1:
    segueIdentifier = "TableToViewController2"
case 2:
    segueIdentifier = "TableToViewController3"
case 3:
    segueIdentifier = "TableToViewController4"
}

performSegue(withIdentifier: segueIdentifier, sender: self)


问:
MYSQL - 2 contraints from the same column
I have a table as follow

My question is sometimes an address can have 2 or 3 different zones.

My column "zone (TINYINT)" is linked to an other table "db_zone" with a foreign key constraint

Is it possible to add a second parameter to my column like

I know I could change my column to varchar, and remove my constraint then add like "Zone: 1/2" and explode the value of my column "zone" to do my query later, but I want to keep my constraint.

I don't want either to duplicate my entry as the column "id" is also linked from an other table so I will have the same problem later.

How can I solve this ?

答:
If I understand your problem correctly, this is a case of a many-to-many relationship. Your address can belong to many zones and the zones can have many addresses under it.

The proper way to do this should be to make an associative table between your address and zone table(i.e. address_zone) where address_zone table has a foreign key to both the address and the zone table.

Here is a reference: https://en.wikipedia.org/wiki/Many-to-many_(data_model)


问:
Exclude G/L with UserResponse in Webi report
I am using Business Objects WEBi to build a new report.

In a cell I want to show the UserResponse to the G/Ls that have been excluded in a list, but when I use the formula =UserResponse["G/Ls to Exclude:"] I get a blank cell

How do I get around this issue?

答: Check whether the string has any blank spaces trailing at the back or front of the string . This may sometime does not bring the value available in the user response.</p>


答:
What you can do is inside your

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    performSegue(withIdentifier: "segue", sender: self)
}
</code>```

func you can check which index it is and based on that present the viewController you want.

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    if let animal = orchard[indexPath.row] as String? {
        if animal == "dog" {
            performSegue(withIdentifier: "dogViewController", sender: self)
        }
    }
}
</code>```

In your storyboard you would create a segue from the viewController to all ur viewControllers and name the segues with something like dogViewController etc.

Title: Xcode 8 Table View Cells to Different Views

Body:
What you can do is inside your

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    performSegue(withIdentifier: "segue", sender: self)
}

func you can check which index it is and based on that present the viewController you want.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    myIndex = indexPath.row
    if let animal = orchard[indexPath.row] as String? {
        if animal == "dog" {
            performSegue(withIdentifier: "dogViewController", sender: self)
        }
    }
}

In your storyboard you would create a segue from the viewController to all ur viewControllers and name the segues with something like dogViewController etc.


问:
Popover on iPhone (Swift 3) from Programmatically Created Button
I am trying to have a popover appear on an iPhone when I click on a programmatically created button. However, I am instead finding that the popover is taking over the entire screen. I've coded the following thus far in the popover view controller's class:

```<code>import UIKit

class GroupSetsPopoverController: UIViewController, UIPopoverPresentationControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    self.preferredContentSize = CGSize(width: 375, height: 162)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "infoButtonSegue" {
        let popoverViewController = segue.destination as! GroupSetsPopoverController

        let pvc = popoverViewController.popoverPresentationController
        pvc?.delegate = self

        //popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
        //popoverViewController.popoverPresentationController!.delegate = self
    }
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}
}
</code>```

Any guidance would be appreciated. I've tried to follow various tutorials and posts here on Stack Overflow, to no avail.

答:
You can check out the answer and library for your references. If the GroupSetsPopoverController is your popover viewcontroller, you can do something like this:</p>

```<code>init(for sender: UIView)) {
    super.init(nibName: nil, bundle: nil)

    modalPresentationStyle = .popover
    guard let pop = popoverPresentationController else { return }
    pop.sourceView = sender
    pop.sourceRect = sender.bounds
    pop.delegate = self
}
</code>```

Body:
I am trying to have a popover appear on an iPhone when I click on a programmatically created button. However, I am instead finding that the popover is taking over the entire screen. I've coded the following thus far in the popover view controller's class:

import UIKit

class GroupSetsPopoverController: UIViewController, UIPopoverPresentationControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    self.preferredContentSize = CGSize(width: 375, height: 162)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "infoButtonSegue" {
        let popoverViewController = segue.destination as! GroupSetsPopoverController

        let pvc = popoverViewController.popoverPresentationController
        pvc?.delegate = self

        //popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
        //popoverViewController.popoverPresentationController!.delegate = self
    }
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}
}

Any guidance would be appreciated. I've tried to follow various tutorials and posts here on Stack Overflow, to no avail.

Body:
You can check out the answer and library for your references. If the GroupSetsPopoverController is your popover viewcontroller, you can do something like this:

init(for sender: UIView)) {
    super.init(nibName: nil, bundle: nil)

    modalPresentationStyle = .popover
    guard let pop = popoverPresentationController else { return }
    pop.sourceView = sender
    pop.sourceRect = sender.bounds
    pop.delegate = self
}


问:
JSDoc UML Diagram
Question:
I'm editing and using an open source javascript library that has JSDoc tags in its code.  I was wondering if anyone knew of a JSDoc plugin that would allow me to generate a class diagram from the JSDoc tags.

Edit
I decided to try out js/uml and found the following.
The JS/UML eclipse extension requires an older version of Eclipse (Indigo) and a non-supported dependency library UML2tools. I found the dependencies needed and according to the Eclipse software manager installed correctly. When I tried to enable the uml functionality (having configured the js root), the process would hang. The examples that the group supplies points at single file Javascript. Seems to have trouble with multiple files being referenced.

答:
Not sure what past versions of JSDoc were capable of but JSDoc now supports Javascript classes and the extends keyword.  If code is marked up correctly JSDoc can understand class inheritance.

Could make a JSDoc plugin which subscribes to the processingComplete event:
"The processingComplete event is fired after JSDoc updates the parse results to reflect inherited and borrowed symbols."
http://usejsdoc.org/about-plugins.html

Then you can iterate over the Doclets (objects representing code elements) and serialize your own JSON out.  Then you can write a simple HTML renderer for the JSON description of your original code.

Title: JSDoc UML Diagram


问:
How to add a custom option(Dowload Image) with other share options in android
Is it possible to add a custom option(For eg. Download Image) with other share option(shown in attached image) in intent chooser?

答:
Unfortunately, I did not get useful answers. I did a workaround to solve this.

Here is the code to add a custom 'Save to Gallery" option(shown in attached image)

```<code>Intent downloadIntent = new Intent(aContext, DownloadActivity.class);
downloadIntent.putExtra("url", url);
intentList.add(new LabeledIntent(downloadIntent, "com.don.offers", "Save To Gallery", R.drawable.ic_save_to_gallery));

// convert intentList to array
LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
</code>```

Here DownloadActivity is transparent activity that has the code to download image.

```<code>public class DownloadActivity extends AppCompatActivity {

    String imageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        imageUrl = getIntent().getStringExtra("url");
        saveToGallery();
        finish();
    }

    public void saveToGallery() {
        try {
            String DIR_NAME = "Don Downloaded Images";
            String filename = "DON_IMG_" + System.currentTimeMillis();
            //String downloadUrlOfImage = "http://fun.localdon.com/DonUGCImg/DON_memes14908366211071492831321991.png";
            String downloadUrlOfImage = imageUrl;
            File direct =
                    new File(Environment
                            .getExternalStoragePublicDirectory(String.valueOf(Environment.DIRECTORY_PICTURES))
                            .getAbsolutePath() + "/" + DIR_NAME + "/");

            if (!direct.exists()) {
                direct.mkdir();
                Log.e("saveToGallery", "dir created for first time");
            }

            DownloadManager dm = (DownloadManager) DownloadActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
            Uri downloadUri = Uri.parse(downloadUrlOfImage);
            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle(filename)
                    .setMimeType("image/jpeg")
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setDestinationInExternalPublicDir(String.valueOf(Environment.DIRECTORY_PICTURES),
                            File.separator + DIR_NAME + File.separator + filename);

            dm.enqueue(request);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                final Uri contentUri = Uri.fromFile(direct);
                scanIntent.setData(contentUri);
                DownloadActivity.this.sendBroadcast(scanIntent);
            } else {
                final Intent intent1 = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
                DownloadActivity.this.sendBroadcast(intent1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

If anyone has better approach please share.Thanks

Body:
Unfortunately, I did not get useful answers. I did a workaround to solve this.

Here is the code to add a custom 'Save to Gallery" option(shown in attached image)

Intent downloadIntent = new Intent(aContext, DownloadActivity.class);
downloadIntent.putExtra("url", url);
intentList.add(new LabeledIntent(downloadIntent, "com.don.offers", "Save To Gallery", R.drawable.ic_save_to_gallery));

// convert intentList to array
LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);

Here DownloadActivity is transparent activity that has the code to download image.

public class DownloadActivity extends AppCompatActivity {

    String imageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        imageUrl = getIntent().getStringExtra("url");
        saveToGallery();
        finish();
    }

    public void saveToGallery() {
        try {
            String DIR_NAME = "Don Downloaded Images";
            String filename = "DON_IMG_" + System.currentTimeMillis();
            //String downloadUrlOfImage = "http://fun.localdon.com/DonUGCImg/DON_memes14908366211071492831321991.png";
            String downloadUrlOfImage = imageUrl;
            File direct =
                    new File(Environment
                            .getExternalStoragePublicDirectory(String.valueOf(Environment.DIRECTORY_PICTURES))
                            .getAbsolutePath() + "/" + DIR_NAME + "/");

            if (!direct.exists()) {
                direct.mkdir();
                Log.e("saveToGallery", "dir created for first time");
            }

            DownloadManager dm = (DownloadManager) DownloadActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
            Uri downloadUri = Uri.parse(downloadUrlOfImage);
            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle(filename)
                    .setMimeType("image/jpeg")
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setDestinationInExternalPublicDir(String.valueOf(Environment.DIRECTORY_PICTURES),
                            File.separator + DIR_NAME + File.separator + filename);

            dm.enqueue(request);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                final Uri contentUri = Uri.fromFile(direct);
                scanIntent.setData(contentUri);
                DownloadActivity.this.sendBroadcast(scanIntent);
            } else {
                final Intent intent1 = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
                DownloadActivity.this.sendBroadcast(intent1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If anyone has better approach please share.Thanks


问:
Play Framework - Passing Application Arguments via Docker Container
Before dockerizing my play web application, I was able to do the following when running:

```<code>Joes-Macbook:project-1 joe$ sbt -Dconfig.env=dev run
</code>```

Where I can use one of the following of either dev, qa, prod to the config.env argument and my application will run using the corresponding application.dev.conf or application.qa.conf accordingly.

Now I have my application as a docker container which means that I need a way to inject my configuration file. How could I do it?

One way what I'm thinking is to have a shell script and use that as the Entrypoint. But not sure how this might work? Any suggestions?

So when I do

sbt docker:publishLocal

I get the following Dockerfile produced

```<code>FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER Joesan <myemail@email.com>
WORKDIR /opt/docker
ADD opt /opt
RUN ["chown", "-R", "daemon:daemon", "."]
USER daemon
ENTRYPOINT ["sh", "-c", "bin/project-1", "-Denv=$configEnv"]
CMD []
ENV configEnv default
</code>```

I could not get the $configEnv resolved in my Scala application. This is how I run the produced docker image:

```<code>docker run -e "configEnv=crap" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT
</code>```

答:
You can set en environment variable when you use docker run (or in docker compose)

```<code>docker run -e "deep=purple" ...
</code>```

That means your Dockerfile can declare that same variable as ENV, and be used by your default CMD.

```<code>ENV configEnv
CMD sbt -Dconfig.env=${configEnv} run
</code>```

Though, the OP is working with sbt-native-packager, which generates a Dockerfile.

Issue 861 shows how to add commands to the generated Dockefile:

```<code>dockerCommands ++= Seq (
      // setting the run script executable
      ExecCmd("RUN", "chmod", "u+x", s"${(defaultLinuxInstallLocation in Docker).value}/bin/${executableScriptName.value}")
    )
</code>```

That means you can declare ENV that way.

And issue 927 shows how to override the default ENTRYPOINT:

```<code>dockerEntrypoint := Seq("bin/my-app", "-Dconfig.resource=application-prod.conf")
</code>```

Combining the two should allow to implement the solution I proposed above.

Actually, after discussion, overriding is no good, because the generated Dcokerfile would have ENTRYPOINT followed by the ENV declaration, which is not good.

Only by adding both ENV and ENTRYPOINT, one can generate the correct Dockerfile, as illustrated by the OP sparkr below.

Body:
Before dockerizing my play web application, I was able to do the following when running:

Joes-Macbook:project-1 joe$ sbt -Dconfig.env=dev run

Where I can use one of the following of either dev, qa, prod to the config.env argument and my application will run using the corresponding application.dev.conf or application.qa.conf accordingly.

Now I have my application as a docker container which means that I need a way to inject my configuration file. How could I do it?

One way what I'm thinking is to have a shell script and use that as the Entrypoint. But not sure how this might work? Any suggestions?

So when I do

sbt docker:publishLocal

I get the following Dockerfile produced

FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER Joesan <myemail@email.com>
WORKDIR /opt/docker
ADD opt /opt
RUN ["chown", "-R", "daemon:daemon", "."]
USER daemon
ENTRYPOINT ["sh", "-c", "bin/project-1", "-Denv=$configEnv"]
CMD []
ENV configEnv default

I could not get the $configEnv resolved in my Scala application. This is how I run the produced docker image:

docker run -e "configEnv=crap" --rm --name play-8080 -p 8080:9000 joesan/project-1:1.0-SNAPSHOT

Body:
You can set en environment variable when you use docker run (or in docker compose)

docker run -e "deep=purple" ...

That means your Dockerfile can declare that same variable as ENV, and be used by your default CMD.

ENV configEnv
CMD sbt -Dconfig.env=${configEnv} run

Though, the OP is working with sbt-native-packager, which generates a Dockerfile.

Issue 861 shows how to add commands to the generated Dockefile:

dockerCommands ++= Seq (
      // setting the run script executable
      ExecCmd("RUN", "chmod", "u+x", s"${(defaultLinuxInstallLocation in Docker).value}/bin/${executableScriptName.value}")
    )

That means you can declare ENV that way.

And issue 927 shows how to override the default ENTRYPOINT:

dockerEntrypoint := Seq("bin/my-app", "-Dconfig.resource=application-prod.conf")

Combining the two should allow to implement the solution I proposed above.

Actually, after discussion, overriding is no good, because the generated Dcokerfile would have ENTRYPOINT followed by the ENV declaration, which is not good.

Only by adding both ENV and ENTRYPOINT, one can generate the correct Dockerfile, as illustrated by the OP sparkr below.


问:
OutOfMemoryError Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM
I am just fetching an image from drawable and getting it into bitmap but while getting into bitmap its throws an error

java.lang.OutOfMemoryError: Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM

Here is my code below

```<code>Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.vr_image);
    int size = icon.getByteCount();
</code>```

Some solution found on stackoverflow but these also not working.

on manifest under application tag i have define following values

```<code> android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:supportsRtl="true"
</code>```

So any one can help me out from this problem not getting any solution for this.

答:
You can make use Picasso library. With the require pixel according to device you can resize and load into the imageview</p>

```<code> Picasso.with(context).load(incidentType.getIconServerPath()).error(R.drawable.no_image_icon).resize(mWidth, mWidth).onlyScaleDown().centerInside().into(holder.imageViewIcon,
                    new Callback() {
                        @Override
                        public void onSuccess() {
                            holder.relativeLayout.removeView(holder.progressBar);
                        }

                        @Override
                        public void onError() {
                            holder.relativeLayout.removeView(holder.progressBar);
                        }
                    });
        }
    });
</code>```

Body:
I am just fetching an image from drawable and getting it into bitmap but while getting into bitmap its throws an error

java.lang.OutOfMemoryError: Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM

Here is my code below

Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.vr_image);
    int size = icon.getByteCount();

Some solution found on stackoverflow but these also not working.

on manifest under application tag i have define following values

 android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:supportsRtl="true"

So any one can help me out from this problem not getting any solution for this.

Body:
You can make use Picasso library. With the require pixel according to device you can resize and load into the imageview

 Picasso.with(context).load(incidentType.getIconServerPath()).error(R.drawable.no_image_icon).resize(mWidth, mWidth).onlyScaleDown().centerInside().into(holder.imageViewIcon,
                    new Callback() {
                        @Override
                        public void onSuccess() {
                            holder.relativeLayout.removeView(holder.progressBar);
                        }

                        @Override
                        public void onError() {
                            holder.relativeLayout.removeView(holder.progressBar);
                        }
                    });
        }
    });


问:
Using Eve and Flask in one application
I want to provide REST interface and a single page JS-application for consuming the REST-service. Is there a way to do both in one python app or should I start eve-app for providing REST and flask-app for providing HTML as two processes?</p>

答: If your flask app is only for serving static files, you don't even need a flask app. You may be able to directly serve static assets via Nginx </p>

Title: Using Eve and Flask in one application


问:
Using values from two data files for one formula for calculation in R
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

```<code>ID      PM
 1       5
 2      10
...    ...
1500    25
</code>```

Data set 2.

```<code>alpha    beta
    5       6
    1       2
  ...     ...
</code>```

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

```<code>for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}
</code>```

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!

答:
We can do this with outer

```<code>data.frame(ID = rep(df1$ID, each = nrow(df2)), alpha = df2$alpha,
     beta = df2$beta, result = c(t(outer(df1$PM, df2$alpha*df2$beta))))
#    ID alpha beta result
#1    1     5    1     25
#2    1     6    2     60
#3    2     5    1     50
#4    2     6    2    120
#5 1500     5    1    125
#6 1500     6    2    300
</code>```

data

```<code>df1 <- structure(list(ID = c(1, 2, 1500), PM = c(5, 10, 25)), .Names = c("ID",
"PM"), row.names = c(NA, -3L), class = "data.frame")

df2 <- structure(list(alpha = c(5, 6), beta = c(1, 2)), .Names = c("alpha",
 "beta"), row.names = c(NA, -2L), class = "data.frame")
</code>```

Body:
I'm a trying-to-be R user. I never learned to code properly and have been just doing it by finding stuff online.

I encountered a problem that I would need some of you experts' help.

I have two data files.

Particulate matter (PM) concentrations (~20000 observations)

Coefficient combinations to use with the particulate matter concentrations to calculate final concentrations.

For example..

Data set 1.

ID      PM
 1       5
 2      10
...    ...
1500    25

Data set 2.

alpha    beta
    5       6
    1       2
  ...     ...

I ultimately have to use all the coefficient combinations (alpha and beta) for each of the IDs from data set 1. For example, if I have 10 observations in data set 1, and 10 coefficient combinations in data set 2, my output table should have 100 different output values (10*10=100).

for (i in cmaq$FID) {
  mean=cmaq$PM*IER$alpha*IER$beta
}

I used the above code to do what I'm trying to do, but it only gave me 10 output values rather than 100. I think using the split function first, and somehow use that with the second dataset would work, but have not figured out how...

It may be a very very simple problem, but after spending hours to figure it out, I thought it may be a better strategy to get some help from R experts.

Thank you in advance!!!

Body:
We can do this with outer

data.frame(ID = rep(df1$ID, each = nrow(df2)), alpha = df2$alpha,
     beta = df2$beta, result = c(t(outer(df1$PM, df2$alpha*df2$beta))))
#    ID alpha beta result
#1    1     5    1     25
#2    1     6    2     60
#3    2     5    1     50
#4    2     6    2    120
#5 1500     5    1    125
#6 1500     6    2    300

data

df1 <- structure(list(ID = c(1, 2, 1500), PM = c(5, 10, 25)), .Names = c("ID",
"PM"), row.names = c(NA, -3L), class = "data.frame")

df2 <- structure(list(alpha = c(5, 6), beta = c(1, 2)), .Names = c("alpha",
 "beta"), row.names = c(NA, -2L), class = "data.frame")