问:
Android - Using generics to have 1 RxJava retrofit call returning various types using the same interface
I'm playing around with Generics for the first time to clean up some repeated code I have around retrofit calls.

I was able to make a generic retrofit adapter, so my providers didn't have to each have a unique creator, which was really awesome and exciting.

```<code>private fun <T> create(service: Class<T>, baseUrl: String): T {
        val retrofit = Retrofit.Builder()
                .client(client)
                .addConverterFactory(MoshiConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build()

        return retrofit.create(service)
    }
</code>```

Now I'm trying to do a generic network call, but I'm not able to figure it out, and wondering if it's even possible given how Retrofit works?

I have 5 services like below right now, all hitting different APIs.  Each one has a different end point, but all accept 1 parameter and return their object which is slightly different for each API call.

```<code>interface ServiceA {
    @GET("v2/ticker")
    fun getCurrentTradingInfo(@Query("book") orderBook: String): Observable<CurrentTradingInfo>
}
</code>```

All the response objects implement an interface to normalize the response data so I can display it later

```<code>data class CurrentTradingInfo(val mid: String,
                              val bid: String,
                              val ask: String,
                              val last_price: String,
                              val low: String,
                              val high: String,
                              val volume: String,
                              val timestamp: String) : normalizedData {

    override fun lastPrice(): String {
        return last_price
    }

    override fun timeStamp(): String {
        return timestamp
    }
}
</code>```

Currently, I have a network call for each service like below

```<code> val disposable = service.getCurrentTradingInfo(ticker.ticker)
                    .observeOn(AndroidSchedulers.mainThread())
                    .repeatWhen { result -> result.delay(10, TimeUnit.SECONDS) }
                    .retryWhen { error -> error.delay(10, TimeUnit.SECONDS) }
                    .subscribeOn(Schedulers.io())
                    .subscribe({ result ->

                        val tradingInfo = TradingInfo(result.lastPrice(), result.timeStamp())
                        networkDataUpdate.updateData(ticker, tradingInfo)
                        callback.updateUi(ticker)

                    }, { error ->
                        error.printStackTrace()
                    })
</code>```

From my little knowledge of generics, it seems like I should be able to pass in a generic service and handle as many different API ends points using this one RxJava call?  I don't know how to access each services getCurrentTradingInfo method though, and from what I do read, I'm doubting if it's possible using retrofit interfaces?

I'm not necessarily looking for a complete answer if it's possible (although an explanation would be nice) but I'm wondering if it's even possible to do in this specific scenario?  I don't want to keep wasting my time if it's not even possible.

答:
I'd suggest using compose():

```<code> val disposable = service.getCurrentTradingInfo(ticker.ticker)
                         .compose(displayOnTicker(ticker))
                         .subscribe();
</code>```

Then just in your displayOnTicker(Source) (apologies for the Java-isms):

```<code> return source -> source
                .observeOn(AndroidSchedulers.mainThread())
                .repeatWhen { result -> result.delay(10, TimeUnit.SECONDS) }
                .retryWhen { error -> error.delay(10, TimeUnit.SECONDS) }
                .subscribeOn(Schedulers.io())
                .doOnNext({ result ->
                    val tradingInfo = TradingInfo(result.lastPrice(), result.timeStamp())
                    networkDataUpdate.updateData(ticker, tradingInfo)
                    callback.updateUi(ticker)
                })
                // add .doOnError / .onErrorResumeNext as desired
                ;
</code>```

This allows you to

be completely independent from a class hierarchy

reuse the same displayOnTicker in other location

maybe place the displayOnTicker in a mixin?

Body:
I'm playing around with Generics for the first time to clean up some repeated code I have around retrofit calls.

I was able to make a generic retrofit adapter, so my providers didn't have to each have a unique creator, which was really awesome and exciting.

private fun <T> create(service: Class<T>, baseUrl: String): T {
        val retrofit = Retrofit.Builder()
                .client(client)
                .addConverterFactory(MoshiConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build()

        return retrofit.create(service)
    }

Now I'm trying to do a generic network call, but I'm not able to figure it out, and wondering if it's even possible given how Retrofit works?

I have 5 services like below right now, all hitting different APIs.  Each one has a different end point, but all accept 1 parameter and return their object which is slightly different for each API call.

interface ServiceA {
    @GET("v2/ticker")
    fun getCurrentTradingInfo(@Query("book") orderBook: String): Observable<CurrentTradingInfo>
}

All the response objects implement an interface to normalize the response data so I can display it later

data class CurrentTradingInfo(val mid: String,
                              val bid: String,
                              val ask: String,
                              val last_price: String,
                              val low: String,
                              val high: String,
                              val volume: String,
                              val timestamp: String) : normalizedData {

    override fun lastPrice(): String {
        return last_price
    }

    override fun timeStamp(): String {
        return timestamp
    }
}

Currently, I have a network call for each service like below

 val disposable = service.getCurrentTradingInfo(ticker.ticker)
                    .observeOn(AndroidSchedulers.mainThread())
                    .repeatWhen { result -> result.delay(10, TimeUnit.SECONDS) }
                    .retryWhen { error -> error.delay(10, TimeUnit.SECONDS) }
                    .subscribeOn(Schedulers.io())
                    .subscribe({ result ->

                        val tradingInfo = TradingInfo(result.lastPrice(), result.timeStamp())
                        networkDataUpdate.updateData(ticker, tradingInfo)
                        callback.updateUi(ticker)

                    }, { error ->
                        error.printStackTrace()
                    })

From my little knowledge of generics, it seems like I should be able to pass in a generic service and handle as many different API ends points using this one RxJava call?  I don't know how to access each services getCurrentTradingInfo method though, and from what I do read, I'm doubting if it's possible using retrofit interfaces?

I'm not necessarily looking for a complete answer if it's possible (although an explanation would be nice) but I'm wondering if it's even possible to do in this specific scenario?  I don't want to keep wasting my time if it's not even possible.

Body:
I'd suggest using compose():

 val disposable = service.getCurrentTradingInfo(ticker.ticker)
                         .compose(displayOnTicker(ticker))
                         .subscribe();

Then just in your displayOnTicker(Source) (apologies for the Java-isms):

 return source -> source
                .observeOn(AndroidSchedulers.mainThread())
                .repeatWhen { result -> result.delay(10, TimeUnit.SECONDS) }
                .retryWhen { error -> error.delay(10, TimeUnit.SECONDS) }
                .subscribeOn(Schedulers.io())
                .doOnNext({ result ->
                    val tradingInfo = TradingInfo(result.lastPrice(), result.timeStamp())
                    networkDataUpdate.updateData(ticker, tradingInfo)
                    callback.updateUi(ticker)
                })
                // add .doOnError / .onErrorResumeNext as desired
                ;

This allows you to

be completely independent from a class hierarchy

reuse the same displayOnTicker in other location

maybe place the displayOnTicker in a mixin?


来源: stackexchange

问:
C++ : prim() in an "if statement"
While studying the C++ programming language by B. Stroustrup, it has been mentioned the existence of the prim() functions which reduces the scope of the declared variable to one single block.

This is an example provided by the book:

```<code>if (double d = prim(true)) {
        left /= d;      break;
}
</code>```

Despite understanding its interest, I cannot figure out how to use it: is it part of a certain library ? Of must I precise the standard because Visual Studio isn't able to recognise the function.

Thanks in advance

答:
The code demonstrates an ability to declare a local variable inside a header of an if statement. It has nothing to do with prim(...) function, which is probably defined in some other place in the book.

Here is another example:

```<code>int k = 3;
if (int d = k*50) {
    cout << "hello " << d << endl;
}
</code>```

This prints hello 150. Variable d is accessible only inside the body of the if statement.

Note that the scope of d extends to else branch as well (demo):

```<code>int k = 0;
if (int d = k*50) {
    cout << "hello " << d << endl;
} else {
    cout << "goodbye " << d << endl;
}
</code>```

Note: In the example above there is no reason to check d in the else branch because it is guaranteed to be zero.

ContentLicense: CC BY-SA 3.0

Title: C++ : prim() in an "if statement"

Body:
While studying the C++ programming language by B. Stroustrup, it has been mentioned the existence of the prim() functions which reduces the scope of the declared variable to one single block.

This is an example provided by the book:

if (double d = prim(true)) {
        left /= d;      break;
}

Despite understanding its interest, I cannot figure out how to use it: is it part of a certain library ? Of must I precise the standard because Visual Studio isn't able to recognise the function.

Thanks in advance

Body:
The code demonstrates an ability to declare a local variable inside a header of an if statement. It has nothing to do with prim(...) function, which is probably defined in some other place in the book.

Here is another example:

int k = 3;
if (int d = k*50) {
    cout << "hello " << d << endl;
}

This prints hello 150. Variable d is accessible only inside the body of the if statement.

Note that the scope of d extends to else branch as well (demo):

int k = 0;
if (int d = k*50) {
    cout << "hello " << d << endl;
} else {
    cout << "goodbye " << d << endl;
}

Note: In the example above there is no reason to check d in the else branch because it is guaranteed to be zero.


问:
Include code coverage report in VSTS, Is Test Adapter mandatory for VSTS?
I am generating code coverage using Karma-coverage. I can host my output coverage folder on http-server and view it locally.

How do I make this report visible on VSTS code coverage tab?

Do I need to re-format my coverage result in VSTS compatible?

I have read about vsts-tasks, but I have no clue how to achieve the same.

Any help is appreciated.

答:
With karma.conf.js file generated by angular CLI 1.2+, it is as simple as adding the cobertura report (instead of lcov report) in istanbul reporter :

```<code>coverageIstanbulReporter: {
  reports: ['html', 'cobertura'],
  fixWebpackSourcePaths: true
}
</code>```

So when you will run your tests with the --code-coverage option, a file named coverage-cobertura.xml will be generated in the coverage directory.

Then in your TFS/VSTS build, you can add a Publish Code Coverage task and specify the cobertura XML file.

Body:
With karma.conf.js file generated by angular CLI 1.2+, it is as simple as adding the cobertura report (instead of lcov report) in istanbul reporter :

coverageIstanbulReporter: {
  reports: ['html', 'cobertura'],
  fixWebpackSourcePaths: true
}

So when you will run your tests with the --code-coverage option, a file named coverage-cobertura.xml will be generated in the coverage directory.

Then in your TFS/VSTS build, you can add a Publish Code Coverage task and specify the cobertura XML file.


问:
How to pick one list out of many based on value in Linq?
I have an object structure which looks like this.

```<code>public class DeliveryManagerQuoteResponse
{
    public string OrderId { get; set; }
    public List<DeliveryManagerQuotes> Quotes { get; set; }
}

public class DeliveryManagerQuotes
{
    public bool IsSuccess { get; set; }
    public List<DeliveryManagerQuoteDetails> QuoteDetails { get; set; }
}

public class DeliveryManagerQuoteDetails
{
    public string QuoteId { get; set; }
    public int? DeliveryFee { get; set; }
}
</code>```

When I have DeliveryManagerQuoteResponse populated, I'll have multiple Quotesand each Quotes will have multiple QuoteDetails. What I want is, based on DeliveryFee which in DeliveryManagerQuoteDetails, I want to pick the DeliveryManagerQuoteResponse which has a minimum delivery fee. How can I do that using LINQ?

I was thinking of getting DeliveryFee first from all Quotes and then write some code/LINQ to use that to fetch quote with a minimum fee but not sure how to write it :

```<code>public void PickDeliveryQuoteBasedOnRate(DeliveryManagerQuoteResponse deliveryManagerQuoteResponse)
{

    var feeList = new List<int>();
    foreach (var quote in deliveryManagerQuoteResponse.Quotes)
    {
        if (quote.QuoteDetails != null && quote.QuoteDetails.Any())
        {
            foreach (var quoteDetail in quote.QuoteDetails)
            {
                feeList.Add(quoteDetail.DeliveryFee ?? default(int));
            }
        }
    }

    if (feeList.Any())
    {
        // This will give me minimum fee
        var minimumDeliveryFee = feeList.Min();
        // Need LINQ to use this minimum fee to pick one quote.
    }

}
</code>```

Screen Shot for better understanding:

答:
Rather than pull the detail to the top and then sort through the multiple copies of quotes, I suggest sorting the quotes by the min of all the DeliveryFees:

```<code>var minDelivery = deliveryManagerQuoteResponse.OrderBy(
                                                  dmqr => dmqr.Quotes // foreach quote
                                                              .SelectMany(q => q.QuoteDetails // foreach QuoteDetail
                                                                                .Where(qd => qd.DeliveryFee.HasValue) // that has a value
                                                                                .Select(qd => qd.DeliveryFee.Value) // select the DeliveryFree
                                                              ) // and flattten the result
                                                              .Min() // and then select the minimum DeliveryFree
                                              ) // sort quotes by minimum DeliveryFee
                                              .FirstOrDefault(); // and select the first quote
</code>```

Body:
I have an object structure which looks like this.

public class DeliveryManagerQuoteResponse
{
    public string OrderId { get; set; }
    public List<DeliveryManagerQuotes> Quotes { get; set; }
}

public class DeliveryManagerQuotes
{
    public bool IsSuccess { get; set; }
    public List<DeliveryManagerQuoteDetails> QuoteDetails { get; set; }
}

public class DeliveryManagerQuoteDetails
{
    public string QuoteId { get; set; }
    public int? DeliveryFee { get; set; }
}

When I have DeliveryManagerQuoteResponse populated, I'll have multiple Quotesand each Quotes will have multiple QuoteDetails. What I want is, based on DeliveryFee which in DeliveryManagerQuoteDetails, I want to pick the DeliveryManagerQuoteResponse which has a minimum delivery fee. How can I do that using LINQ?

I was thinking of getting DeliveryFee first from all Quotes and then write some code/LINQ to use that to fetch quote with a minimum fee but not sure how to write it :

public void PickDeliveryQuoteBasedOnRate(DeliveryManagerQuoteResponse deliveryManagerQuoteResponse)
{

    var feeList = new List<int>();
    foreach (var quote in deliveryManagerQuoteResponse.Quotes)
    {
        if (quote.QuoteDetails != null && quote.QuoteDetails.Any())
        {
            foreach (var quoteDetail in quote.QuoteDetails)
            {
                feeList.Add(quoteDetail.DeliveryFee ?? default(int));
            }
        }
    }

    if (feeList.Any())
    {
        // This will give me minimum fee
        var minimumDeliveryFee = feeList.Min();
        // Need LINQ to use this minimum fee to pick one quote.
    }

}

Screen Shot for better understanding:

Body:
Rather than pull the detail to the top and then sort through the multiple copies of quotes, I suggest sorting the quotes by the min of all the DeliveryFees:

var minDelivery = deliveryManagerQuoteResponse.OrderBy(
                                                  dmqr => dmqr.Quotes // foreach quote
                                                              .SelectMany(q => q.QuoteDetails // foreach QuoteDetail
                                                                                .Where(qd => qd.DeliveryFee.HasValue) // that has a value
                                                                                .Select(qd => qd.DeliveryFee.Value) // select the DeliveryFree
                                                              ) // and flattten the result
                                                              .Min() // and then select the minimum DeliveryFree
                                              ) // sort quotes by minimum DeliveryFee
                                              .FirstOrDefault(); // and select the first quote


问:
DocuSign (sending email to client) ASP.NET MVC
I am using DocuSign demo account to send a document as an email for signing to the client using C#. I am using the code in this link (https://www.docusign.com/developer-center/api-overview#quickstart) to do that. But when I run the code it is not sending any email to the client and it is not showing any error too. I also tried posting the baseurl that it returns after authentication along with the envelope using HttpWebRequest and also with ajax. It didn't worked out too. Can anyone please help me with this ?

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

using Newtonsoft.Json;

using DocuSign.eSign.Api;

using DocuSign.eSign.Model;

using DocuSign.eSign.Client;

namespace DocuSignTest
{

```<code>class Program
{

    static void Main(string[] args)
    {

        try
        {

            // Enter your DocuSign credentials
            string Username = "pradeepp.wayne@gmail.com";
            string Password = "******";
            string IntegratorKey = "****************";

            // specify the document we want signed
            string SignTest1File = @"C://SamplePdfSign.pdf";
            // Enter recipient (signer) name and email address
            string recipientName = "PPradeep";
            string recipientEmail = "*****************";
            // instantiate api client with appropriate environment
            string basePath = "https://demo.docusign.net/restapi";
            // instantiate a new api client
            ApiClient apiClient = new ApiClient(basePath);
            // set client in global config so we don't need to pass it to each API object
            Configuration.Default.ApiClient = apiClient;
            string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
            // we will retrieve this from the login() results
            string accountId = null;
            AuthenticationApi authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();
            accountId = loginInfo.LoginAccounts[0].AccountId;

            Console.WriteLine("LoginInformation: {0}", loginInfo.ToJson());
            // Read a file from disk to use as a document
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";
            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Name = recipientName;
            signer.Email = recipientEmail;
            signer.RecipientId = "1";

            // must set |clientUserId| to embed the recipient
            signer.ClientUserId = "1234";
            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "150";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // Use the EnvelopesApi to create and send the signature request
            EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));

        } //try
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }
}
</code>```

}

答:
I'd suggest that you comment-out (or remove altogether) this line from your code:

signer.ClientUserId = "1234";

When you specify ClientUserId, you're telling DocuSign not to send an email to the signer (because that signer is what DocuSign refers to as an embedded recipient).  If you remove ClientUserId, you're telling DocuSign that the signer is a remote recipient, so DocuSign will send a signing invitation email to that recipient.

Body:
I am using DocuSign demo account to send a document as an email for signing to the client using C#. I am using the code in this link (https://www.docusign.com/developer-center/api-overview#quickstart) to do that. But when I run the code it is not sending any email to the client and it is not showing any error too. I also tried posting the baseurl that it returns after authentication along with the envelope using HttpWebRequest and also with ajax. It didn't worked out too. Can anyone please help me with this ?

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

using Newtonsoft.Json;

using DocuSign.eSign.Api;

using DocuSign.eSign.Model;

using DocuSign.eSign.Client;

namespace DocuSignTest
{

class Program
{

    static void Main(string[] args)
    {

        try
        {

            // Enter your DocuSign credentials
            string Username = "pradeepp.wayne@gmail.com";
            string Password = "******";
            string IntegratorKey = "****************";

            // specify the document we want signed
            string SignTest1File = @"C://SamplePdfSign.pdf";
            // Enter recipient (signer) name and email address
            string recipientName = "PPradeep";
            string recipientEmail = "*****************";
            // instantiate api client with appropriate environment
            string basePath = "https://demo.docusign.net/restapi";
            // instantiate a new api client
            ApiClient apiClient = new ApiClient(basePath);
            // set client in global config so we don't need to pass it to each API object
            Configuration.Default.ApiClient = apiClient;
            string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
            // we will retrieve this from the login() results
            string accountId = null;
            AuthenticationApi authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();
            accountId = loginInfo.LoginAccounts[0].AccountId;

            Console.WriteLine("LoginInformation: {0}", loginInfo.ToJson());
            // Read a file from disk to use as a document
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";
            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Name = recipientName;
            signer.Email = recipientEmail;
            signer.RecipientId = "1";

            // must set |clientUserId| to embed the recipient
            signer.ClientUserId = "1234";
            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "150";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // Use the EnvelopesApi to create and send the signature request
            EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));

        } //try
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }
}

}


问:
Sort XML based on name, attribute name, attribute value and node value
I am trying to sort xml files based on 4 dimensions - nodenames, attribute names, attribute values, and lastly based on node values.

My XML

```<code><NodeRoot>
    <NodeA class="3">
        <NodeB>
            <NodeC abc="1">103</NodeC>
            <NodeD>103</NodeD>
            <NodeC pqr="2">101</NodeC>
            <NodeC pqr="1">102</NodeC>
            <NodeD>101</NodeD>
        </NodeB>
    </NodeA>
    <NodeA class="1">
        <NodeGroup>
            <NodeC name="z" asc="2">103</NodeC>
            <NodeC name="b">101</NodeC>
            <NodeC name="a">102</NodeC>
        </NodeGroup>
    </NodeA>
</NodeRoot>
</code>```

My XSL

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*">
            <xsl:sort select="local-name()"/>
            <xsl:sort select="."/>
        </xsl:apply-templates>
        <xsl:apply-templates select="node()">
            <xsl:sort select="local-name()"/>
            <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code>```

Current Output

```<code><NodeRoot>
   <NodeA class="1">
      <NodeGroup>
         <NodeC name="b">101</NodeC>
         <NodeC name="a">102</NodeC>
         <NodeC asc="2" name="z">103</NodeC>
      </NodeGroup>
   </NodeA>
   <NodeA class="3">
      <NodeB>
         <NodeC pqr="2">101</NodeC>
         <NodeC pqr="1">102</NodeC>
         <NodeC abc="1">103</NodeC>
         <NodeD>101</NodeD>
         <NodeD>103</NodeD>
      </NodeB>
   </NodeA>
</NodeRoot>
</code>```

Expected Outcome

```<code><NodeRoot>
   <NodeA class="1">
      <NodeGroup>
         <NodeC asc="2" name="z">103</NodeC>
         <NodeC name="a">102</NodeC>
         <NodeC name="b">101</NodeC>
      </NodeGroup>
   </NodeA>
   <NodeA class="3">
      <NodeB>
         <NodeC abc="1">103</NodeC>
         <NodeC pqr="1">102</NodeC>
         <NodeC pqr="2">101</NodeC>
         <NodeD>101</NodeD>
         <NodeD>103</NodeD>
      </NodeB>
   </NodeA>
</NodeRoot>
</code>```

Test XSLT --> http://xsltransform.net/naZXpY7

答:
You're currently sorting all attributes of an element by local name and value, and then all children (again by local name and string value).

So far, so good.

One difficulty you face is what exactly you mean by sorting by "attribute names".  From your example, it looks as if you want elements sorted by a list of their attribute names in alphabetic order, so that the sort keys for the children of your NodeGroup element are

```<code>'NodeC', 'asc name', '2 z', 103
'NodeC', 'name', 'a', 102
'NodeC', 'name', 'b', 201
</code>```

The next difficulty is that there's no obvious way to obtain the value 'asc name' from an XPath 1.0 expression with the first NodeC of your NodeGroup element as context node.  It's possible to generate the string, of course, but it requires a call to a named template.  (Or, to be more precise:  I don't see how to generate it without such a call.)

XSLT 2.0 solution

The problem is relatively straightforward in XSLT 2.0; the following fragments show the crucial bits:

```<code><xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="."/>
    </xsl:apply-templates>
    <xsl:apply-templates select="node()">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string-join(local:key2(.), ' ')"/>
      <xsl:sort select="string-join(local:key3(.), ' ')"/>
      <xsl:sort select="." data-type="number"/>
    </xsl:apply-templates>
  </xsl:copy>
</xsl:template>

<xsl:function name="local:key2"  as="xs:string*">
  <xsl:param name="e" as="node()"/>
  <xsl:for-each select="$e/@*">
    <xsl:sort select="local-name()"/>
    <xsl:sort select="string()"/>
    <xsl:value-of select="local-name()"/>
  </xsl:for-each>
</xsl:function>

<xsl:function name="local:key3"  as="xs:string*">
  <xsl:param name="e" as="node()"/>
  <xsl:for-each select="$e/@*">
    <xsl:sort select="local-name()"/>
    <xsl:sort select="string()"/>
    <xsl:value-of select="string()"/>
  </xsl:for-each>
</xsl:function>
</code>```

This general approach can also be used in XSLT 1.0 with the EXSLT extension for user-defined functions.

Solution in XSLT 1.0 with EXSLT functions

If your XSLT 1.0 processor supports EXSLT-style user-defined functions, you may be able to do something similar in XSLT 1.0.  (My initial attempts failed, but the errors disappeared when I remembered to add the extension-element-prefixes attribute to the stylesheet element.)

```<code><xsl:stylesheet version="1.0"
                extension-element-prefixes="func"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                xmlns:func="http://exslt.org/functions"
                xmlns:local="http://example.com/nss/dummy">

  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
      <xsl:apply-templates select="node()">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="local:key2(.)"/>
        <xsl:sort select="local:key3(.)"/>
        <xsl:sort select="." data-type="number"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <func:function name="local:key2">
    <xsl:param name="e" select="."/>

    <func:result>
      <xsl:for-each select="$e/@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="string()"/>
        <xsl:value-of select="concat(local-name(), ' ')"/>
      </xsl:for-each>
    </func:result>
  </func:function>

  <func:function name="local:key3">
    <xsl:param name="e" select="."/>
    <func:result>
      <xsl:for-each select="$e/@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="string()"/>
        <xsl:value-of select="concat(string(), ' ')"/>
      </xsl:for-each>
    </func:result>
  </func:function>
</xsl:stylesheet>
</code>```

When run on your input with xsltproc, this produces the desired output.

You might also be able to do something clever in XSLT 1.0 with the node-set extension.

Two-stage pipeline in unextended XSLT 1.0

But the simplest way I can see to solve this problem in unextended XSLT 1.0 is to pipeline two stylesheets together.  The first one adds two attributes to every element, to provide sort keys 2 and 3.  (Adjust the named templates to make them do what you want.)

```<code><xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:PJ="http://example.com/PankajJaju">
  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:if test="self::*">
        <xsl:attribute name="PJ:attribute-names"
                       namespace="http://example.com/PankajJaju">
          <xsl:call-template name="attribute-name-list"/>
        </xsl:attribute>
        <xsl:attribute name="PJ:attribute-values"
                       namespace="http://example.com/PankajJaju">
          <xsl:call-template name="attribute-value-list"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template name="attribute-name-list">
    <xsl:for-each select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string()"/>
      <xsl:value-of select="concat(local-name(), ' ')"/>
    </xsl:for-each>
  </xsl:template>
  <xsl:template name="attribute-value-list">
    <xsl:for-each select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string()"/>
      <xsl:value-of select="concat(string(), ' ')"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

I've put them into a namespace to reduce the likelihood of name collisions.

The second one uses the sort keys to perform the actual sort and suppresses the temporary attributes.

```<code><xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:PJ="http://example.com/PankajJaju">
  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
      <xsl:apply-templates select="node()">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="@PJ:attribute-names"/>
        <xsl:sort select="@PJ:attribute-values"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@PJ:attribute-names | @PJ:attribute-values"/>
</xsl:stylesheet>
</code>```

These can be pipelined together using whatever technology you prefer.  Using xsltproc from the bash command line, for example, and assigning the names p1.xsl and p2.xsl to pipeline stylesheets 1 and 2 ...

```<code>xsltproc p1.xsl input.xml | xsltproc p2.xsl -
</code>```

This produces the output you say you want.

Body:
I am trying to sort xml files based on 4 dimensions - nodenames, attribute names, attribute values, and lastly based on node values.

My XML

<NodeRoot>
    <NodeA class="3">
        <NodeB>
            <NodeC abc="1">103</NodeC>
            <NodeD>103</NodeD>
            <NodeC pqr="2">101</NodeC>
            <NodeC pqr="1">102</NodeC>
            <NodeD>101</NodeD>
        </NodeB>
    </NodeA>
    <NodeA class="1">
        <NodeGroup>
            <NodeC name="z" asc="2">103</NodeC>
            <NodeC name="b">101</NodeC>
            <NodeC name="a">102</NodeC>
        </NodeGroup>
    </NodeA>
</NodeRoot>

My XSL

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*">
            <xsl:sort select="local-name()"/>
            <xsl:sort select="."/>
        </xsl:apply-templates>
        <xsl:apply-templates select="node()">
            <xsl:sort select="local-name()"/>
            <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Current Output

<NodeRoot>
   <NodeA class="1">
      <NodeGroup>
         <NodeC name="b">101</NodeC>
         <NodeC name="a">102</NodeC>
         <NodeC asc="2" name="z">103</NodeC>
      </NodeGroup>
   </NodeA>
   <NodeA class="3">
      <NodeB>
         <NodeC pqr="2">101</NodeC>
         <NodeC pqr="1">102</NodeC>
         <NodeC abc="1">103</NodeC>
         <NodeD>101</NodeD>
         <NodeD>103</NodeD>
      </NodeB>
   </NodeA>
</NodeRoot>

Expected Outcome

<NodeRoot>
   <NodeA class="1">
      <NodeGroup>
         <NodeC asc="2" name="z">103</NodeC>
         <NodeC name="a">102</NodeC>
         <NodeC name="b">101</NodeC>
      </NodeGroup>
   </NodeA>
   <NodeA class="3">
      <NodeB>
         <NodeC abc="1">103</NodeC>
         <NodeC pqr="1">102</NodeC>
         <NodeC pqr="2">101</NodeC>
         <NodeD>101</NodeD>
         <NodeD>103</NodeD>
      </NodeB>
   </NodeA>
</NodeRoot>

Test XSLT --> http://xsltransform.net/naZXpY7

Body:
You're currently sorting all attributes of an element by local name and value, and then all children (again by local name and string value).

So far, so good.

One difficulty you face is what exactly you mean by sorting by "attribute names".  From your example, it looks as if you want elements sorted by a list of their attribute names in alphabetic order, so that the sort keys for the children of your NodeGroup element are

'NodeC', 'asc name', '2 z', 103
'NodeC', 'name', 'a', 102
'NodeC', 'name', 'b', 201

The next difficulty is that there's no obvious way to obtain the value 'asc name' from an XPath 1.0 expression with the first NodeC of your NodeGroup element as context node.  It's possible to generate the string, of course, but it requires a call to a named template.  (Or, to be more precise:  I don't see how to generate it without such a call.)

XSLT 2.0 solution

The problem is relatively straightforward in XSLT 2.0; the following fragments show the crucial bits:

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="."/>
    </xsl:apply-templates>
    <xsl:apply-templates select="node()">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string-join(local:key2(.), ' ')"/>
      <xsl:sort select="string-join(local:key3(.), ' ')"/>
      <xsl:sort select="." data-type="number"/>
    </xsl:apply-templates>
  </xsl:copy>
</xsl:template>

<xsl:function name="local:key2"  as="xs:string*">
  <xsl:param name="e" as="node()"/>
  <xsl:for-each select="$e/@*">
    <xsl:sort select="local-name()"/>
    <xsl:sort select="string()"/>
    <xsl:value-of select="local-name()"/>
  </xsl:for-each>
</xsl:function>

<xsl:function name="local:key3"  as="xs:string*">
  <xsl:param name="e" as="node()"/>
  <xsl:for-each select="$e/@*">
    <xsl:sort select="local-name()"/>
    <xsl:sort select="string()"/>
    <xsl:value-of select="string()"/>
  </xsl:for-each>
</xsl:function>

This general approach can also be used in XSLT 1.0 with the EXSLT extension for user-defined functions.

Solution in XSLT 1.0 with EXSLT functions

If your XSLT 1.0 processor supports EXSLT-style user-defined functions, you may be able to do something similar in XSLT 1.0.  (My initial attempts failed, but the errors disappeared when I remembered to add the extension-element-prefixes attribute to the stylesheet element.)

<xsl:stylesheet version="1.0"
                extension-element-prefixes="func"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                xmlns:func="http://exslt.org/functions"
                xmlns:local="http://example.com/nss/dummy">

  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
      <xsl:apply-templates select="node()">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="local:key2(.)"/>
        <xsl:sort select="local:key3(.)"/>
        <xsl:sort select="." data-type="number"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <func:function name="local:key2">
    <xsl:param name="e" select="."/>

    <func:result>
      <xsl:for-each select="$e/@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="string()"/>
        <xsl:value-of select="concat(local-name(), ' ')"/>
      </xsl:for-each>
    </func:result>
  </func:function>

  <func:function name="local:key3">
    <xsl:param name="e" select="."/>
    <func:result>
      <xsl:for-each select="$e/@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="string()"/>
        <xsl:value-of select="concat(string(), ' ')"/>
      </xsl:for-each>
    </func:result>
  </func:function>
</xsl:stylesheet>

When run on your input with xsltproc, this produces the desired output.

You might also be able to do something clever in XSLT 1.0 with the node-set extension.

Two-stage pipeline in unextended XSLT 1.0

But the simplest way I can see to solve this problem in unextended XSLT 1.0 is to pipeline two stylesheets together.  The first one adds two attributes to every element, to provide sort keys 2 and 3.  (Adjust the named templates to make them do what you want.)

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:PJ="http://example.com/PankajJaju">
  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:if test="self::*">
        <xsl:attribute name="PJ:attribute-names"
                       namespace="http://example.com/PankajJaju">
          <xsl:call-template name="attribute-name-list"/>
        </xsl:attribute>
        <xsl:attribute name="PJ:attribute-values"
                       namespace="http://example.com/PankajJaju">
          <xsl:call-template name="attribute-value-list"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template name="attribute-name-list">
    <xsl:for-each select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string()"/>
      <xsl:value-of select="concat(local-name(), ' ')"/>
    </xsl:for-each>
  </xsl:template>
  <xsl:template name="attribute-value-list">
    <xsl:for-each select="@*">
      <xsl:sort select="local-name()"/>
      <xsl:sort select="string()"/>
      <xsl:value-of select="concat(string(), ' ')"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

I've put them into a namespace to reduce the likelihood of name collisions.

The second one uses the sort keys to perform the actual sort and suppresses the temporary attributes.

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:PJ="http://example.com/PankajJaju">
  <xsl:output encoding="utf-8"
              method="xml"
              omit-xml-declaration="yes"
              indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
      <xsl:apply-templates select="node()">
        <xsl:sort select="local-name()"/>
        <xsl:sort select="@PJ:attribute-names"/>
        <xsl:sort select="@PJ:attribute-values"/>
        <xsl:sort select="."/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@PJ:attribute-names | @PJ:attribute-values"/>
</xsl:stylesheet>

These can be pipelined together using whatever technology you prefer.  Using xsltproc from the bash command line, for example, and assigning the names p1.xsl and p2.xsl to pipeline stylesheets 1 and 2 ...

xsltproc p1.xsl input.xml | xsltproc p2.xsl -

This produces the output you say you want.


问:
Wcf remote procedure calls
I have created a custom release/deployment log application for a large organization. Front end has been implemented in Adobe AIR backed up by PHP using amfphp for communication. Performance has been excellent. Currently, I have been asked to integrate some windows features (i.e outlook calendar, sharepoint). I thought it would be easier going with a native client and I tried creating a mockup in wpf(managed, but still native) and it looks really  good. My problem though is on the server side. I had in mind wcf, but to my surprise it is a soap framework(xml) and does not support object exchange between the client and the server. So my problem is how to sent to the client a "user" object as I already do with amphph?</p>

答:
amfphp does binary serialization of ActionScript objects.  You should be able to pass objects back and forth using serialized XML using a .NET class that represents your data, unless you're doing something fairly complex. The service references automatically expose the types used in WCF method parameters and return types to the client.

The difficultly with passing objects back and forth with WCF usually lies within the change tracking and concurrency.  If you add some audit fields (i.e. timestamp) to the class you use for passing back and forth, that should handle concurrency.  As for what type of concurrency handling you use to apply changes, that is up to your business rules.

ContentLicense: CC BY-SA 2.5

Title: Wcf remote procedure calls


问:
jQuery breaks when loaded from disk cache
I have a script that will hide a submit button while the form processes to prevent multiple clicks on the button.  Recently it appears this is not working all the time.

I can verify that the validate jQuery file is loading each time. I didn't make  difference when I used the file loaded from my server or a CDN.

The error only appears when the file is loaded from disk cache.  I temporarily fixed the issue by adding a random version number after the jQuery file but I wondered what could be causing the break when disk cache is used?

The browser console lists this error:

```<code>custom-quote-form:21 Uncaught TypeError: $(...).validate is not a function
    at HTMLDocument.<anonymous> (custom-quote-form:21)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)
</code>```

jquery.min.js loads first, then the CMS cached JS file after that is the jquery validate file.

This is the script

```<code><script>
    $(function() {
        $("form[name='customBuilder']").validate({
            // remove error label
            errorPlacement: function(error, element) {},
            rules: {
                fname: "required",
                lname: "required",
                phone: "required",
                company: "required",
                Email: {
                    required: true,
                    email: true
                },
            },
            submitHandler: function(form) {
                $("#loading-img").css("display", "block");
                form.submit();
                var elem = $("#submitMessage");
                elem.css("display", "none");
                setTimeout(function() {
                    elem.css("display", "");
                }, 10000);
            }
        });
    });
< /script>
</code>```

答: A.Wolff set me on the right track.  Removed defer="defer" from jquery validation plugin link.  It was auto added by the CMS.</p>

Body:
I have a script that will hide a submit button while the form processes to prevent multiple clicks on the button.  Recently it appears this is not working all the time.

I can verify that the validate jQuery file is loading each time. I didn't make  difference when I used the file loaded from my server or a CDN.

The error only appears when the file is loaded from disk cache.  I temporarily fixed the issue by adding a random version number after the jQuery file but I wondered what could be causing the break when disk cache is used?

The browser console lists this error:

custom-quote-form:21 Uncaught TypeError: $(...).validate is not a function
    at HTMLDocument.<anonymous> (custom-quote-form:21)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)

jquery.min.js loads first, then the CMS cached JS file after that is the jquery validate file.

This is the script


问:
how to customize TestNG report result with json format
I am working with TestNG and selenium webdriver java. I want to make a output report in json format, can testng make a report with json format?Please suggest me a example for this issue.</p>

答:
You can write your own reporter that will produce test execution reports in whatever format you need. Here is an example of simple json reporter

```<code>package test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.xml.XmlSuite;

public class Reporter implements IReporter {

    @SuppressWarnings("unchecked")
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        JSONArray results = new JSONArray();
        suites.forEach(element->{
            results.add(createSuiteJsonObject(element));
        });
        try (FileWriter file = new FileWriter(outputDirectory + "/report.json")) {
            file.write(results.toJSONString());
        } catch (IOException e) {
            //handle
        }

    }

    @SuppressWarnings("unchecked")
    public JSONObject createSuiteJsonObject(ISuite suite) {
        JSONObject result = new JSONObject();
        JSONArray passedMethods = new JSONArray();
        JSONArray failedMethods = new JSONArray();
        JSONArray skippedMethods = new JSONArray();
        suite.getResults().entrySet().forEach(element -> {
            ITestContext context = element.getValue().getTestContext();
            passedMethods.addAll(createResultJsonArray(context.getPassedTests().getAllResults()));
            failedMethods.addAll(createResultJsonArray(context.getFailedTests().getAllResults()));
            skippedMethods.addAll(createResultJsonArray(context.getSkippedTests().getAllResults()));
        });
        result.put("name", suite.getName());
        result.put("passed", passedMethods);
        result.put("failed", failedMethods);
        result.put("skipped", skippedMethods);
        return result;
    }

    @SuppressWarnings("unchecked")
    public JSONArray createResultJsonArray(Set<ITestResult> results) {
        JSONArray result = new JSONArray();
        results.forEach(element ->{
            JSONObject currentJsonResult = new JSONObject();
            currentJsonResult.put("name", element.getName());
            result.add(currentJsonResult);
        });
        return result;
    }

}
</code>```

And example of the report produced by it

```<code>[
    {
        "name": "Suite1",
        "passed": [
            {
                "name": "test1"
            }
        ],
        "failed": [
            {
                "name": "test2"
            },
            {
                "name": "test3"
            }
        ],
        "skipped": [
            {
                "name": "test4"
            }
        ]
    }
]
</code>```

Body:
You can write your own reporter that will produce test execution reports in whatever format you need. Here is an example of simple json reporter

package test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.xml.XmlSuite;

public class Reporter implements IReporter {

    @SuppressWarnings("unchecked")
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        JSONArray results = new JSONArray();
        suites.forEach(element->{
            results.add(createSuiteJsonObject(element));
        });
        try (FileWriter file = new FileWriter(outputDirectory + "/report.json")) {
            file.write(results.toJSONString());
        } catch (IOException e) {
            //handle
        }

    }

    @SuppressWarnings("unchecked")
    public JSONObject createSuiteJsonObject(ISuite suite) {
        JSONObject result = new JSONObject();
        JSONArray passedMethods = new JSONArray();
        JSONArray failedMethods = new JSONArray();
        JSONArray skippedMethods = new JSONArray();
        suite.getResults().entrySet().forEach(element -> {
            ITestContext context = element.getValue().getTestContext();
            passedMethods.addAll(createResultJsonArray(context.getPassedTests().getAllResults()));
            failedMethods.addAll(createResultJsonArray(context.getFailedTests().getAllResults()));
            skippedMethods.addAll(createResultJsonArray(context.getSkippedTests().getAllResults()));
        });
        result.put("name", suite.getName());
        result.put("passed", passedMethods);
        result.put("failed", failedMethods);
        result.put("skipped", skippedMethods);
        return result;
    }

    @SuppressWarnings("unchecked")
    public JSONArray createResultJsonArray(Set<ITestResult> results) {
        JSONArray result = new JSONArray();
        results.forEach(element ->{
            JSONObject currentJsonResult = new JSONObject();
            currentJsonResult.put("name", element.getName());
            result.add(currentJsonResult);
        });
        return result;
    }

}

And example of the report produced by it

[
    {
        "name": "Suite1",
        "passed": [
            {
                "name": "test1"
            }
        ],
        "failed": [
            {
                "name": "test2"
            },
            {
                "name": "test3"
            }
        ],
        "skipped": [
            {
                "name": "test4"
            }
        ]
    }
]


问:
golang udp client can't receive msg from server
i can send msg from client to server successfully. But when i try to reply message back to client, somehow client cant receive the message.

Client:

```<code>conn, _:= net.Dial("udp", serv_addr:port)
defer conn.close()
buf:= []byte("Hey, server")
conn.Write(buf)

recv:= make([]byte, 1024)
fmt.Println("Reading...\n")
conn.Read(recv)
</code>```

Server:

```<code>addr, _:= net.ResolveUDPAddr("udp", addr:port)
msg := make([]byte, 1024)

conn,_: net.ListenUDP("udp", addr)
_, ret_addr, _: conn.ReadFromUDP(msg)
//print msg
conn.WriteToUDP([]byte("got your msg", ret)
</code>```

It's a very simple udp connection. server can printout the msg from client, but on client side, it keeps waiting before conn.read() while server finished its task.

I followed this article. my implementation is almost identical.

答:
Here is a minimum code for you to play around with.

start a server part in one terminal:

go run main.go server :53033

start client in the other terminal:

go run main.go client :53033

now type messages at the client terminal and you should see both client and server exchanging messages. You can start multiple clients (in new terminal windows) and communicate with the same server.

```<code>package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net"
    "os"
)

func server(url string) {
    log.Printf("serving on %s\n", url)
    addr, err := net.ResolveUDPAddr("udp", url)
    errcheck(err)

    conn, err := net.ListenUDP("udp", addr)
    errcheck(err)
    defer close(conn)

    msg := make([]byte, 1024)

    for {
        n, retAddr, err := conn.ReadFromUDP(msg)
        errcheck(err)

        log.Printf("received %v bytes, ret addr %v, msg %s", n, retAddr, string(msg[:n]))

        reply := []byte(fmt.Sprintf("received from you: %v bytes", n))
        n, err = conn.WriteToUDP(reply, retAddr)
        errcheck(err)

        log.Printf("sent reply %v bytes\n", n)
    }
}

func client(url string) {
    log.Printf("client for server url: %s\n", url)

    addr, err := net.ResolveUDPAddr("udp", url)
    errcheck(err)

    conn, err := net.DialUDP("udp", nil, addr)
    errcheck(err)
    defer close(conn)

    msg := make([]byte, 512)
    scanner := bufio.NewScanner(os.Stdin)
    for {
        if scanner.Scan() {
            line := scanner.Text()

            n, err := conn.Write([]byte(line))
            errcheck(err)
            log.Printf("sent %d bytes \n", n)

            n, err = conn.Read(msg)
            errcheck(err)
            log.Printf("server replied with: %s \n", string(msg[:n]))
        }
    }
}

func main() {
    args := os.Args[1:]

    if len(args) < 2 {
        log.Fatal("expecting 2 arguments client or server first followed by the address:port")
    }

    switch args[0] {
    case "server":
        server(args[1])

    case "client":
        client(args[1])

    default:
        log.Fatal("first argument must be server or client")
    }

}

func errcheck(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func close(c io.Closer) {
    err := c.Close()
    if err != nil {
        log.Fatal()
    }
}
</code>```

Have fun!

Body:
i can send msg from client to server successfully. But when i try to reply message back to client, somehow client cant receive the message.

Client:

conn, _:= net.Dial("udp", serv_addr:port)
defer conn.close()
buf:= []byte("Hey, server")
conn.Write(buf)

recv:= make([]byte, 1024)
fmt.Println("Reading...\n")
conn.Read(recv)

Server:

addr, _:= net.ResolveUDPAddr("udp", addr:port)
msg := make([]byte, 1024)

conn,_: net.ListenUDP("udp", addr)
_, ret_addr, _: conn.ReadFromUDP(msg)
//print msg
conn.WriteToUDP([]byte("got your msg", ret)

It's a very simple udp connection. server can printout the msg from client, but on client side, it keeps waiting before conn.read() while server finished its task.

I followed this article. my implementation is almost identical.

Body:
Here is a minimum code for you to play around with.

start a server part in one terminal:

go run main.go server :53033

start client in the other terminal:

go run main.go client :53033

now type messages at the client terminal and you should see both client and server exchanging messages. You can start multiple clients (in new terminal windows) and communicate with the same server.

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net"
    "os"
)

func server(url string) {
    log.Printf("serving on %s\n", url)
    addr, err := net.ResolveUDPAddr("udp", url)
    errcheck(err)

    conn, err := net.ListenUDP("udp", addr)
    errcheck(err)
    defer close(conn)

    msg := make([]byte, 1024)

    for {
        n, retAddr, err := conn.ReadFromUDP(msg)
        errcheck(err)

        log.Printf("received %v bytes, ret addr %v, msg %s", n, retAddr, string(msg[:n]))

        reply := []byte(fmt.Sprintf("received from you: %v bytes", n))
        n, err = conn.WriteToUDP(reply, retAddr)
        errcheck(err)

        log.Printf("sent reply %v bytes\n", n)
    }
}

func client(url string) {
    log.Printf("client for server url: %s\n", url)

    addr, err := net.ResolveUDPAddr("udp", url)
    errcheck(err)

    conn, err := net.DialUDP("udp", nil, addr)
    errcheck(err)
    defer close(conn)

    msg := make([]byte, 512)
    scanner := bufio.NewScanner(os.Stdin)
    for {
        if scanner.Scan() {
            line := scanner.Text()

            n, err := conn.Write([]byte(line))
            errcheck(err)
            log.Printf("sent %d bytes \n", n)

            n, err = conn.Read(msg)
            errcheck(err)
            log.Printf("server replied with: %s \n", string(msg[:n]))
        }
    }
}

func main() {
    args := os.Args[1:]

    if len(args) < 2 {
        log.Fatal("expecting 2 arguments client or server first followed by the address:port")
    }

    switch args[0] {
    case "server":
        server(args[1])

    case "client":
        client(args[1])

    default:
        log.Fatal("first argument must be server or client")
    }

}

func errcheck(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func close(c io.Closer) {
    err := c.Close()
    if err != nil {
        log.Fatal()
    }
}

Have fun!


问:
C++ variable declation syntax
I recently came across this construct:
    int(m);
which seems to be equivalent to:
    int m;

Oddly, I have never seen this particular idiom before.  Can someone point me to a reference where I can read the spec on this, or just explain directly?  Does this also work in straight C?

Thanks,
ConfusedDeveloper

答:
In addition to other answers, sometimes declarator has to be parenthesized.

For example:

```<code>struct A {};

struct B { A a; };

namespace N {
  struct B { int a; };

  void f()
  {
    A (::B::*p) = &::B::a; // this () cannot be omitted
  }
}
</code>```

If () is omitted in the above code, compiler recognizes a consecutive nested
name specifier A::B instead of A and ::B, and will issue an error.

This parenthesis is necessary, but sometimes leads to a misleading situation.

```<code>struct A {
  int m;
  A() {}
  A( int ) {} // this isn't called
};

int i;

int main()
{
  A(i); // this is a declaration
  i.m = 1; // ok
}
</code>```

In the above code, A(i) is a declaration(and also a definition in this case) of an object i,
instead of a constructor call expression with an int argument i.

Hope this helps.

Title: C++ variable declation syntax

Body:
In addition to other answers, sometimes declarator has to be parenthesized.

For example:

struct A {};

struct B { A a; };

namespace N {
  struct B { int a; };

  void f()
  {
    A (::B::*p) = &::B::a; // this () cannot be omitted
  }
}

If () is omitted in the above code, compiler recognizes a consecutive nested
name specifier A::B instead of A and ::B, and will issue an error.

This parenthesis is necessary, but sometimes leads to a misleading situation.

struct A {
  int m;
  A() {}
  A( int ) {} // this isn't called
};

int i;

int main()
{
  A(i); // this is a declaration
  i.m = 1; // ok
}

In the above code, A(i) is a declaration(and also a definition in this case) of an object i,
instead of a constructor call expression with an int argument i.

Hope this helps.


问:
How to collect only part of Geo IP data(like 'country' and 'continent' )
I'm using Keen IO with the Geo IP Enrichment add-on. It works fine but I would only like to collect the 'country' and 'continent' data rather than all of it. However I cannot find how to do it. Does anyone know how this can be done? (The reason I want to do this is a "better safe than sorry" approach to GDPR)</p>

答:
Sadly, with Keen IO's Data Enrichment add-ons it is all or nothing.

One suggestion: You use a library to get the IP to Geo data on the client side, then only add the information you want to keep to the event that you are sending to Keen IO.

ContentLicense: CC BY-SA 4.0


问:
Why does it create new variable instead of reporting an error?
I have the following code:

```<code>   let answer: SomeType = new SomeType();
   ...some code...
   if(something)
   {
       let answer = new SomeType();
   }
</code>```

In the above code using "let" inside the "if" was a mistake and I would expect Typescript to report it as an error. Instead, Typescript compiled this line to Java script as:
        var answer_1 = new SomeType();
basically generated a new variable by its own.

Is this expected behavior? I think it's a bug. This is why I'm using let instead of var If expected behavior, is there a compiler option that would report this as an error?

I'm using Visual Studio 2017

Thanks

答:
Is this expected behavior?

Yes.

It's why let is different then var. You can read more about the difference between var and let in the documentation.

Excerpt:

When a variable is declared using let, it uses what some call lexical-scoping or block-scoping. Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for-loop.

Body:
I have the following code:

   let answer: SomeType = new SomeType();
   ...some code...
   if(something)
   {
       let answer = new SomeType();
   }

In the above code using "let" inside the "if" was a mistake and I would expect Typescript to report it as an error. Instead, Typescript compiled this line to Java script as:
        var answer_1 = new SomeType();
basically generated a new variable by its own.

Is this expected behavior? I think it's a bug. This is why I'm using let instead of var If expected behavior, is there a compiler option that would report this as an error?

I'm using Visual Studio 2017

Thanks


问:
Babel Preset ENV issues
Good day:

I've just installed Babel Preset-ENV through NPM and getting this issue:

```<code>[nodemon] starting `babel-node server.js server.js`
/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/home/vagrant/api/node_modules/@babel/preset-env/lib/index.js")
    at _default (/home/vagrant/api/node_modules/@babel/plugin-transform-modules-commonjs/lib/index.js:19:22)
    at Function.memoisePluginContainer (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:113:13)
    at Function.normalisePlugin (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:146:32)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (native)
</code>```

My Package.JSON is the following:

```<code>{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -L server.js --ignore 'db/schema.json' --exec babel-node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.0.0-beta.32",
    "@babel/preset-env": "^7.0.0-beta.32",
    "babel-core": "^6.26.0",
    "express": "^4.16.2",
    "express-graphql": "^0.6.11",
    "express-oauth-server": "^2.0.0",
    "graphql": "^0.11.7",
    "jsonwebtoken": "^8.1.0",
    "mongo": "^0.1.0",
    "mongoose": "^4.13.2",
    "password-hash": "^1.2.2",
    "react-relay": "^1.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0"
  }
}
</code>```

And also my .babelrc is this:

```<code>vagrant@vagrant-ubuntu-trusty-64:~/api$ cat .babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}
</code>```

Before the upgrade I was using stage-0 and es2015 presets that were working however, after the upgrade this has been buggy. Note, my NPM version is 4.6.1.

Thanks.

答: I followed this instruction for setup https://github.com/babel/babel/tree/master/experimental/babel-preset-env however, the documentation here seems outdated. I was advised to use the official babel documentation mentioned here for the preset setup https://babeljs.io/</p>

Title: Babel Preset ENV issues

Body:
Good day:

I've just installed Babel Preset-ENV through NPM and getting this issue:

[nodemon] starting `babel-node server.js server.js`
/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/home/vagrant/api/node_modules/@babel/preset-env/lib/index.js")
    at _default (/home/vagrant/api/node_modules/@babel/plugin-transform-modules-commonjs/lib/index.js:19:22)
    at Function.memoisePluginContainer (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:113:13)
    at Function.normalisePlugin (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:146:32)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (native)

My Package.JSON is the following:

{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -L server.js --ignore 'db/schema.json' --exec babel-node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.0.0-beta.32",
    "@babel/preset-env": "^7.0.0-beta.32",
    "babel-core": "^6.26.0",
    "express": "^4.16.2",
    "express-graphql": "^0.6.11",
    "express-oauth-server": "^2.0.0",
    "graphql": "^0.11.7",
    "jsonwebtoken": "^8.1.0",
    "mongo": "^0.1.0",
    "mongoose": "^4.13.2",
    "password-hash": "^1.2.2",
    "react-relay": "^1.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0"
  }
}

And also my .babelrc is this:

vagrant@vagrant-ubuntu-trusty-64:~/api$ cat .babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Before the upgrade I was using stage-0 and es2015 presets that were working however, after the upgrade this has been buggy. Note, my NPM version is 4.6.1.

Thanks.


问:
Bootstrap responsive image fit to parent height, stretching full width
I have a row with a certain height (e.g. 600px) and would like fit an img (size 1920x1080) into this row, stretching responsively 100% to the row width but not exceeding the height.

In other words, only 600px of the height of the image should be shown (the rest can be cut off, hidden, etc.), and it should remain responsive to the row width. To illustrate, only the part within the red borders should show:

The problem I am having is that "img-fluid" always fits the image to the smaller height of the container, and thus shrinking the width to keep the aspect ratio. Without img-fluid, or adding a fixed height to the image, the aspect ratio gets lost and the image is "squeezed" into the row-container. My code:

.img-400 {
  height: 400px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="container">
  <div class="row img-400">
    <div class="col-12">
      <img src="https://image.ibb.co/iG8OSb/dogs.jpg" class="img-fluid" />
    </div>
  </div>
</div></code>```

Note I tried this one: Constraining image height with bootstrap responsive image? but didn't work, it keeps scaling the img out of the container.

答:
the above solution works if the .img-fluid is not manipulated:

.img-400 {
  height: 400px;
  overflow: hidden;
}```

Body:
I have a row with a certain height (e.g. 600px) and would like fit an img (size 1920x1080) into this row, stretching responsively 100% to the row width but not exceeding the height.

In other words, only 600px of the height of the image should be shown (the rest can be cut off, hidden, etc.), and it should remain responsive to the row width. To illustrate, only the part within the red borders should show:

The problem I am having is that "img-fluid" always fits the image to the smaller height of the container, and thus shrinking the width to keep the aspect ratio. Without img-fluid, or adding a fixed height to the image, the aspect ratio gets lost and the image is "squeezed" into the row-container. My code:

.img-400 {
  height: 400px !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Note I tried this one: Constraining image height with bootstrap responsive image? but didn't work, it keeps scaling the img out of the container.


问:
Hibernate calculated collection @Formula
is it possible to have and Entity with a field calculated using Formula when the field is a Collection (let's say it's a Set)?

Here's the dummy example of what I'm trying to achive:

```<code>@Formula(value =
    "SELECT NEW com.example.entity.Person(p.name, p.age) FROM Person p")
lateinit var people :Set<Person>
</code>```

答:
From the JavaDoc for @Formula:

Defines a formula (derived value) which is a SQL fragment ...

You have to think of the fragment you write as an replacement in the select statement:

```<code>SELECT (formulaValue) AS propertyName FROM ....
</code>```

Everything you can write into formulaValue can be used in @Formula.

Your example is not a valid SQL fragment and as you can see, it is not possible to return more than one value from a @Formula.

But you could use @Subselect and a wrapper object instead:

```<code>@Entity
@Subselect("SELECT name, age FROM Person p")
public class PersonWrapper {

  @Id
  private String name;

  private int age;

}
</code>```

(in Java, as I'm not aware of the correct syntax of Kotlin)

If you really need the collection of these values in another entity, you need something to join on (which is missing in your example) and use that in an @OneToMany or @ManyToMany. Otherwise there is no use to have all these values in your entity, as all entities would have the same collection.

Body:
is it possible to have and Entity with a field calculated using Formula when the field is a Collection (let's say it's a Set)?

Here's the dummy example of what I'm trying to achive:

@Formula(value =
    "SELECT NEW com.example.entity.Person(p.name, p.age) FROM Person p")
lateinit var people :Set<Person>

Body:
From the JavaDoc for @Formula:

Defines a formula (derived value) which is a SQL fragment ...

You have to think of the fragment you write as an replacement in the select statement:

SELECT (formulaValue) AS propertyName FROM ....

Everything you can write into formulaValue can be used in @Formula.

Your example is not a valid SQL fragment and as you can see, it is not possible to return more than one value from a @Formula.

But you could use @Subselect and a wrapper object instead:

@Entity
@Subselect("SELECT name, age FROM Person p")
public class PersonWrapper {

  @Id
  private String name;

  private int age;

}

(in Java, as I'm not aware of the correct syntax of Kotlin)

If you really need the collection of these values in another entity, you need something to join on (which is missing in your example) and use that in an @OneToMany or @ManyToMany. Otherwise there is no use to have all these values in your entity, as all entities would have the same collection.


问:
QtWebEngine - synchronously execute JavaScript to read function result
I have the following method in one of my C++ classes (using QtWebEngine):

```<code>    QString get()
    {
        QString result;

        view->page()->runJavaScript("test();", [this](const QVariant &v)
            {
                result = v.toString();
            });

        return result;
    }
</code>```

It is to execute test() JS function and return the result of this invocation.

Unfortunately, the callback is asynchronous and the program crashes. How can I make it work?

答:
Dmitry's solution only works partially, unfortunately. In his example the code is invoked upon pressing a button. However, if the same code is moved to execute while the window is loading, the slot for the finished script (onScriptEnded) is never called. To fix this, I had to wrap the call to the evaluation of JS itself (called evaluateJavaScript in my project) in another QTimer::singleShot:

```<code>QTimer::singleShot(0, this, [&] { evaluateJavaScript(); });
</code>```

Unfortunately, in my real project I have many calls, often one evaluation waiting for another before it to finish. It's practically impossible to use this every single time so I still look for a solution.

Body:
I have the following method in one of my C++ classes (using QtWebEngine):

    QString get()
    {
        QString result;

        view->page()->runJavaScript("test();", [this](const QVariant &v)
            {
                result = v.toString();
            });

        return result;
    }

It is to execute test() JS function and return the result of this invocation.

Unfortunately, the callback is asynchronous and the program crashes. How can I make it work?

Body:
Dmitry's solution only works partially, unfortunately. In his example the code is invoked upon pressing a button. However, if the same code is moved to execute while the window is loading, the slot for the finished script (onScriptEnded) is never called. To fix this, I had to wrap the call to the evaluation of JS itself (called evaluateJavaScript in my project) in another QTimer::singleShot:

QTimer::singleShot(0, this, [&] { evaluateJavaScript(); });

Unfortunately, in my real project I have many calls, often one evaluation waiting for another before it to finish. It's practically impossible to use this every single time so I still look for a solution.


问:
Recursive Method Not Returning Expected Results (JAVA)
I was assisting a student with a question about for loops, essentially you have 2 numbers x and y and you want to sum every value from x to y together to get a total. For example 5 to 10 would print 45 (5+6+7+8+9+10). While helping this person I decided to write the program recursively for some practice and noticed that my recursive method wasn't returning 45, instead it just keeps returning 5. If anyone could explain to me what's going on I'd appreciate it! Thanks!</p>

```<code>public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        int sum = calc(num1, num2, 0 );

        return sum;
    }

    public static int calc(int num1, int num2, int total) {

        if(num1 <= num2)
        {
            total += num1;
            num1++;
            System.out.println(num1);
            calc(num1, num2,total);
        }

        return total;
    }

}
</code>```

答:
the problem with you code was mainly not doing any aggregation.. the value returned from

```<code>calc(num1, num2,total)
</code>```

is never stored.

replace:

```<code>total += num1;
num1++;
System.out.println(num1);
calc(num1, num2,total);
</code>```

with:

```<code>num1++;
System.out.println(num1);
total = num1 + calc(num1, num2 , total);
</code>```

a much simpler solution would be:

```<code>public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        if(num1 > num){ // break condition
            return 0;
        }

        // aggregation in a recursive manner
        return num1 + calc( num1+1 , num2);
    }
}
</code>```

Body:
I was assisting a student with a question about for loops, essentially you have 2 numbers x and y and you want to sum every value from x to y together to get a total. For example 5 to 10 would print 45 (5+6+7+8+9+10). While helping this person I decided to write the program recursively for some practice and noticed that my recursive method wasn't returning 45, instead it just keeps returning 5. If anyone could explain to me what's going on I'd appreciate it! Thanks!

public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        int sum = calc(num1, num2, 0 );

        return sum;
    }

    public static int calc(int num1, int num2, int total) {

        if(num1 <= num2)
        {
            total += num1;
            num1++;
            System.out.println(num1);
            calc(num1, num2,total);
        }

        return total;
    }

}

Body:
the problem with you code was mainly not doing any aggregation.. the value returned from

calc(num1, num2,total)

is never stored.

replace:

total += num1;
num1++;
System.out.println(num1);
calc(num1, num2,total);

with:

num1++;
System.out.println(num1);
total = num1 + calc(num1, num2 , total);

a much simpler solution would be:

public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        if(num1 > num){ // break condition
            return 0;
        }

        // aggregation in a recursive manner
        return num1 + calc( num1+1 , num2);
    }
}


问:
Check all numbers are equal
What is the best way to check that all numbers in the array (or list) are equal?

I think the solution as a loop that seek for the first unequal element ist maybe efficient, but not so elegant or readable. Any solutions in one line?

答:
Not one line though in the right language, I'm sure you could get it to one.

EDIT: Since you said C#...

```<code>return list.Length > 0 && list[0] == list.Aggregate(list[0], (current, i) => current & i);
</code>```

Title: Check all numbers are equal

Body:
Not one line though in the right language, I'm sure you could get it to one.

EDIT: Since you said C#...

return list.Length > 0 && list[0] == list.Aggregate(list[0], (current, i) => current & i);


问:
Improve DataTable performance when modifying class of cell
I'm very satisified using jquery DataTables, but I have found one situation where I need to boost performance. I'm updating the class of a cell depending on the data. To do this I'm using the render function and creating an api instance from the settings to get hold of the cell via the api. Is there a better way for doing this?</p>

```<code>{
        "data": "statusText", "className": "status",
        "render": function (data, type, full, meta) {
            switch (type) {
                case "display":
                    var api = new $.fn.dataTable.Api(meta.settings);
                    var td = api.cell({ row: meta.row, column: meta.col }).node();
                    switch (full.status) {
                        case Status.Saved:
                            $(td).addClass("status-saved");
                            break;
                        case Status.Sent:
                            $(td).addClass("status-sent");
                            break;
                        default:
                            $(td).addClass("status-saved");
                    }
                    return full.statusText;
                case "sort":
                    return full.status;
                default:
                    return full.statusText;
             }
        }
    }
</code>```

答: Found out that the rowCallback (documentation here) method is better than the render method. In rowCallback we have access to the DOM row and don’t have to new up api instance and lookup the cell. I still use jQuery and addClass to set the class. Will try plain vanilla instead of jQuery to try to improve performance even more. As suggested by @shyammakwana.me</p>

Body:
I'm very satisified using jquery DataTables, but I have found one situation where I need to boost performance. I'm updating the class of a cell depending on the data. To do this I'm using the render function and creating an api instance from the settings to get hold of the cell via the api. Is there a better way for doing this?

{
        "data": "statusText", "className": "status",
        "render": function (data, type, full, meta) {
            switch (type) {
                case "display":
                    var api = new $.fn.dataTable.Api(meta.settings);
                    var td = api.cell({ row: meta.row, column: meta.col }).node();
                    switch (full.status) {
                        case Status.Saved:
                            $(td).addClass("status-saved");
                            break;
                        case Status.Sent:
                            $(td).addClass("status-sent");
                            break;
                        default:
                            $(td).addClass("status-saved");
                    }
                    return full.statusText;
                case "sort":
                    return full.status;
                default:
                    return full.statusText;
             }
        }
    }


问:
Python loop ending but then ends but then repeats for no reason
I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again???

Here is my code where I think the problem is:

```<code>def Login(): #Login function
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    validuser = False
    while validuser == False:
        if usernameLog == username:
            print('Username accepted')

            time.sleep(1)

            userpassLog = input('Please enter a password: ')

            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validuser = True
            else:
                print('Please enter a valid password')
            validuser = False
        else:
            print('Invalid username please re-enter it.')
            validuser = False
            Login()
    f.close()
</code>```

答:
First to answer your question: under your else condition for a wrong password (under print('Please enter a valid password')), you have a non-indented validuser = False. So what happens is that the validuser = True that you set a bit earlier when the password was good is replaced instantly by a validuser = False. Simply indenting that line to put it within your else condition fixes your code :)

Now, talking optimisation/best practice... In your code you are using both an infinite loop conditional on a variable which is an iterative approach, and a call to your function within your function which is a recursive approach, which is not in my opinion a really good choice... Or at least not for the same level of the loop!

If you wanted to go fully iterative, then you would simply need to replace your Login() towards the end by

```<code>usernameLog = input('Please enter your username: ')
</code>```

Or, if you want to have both a recursive call and an iterative loop, you could loop only over the password:

```<code>def Login():
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    if usernameLog == username:
        print('Username accepted')

        time.sleep(1)

        validpassword = False
        while validpassword == False:
            userpassLog = input('Please enter a password: ')
            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validpassword = True
            else:
                print('Please enter a valid password')
                validpassword = False
    else:
        print('Invalid username please re-enter it.')
        Login()
    f.close()
</code>```

To be honest, re-opening the same file every time you enter a wrong username seems a bit of a waste of time, so I'd recommend using the iterative-only version if that's good with your assignment...

Body:
I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again???

Here is my code where I think the problem is:

def Login(): #Login function
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    validuser = False
    while validuser == False:
        if usernameLog == username:
            print('Username accepted')

            time.sleep(1)

            userpassLog = input('Please enter a password: ')

            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validuser = True
            else:
                print('Please enter a valid password')
            validuser = False
        else:
            print('Invalid username please re-enter it.')
            validuser = False
            Login()
    f.close()

Body:
First to answer your question: under your else condition for a wrong password (under print('Please enter a valid password')), you have a non-indented validuser = False. So what happens is that the validuser = True that you set a bit earlier when the password was good is replaced instantly by a validuser = False. Simply indenting that line to put it within your else condition fixes your code :)

Now, talking optimisation/best practice... In your code you are using both an infinite loop conditional on a variable which is an iterative approach, and a call to your function within your function which is a recursive approach, which is not in my opinion a really good choice... Or at least not for the same level of the loop!

If you wanted to go fully iterative, then you would simply need to replace your Login() towards the end by

usernameLog = input('Please enter your username: ')

Or, if you want to have both a recursive call and an iterative loop, you could loop only over the password:

def Login():
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    if usernameLog == username:
        print('Username accepted')

        time.sleep(1)

        validpassword = False
        while validpassword == False:
            userpassLog = input('Please enter a password: ')
            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validpassword = True
            else:
                print('Please enter a valid password')
                validpassword = False
    else:
        print('Invalid username please re-enter it.')
        Login()
    f.close()

To be honest, re-opening the same file every time you enter a wrong username seems a bit of a waste of time, so I'd recommend using the iterative-only version if that's good with your assignment...