问:
How to remove ordinal indicators of the Portuguese language string
In portuguese several names have the following characters:

```<code>feminine ª
and
masculine º
</code>```

I need to remove them from my string, but I can't find the right regex. Anyone able to help me out?

答:
The Portuguese ASCII code page is CP860. And the codes for those characters are

Feminine ª  - \xa6

Masculine º - \xa7

So you can iconv them to your locale and then sub or gsub.

```<code>fem <- iconv('\xa6', 'CP860', 'UTF-8')
masc <- iconv('\xa7', 'CP860', 'UTF-8')

s <- c('feminine ª', 'masculine º')

sub(fem, '', s)
#[1] "feminine "   "masculine º"

sub(masc, '', s)
#[1] "feminine ª" "masculine "
</code>```

Body:
In portuguese several names have the following characters:

feminine ª
and
masculine º

I need to remove them from my string, but I can't find the right regex. Anyone able to help me out?

Body:
The Portuguese ASCII code page is CP860. And the codes for those characters are

Feminine ª  - \xa6

Masculine º - \xa7

So you can iconv them to your locale and then sub or gsub.

fem <- iconv('\xa6', 'CP860', 'UTF-8')
masc <- iconv('\xa7', 'CP860', 'UTF-8')

s <- c('feminine ª', 'masculine º')

sub(fem, '', s)
#[1] "feminine "   "masculine º"

sub(masc, '', s)
#[1] "feminine ª" "masculine "


来源: stackexchange

问:
How to convert a List[List[Long]] to a List[List[Int]]?
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

```<code>val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
</code>```

how can it be converted to List[List[Int]]?

答:
can be achieved with simple transformation on collection using map function.

map works by applying a function to each element in the list. in your case nested lists are there. so you need to apply map function 2 times like below example...

```<code>val x : List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
println(x)

val y :List[List[Int]]= x.map(a => a.map(_.toInt))

println(y)
</code>```

Output :

```<code>List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What's the best way to convert a List[List[Long]] to a List[List[Int]] in Scala?

For example, given the following list of type List[List[Long]]

val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))

how can it be converted to List[List[Int]]?

Body:
can be achieved with simple transformation on collection using map function.

map works by applying a function to each element in the list. in your case nested lists are there. so you need to apply map function 2 times like below example...

val x : List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
println(x)

val y :List[List[Int]]= x.map(a => a.map(_.toInt))

println(y)

Output :

List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))


问:
Finite difference in Haskell, or how to disable potential optimizations
I'd like to implement the following naive (first order) finite differencing function:

```<code>finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h
</code>```

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

```<code>volatile double temp = x + h;
h = temp - x;
</code>```

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

```<code>let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h
</code>```

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

答:
One way is to look at the Core.

Specializing to Doubles (which will be the case most likely to trigger some optimization):

```<code>finite_difference :: Double -> (Double -> Double) -> Double -> Double
finite_difference h f x = ((f $ x + hh) - (f x)) / h
   where
        temp = x + h
        hh   = temp - x
</code>```

Is compiled to:

```<code>A.$wfinite_difference h f x =
    case f (case x of
                  D# x' -> D# (+## x' (-## (+## x' h) x'))
           ) of
        D# x'' -> case f x of D# y -> /## (-## x'' y) h
</code>```

And similarly (with even less rewriting) for the polymorphic version.

So while the variables are inlined, the math isn't optimized away.
Beyond looking at the Core, I can't think of a way to guarantee the property you want.

Body:
I'd like to implement the following naive (first order) finite differencing function:

finite_difference :: Fractional a => a -> (a -> a) -> a -> a
finite_difference h f x = ((f $ x + h) - (f x)) / h

As you may know, there is a subtle problem: one has to make sure that (x + h) and x differ by an exactly representable number. Otherwise, the result has a huge error, leveraged by the fact that (f $ x + h) - (f x) involves catastrophic cancellation (and one has to carefully choose h, but that is not my problem here).

In C or C++, the problem can be solved like this:

volatile double temp = x + h;
h = temp - x;

and the volatile modifier disables any optimization pertaining to the variable temp, so we are assured that a "clever" compiler will not optimize away those two lines.

I don't know enough Haskell yet to know how to solve this. I'm afraid that

let temp = x + h
    hh = temp - x
in ((f $ x + hh) - (f x)) / h

will get optimized away by Haskell (or the backend it uses). How do I get the equivalent of volatile here (if possible without sacrificing laziness)? I don't mind GHC specific answers.

Body:
One way is to look at the Core.

Specializing to Doubles (which will be the case most likely to trigger some optimization):

finite_difference :: Double -> (Double -> Double) -> Double -> Double
finite_difference h f x = ((f $ x + hh) - (f x)) / h
   where
        temp = x + h
        hh   = temp - x

Is compiled to:

A.$wfinite_difference h f x =
    case f (case x of
                  D# x' -> D# (+## x' (-## (+## x' h) x'))
           ) of
        D# x'' -> case f x of D# y -> /## (-## x'' y) h

And similarly (with even less rewriting) for the polymorphic version.

So while the variables are inlined, the math isn't optimized away.
Beyond looking at the Core, I can't think of a way to guarantee the property you want.

ContentLicense: CC BY-SA 3.0


问:
Having strange {"d":null} in JSON response
Please am doing a AJAX call to a web API as below

```<code>$.ajax({
         type: "POST",
         url: "CustomerService.asmx/GetAccounts",
         data: '{"custid":"' + cusID + '"}',
         contentType: "application/json; charset-utf-8",
         dataType: "json",
         success: function (data) {
             datatableVariable = $('#dtAccounts').DataTable({.......
</code>```

This is my ASP.NET Web Method

```<code><WebMethod()>
Public Sub GetAccounts(ByVal custid As Integer)

    Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"

    Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
    Dim accs = New List(Of Accounts)()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(sql)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Dim dr = cmd.ExecuteReader()
            If dr.HasRows Then
                While dr.Read
                    Dim acc = New Accounts() With {
                   .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                    .AccNum = dr("AccountNumber").ToString(),
                    .Descri = dr("Description").ToString(),
                    .CurrBalance = dr("CurrentBalance").ToString(),
                    .typOA = dr("TypeOfAccount").ToString(),
                    .Frozen = dr("Frozen").ToString()
                    }
                    accs.Add(acc)
                End While
            End If
        End Using
    End Using
    Dim js = New JavaScriptSerializer()
    Dim strResponse As String = js.Serialize(accs)
    Context.Response.Write(strResponse)
End Sub
</code>```

The JSON string response returned is the below with additional strange {"d":null} value that I dont know where its coming from

```<code>[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false,"typOA":0}]{"d":null}
</code>```

If I use Context.Response.Flush() it disappears but then I get another error from the browser Server cannot clear headers after HTTP headers have been sent.

Please can someone assist me to resolve this,been doing this for weeks now

Thanks a lot

答:
We have to clear the default response {d:null} from ASP.NET Webservice before giving the response on the server side by using Context.Response.Clear() and set the contentType

```<code>Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.AddHeader("content-length", stringJSON.Length.ToString())
Context.Response.Flush()
Context.Response.Write(stringJSON)
HttpContext.Current.ApplicationInstance.CompleteRequest()
</code>```

Body:
Please am doing a AJAX call to a web API as below

$.ajax({
         type: "POST",
         url: "CustomerService.asmx/GetAccounts",
         data: '{"custid":"' + cusID + '"}',
         contentType: "application/json; charset-utf-8",
         dataType: "json",
         success: function (data) {
             datatableVariable = $('#dtAccounts').DataTable({.......

This is my ASP.NET Web Method

<WebMethod()>
Public Sub GetAccounts(ByVal custid As Integer)

    Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"

    Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
    Dim accs = New List(Of Accounts)()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(sql)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Dim dr = cmd.ExecuteReader()
            If dr.HasRows Then
                While dr.Read
                    Dim acc = New Accounts() With {
                   .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                    .AccNum = dr("AccountNumber").ToString(),
                    .Descri = dr("Description").ToString(),
                    .CurrBalance = dr("CurrentBalance").ToString(),
                    .typOA = dr("TypeOfAccount").ToString(),
                    .Frozen = dr("Frozen").ToString()
                    }
                    accs.Add(acc)
                End While
            End If
        End Using
    End Using
    Dim js = New JavaScriptSerializer()
    Dim strResponse As String = js.Serialize(accs)
    Context.Response.Write(strResponse)
End Sub

The JSON string response returned is the below with additional strange {"d":null} value that I dont know where its coming from

[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false,"typOA":0}]{"d":null}

If I use Context.Response.Flush() it disappears but then I get another error from the browser Server cannot clear headers after HTTP headers have been sent.

Please can someone assist me to resolve this,been doing this for weeks now

Thanks a lot

Body:
We have to clear the default response {d:null} from ASP.NET Webservice before giving the response on the server side by using Context.Response.Clear() and set the contentType

Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.AddHeader("content-length", stringJSON.Length.ToString())
Context.Response.Flush()
Context.Response.Write(stringJSON)
HttpContext.Current.ApplicationInstance.CompleteRequest()


问:
Unit test function that is opening and reading a file
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!    </p>

```<code>func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}
</code>```

答:
You need to refactor your code and make more suitable for testing.

Here is how I would do it:

```<code>func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to open file: %s", fileName)
    }
    lines, err := readFile(file)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    return lines
}

func readFile(reader io.Reader) ([][]string, error) {
    r := csv.NewReader(reader)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines, err
}
</code>```

Then for testing you can simply use any data structure that implements the io.reader interface. For example, I use a bytes buffer, but you can choose a network connection:

```<code>func TestReadFile(t *testing.T) {
    var buffer bytes.Buffer
    buffer.WriteString("fake, csv, data")
    content, err := readFile(&buffer)
    if err != nil {
        t.Error("Failed to read csv data")
    }
    fmt.Print(content)
}
</code>```

Body:
I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!

func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}

Body:
You need to refactor your code and make more suitable for testing.

Here is how I would do it:

func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf("Failed to open file: %s", fileName)
    }
    lines, err := readFile(file)
    if err != nil {
        fmt.Printf("Failed to read file: %s", fileName)
    }
    return lines
}

func readFile(reader io.Reader) ([][]string, error) {
    r := csv.NewReader(reader)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines, err
}

Then for testing you can simply use any data structure that implements the io.reader interface. For example, I use a bytes buffer, but you can choose a network connection:

func TestReadFile(t *testing.T) {
    var buffer bytes.Buffer
    buffer.WriteString("fake, csv, data")
    content, err := readFile(&buffer)
    if err != nil {
        t.Error("Failed to read csv data")
    }
    fmt.Print(content)
}


问:
Is there an easier way to do this in python?
I want to try to find an easier way to do this and I haven't found any way to do it.

This is meant to be a menu that can be written in. I am trying to add personalized messages to the text to further make it human-like, however it seems very long and longer than it should be. sandwich_t is a question asking the user if they want a sandwich, beverage is asking the user if they want a beverage, etc.

if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with no ketchup"
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink no fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink, no fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich, no drink, no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Chasier: You ordered nothing. Why did you come here?"
```

答:
You could assemble the selection description part by part using format strings and a list index to select between "Yes" and "No" alternative texts:

```<code>selection  = "Cashier: In total so far you have ordered "
selection += ["no sandwich", f"a {sandwich}"][sandwich_t=="Yes"]
selection += " with "
selection += ["no drinks",   f"a {beverage_selection}"][beverage=="Yes"]
selection += ", "
selection += ["no fries",    f"{fries_selection} fries"][fries=="Yes"]
selection += " with "
selection += ["no ketchup",  f"{Ketchup_Selection} ketchup packets"][Ketchup=="Yes"]
selection += "."

print(selection)
print("Cashier: In total it will be $", total, "alright?")
print("You: Alright")
</code>```

The pattern for selection of a food item descriptions is:

```<code>["No-Text","Yes-Text"][state == "Yes"]
</code>```

This works because List[True] is equivalent to List[1] and List[False] is equivalent to List[0]

Body:
You could assemble the selection description part by part using format strings and a list index to select between "Yes" and "No" alternative texts:

selection  = "Cashier: In total so far you have ordered "
selection += ["no sandwich", f"a {sandwich}"][sandwich_t=="Yes"]
selection += " with "
selection += ["no drinks",   f"a {beverage_selection}"][beverage=="Yes"]
selection += ", "
selection += ["no fries",    f"{fries_selection} fries"][fries=="Yes"]
selection += " with "
selection += ["no ketchup",  f"{Ketchup_Selection} ketchup packets"][Ketchup=="Yes"]
selection += "."

print(selection)
print("Cashier: In total it will be $", total, "alright?")
print("You: Alright")

The pattern for selection of a food item descriptions is:

["No-Text","Yes-Text"][state == "Yes"]

This works because List[True] is equivalent to List[1] and List[False] is equivalent to List[0]


问:
ActiveMQ Artemis redelivery delay
Setup:

We have a Spring Boot application that is reading messages from an ActiveMQ Artemis JMS queue.

The messages are processing in a JPA transaction.

When there is an exception triggering a rollback in JPA, it also triggers a JMS rollback in Artemis that is setup with redelivery delay.

Our app is running in multiple instances in parallel and this cause optimistic locking issues when processing multiple messages that share common data.

Issue: When X messages are processed in parallel and there is optimistic locking issue, then only 1 message goes through and all the others are re-scheduled with the delay. When redelivery happens, then same as before the X-1 messages will arrive at the same time since the delay is the same and cause the same issue with only one going through.

Question: Does anyone know a way to add variance to the redelivery delay time of ActiveMQ Artemis?

Note: I know that there is an option for that in ActiveMQ 5.x called collisionAvoidanceFactor, but it is missing from ActiveMQ Artemis.

答:
As you note, there is no equivalent for collisionAvoidanceFactor in ActiveMQ Artemis. I know of no way to modify the redelivery delay in a similar manner. There is the redelivery-delay-multiplier, but that is enforced consistently across redeliveries and would not provide the variance that you're looking for.

You may consider using message grouping so that "messages that share common data" are consumed serially by the same consumer and therefore avoid the locking issues in the first place.

After looking at what it would take to implement this feature I opened ARTEMIS-2364. I'll be sending a pull-request soon so it will likely be in the next version of Artemis (i.e. 2.10).

Title: ActiveMQ Artemis redelivery delay


问:
Sequence processing with Azure Function & Service Bus
I have an issue with Azure Function Service Bus trigger.
The issue is Azure function cannot wait a message done before process a new message. It process Parallel, it not wait 5s before get next message. But i need it process sequencecy (as image bellow).
How can i do that?

```<code>[FunctionName("HttpStartSingle")]
    public static void Run(
 [ServiceBusTrigger("MyServiceBusQueue", Connection = "Connection")]string myQueueItem,
[OrchestrationClient] DurableOrchestrationClient starter,
ILogger log)
    {
        Console.WriteLine($"MessageId={myQueueItem}");
        Thread.Sleep(5000);
    }
</code>```

答:
In general, ordered messaging is not something I'd be striving to implement since the order can and at some point will be distorted. Saying that, in some scenarios, it's required. For that, you should either use Durable Function to orchestrate your messages or use Service Bus message Sessions.

Azure Functions has recently added support for ordered message delivery (accent on the delivery part as processing can still fail). It's almost the same as the normal Function, with a slight change that you need to instruct the SDK to utilize sessions.

```<code>public async Task Run(
  [ServiceBusTrigger("queue",
   Connection = "ServiceBusConnectionString",
   IsSessionsEnabled = true)] Message message, // Enable Sessions
   ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {Encoding.UTF8.GetString(message.MessageId)}");
    await _cosmosDbClient.Save(...);
}
</code>```

Here's a post for more detials.

Warning: using sessions will require messages to be sent with a session ID, potentially requiring a change on the sending side.

Body:
I have an issue with Azure Function Service Bus trigger.
The issue is Azure function cannot wait a message done before process a new message. It process Parallel, it not wait 5s before get next message. But i need it process sequencecy (as image bellow).
How can i do that?

[FunctionName("HttpStartSingle")]
    public static void Run(
 [ServiceBusTrigger("MyServiceBusQueue", Connection = "Connection")]string myQueueItem,
[OrchestrationClient] DurableOrchestrationClient starter,
ILogger log)
    {
        Console.WriteLine($"MessageId={myQueueItem}");
        Thread.Sleep(5000);
    }

Body:
In general, ordered messaging is not something I'd be striving to implement since the order can and at some point will be distorted. Saying that, in some scenarios, it's required. For that, you should either use Durable Function to orchestrate your messages or use Service Bus message Sessions.

Azure Functions has recently added support for ordered message delivery (accent on the delivery part as processing can still fail). It's almost the same as the normal Function, with a slight change that you need to instruct the SDK to utilize sessions.

public async Task Run(
  [ServiceBusTrigger("queue",
   Connection = "ServiceBusConnectionString",
   IsSessionsEnabled = true)] Message message, // Enable Sessions
   ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {Encoding.UTF8.GetString(message.MessageId)}");
    await _cosmosDbClient.Save(...);
}

Here's a post for more detials.

Warning: using sessions will require messages to be sent with a session ID, potentially requiring a change on the sending side.


问:
2 decimal places in web grid for mvc - need total value to display value with 2 decimal places
2 decimal places in web grid for mvc - need total value to display value with 2 decimal places</p>

```<code>@grid.GetHtml(

            tableStyle: "table",
            fillEmptyRows: true,
            headerStyle: "header",
            footerStyle: "grid-footer",
            mode: WebGridPagerModes.All,
            columns: new[]
            {
                grid.Column(columnName: "SelfBillInvoiceNumber", header: "Invoice Number"), //the model fields to display

                grid.Column(columnName: "SelfBillItemTotalvalue", header: "Total Value")
            })
</code>```

答:
You should change this line:

```<code>grid.Column(columnName: "SelfBillItemTotalvalue", header: "Total Value")
</code>```

in this one:

```<code>grid.Column(header: "Total Value", format: item => String.Format("{0:0.00}", item.SelfBillItemTotalvalue))
</code>```

Body:
2 decimal places in web grid for mvc - need total value to display value with 2 decimal places

@grid.GetHtml(

            tableStyle: "table",
            fillEmptyRows: true,
            headerStyle: "header",
            footerStyle: "grid-footer",
            mode: WebGridPagerModes.All,
            columns: new[]
            {
                grid.Column(columnName: "SelfBillInvoiceNumber", header: "Invoice Number"), //the model fields to display

                grid.Column(columnName: "SelfBillItemTotalvalue", header: "Total Value")
            })

Body:
You should change this line:

grid.Column(columnName: "SelfBillItemTotalvalue", header: "Total Value")

in this one:

grid.Column(header: "Total Value", format: item => String.Format("{0:0.00}", item.SelfBillItemTotalvalue))


问:
Using tuples in SQL "IN" clause
I have a table containing the fields group_id and group_type and I want to query the table for all the records having any tuple (group id, group type) from a list of tuples. For example, I want to be able to do something like:

```<code>SELECT *
FROM mytable
WHERE (group_id, group_type) IN (("1234-567", 2), ("4321-765", 3), ("1111-222", 5))
</code>```

A very similar question is already asked at: using tuples in sql in clause , but the solution proposed there presumes the tuple list is to be fetched from another table. This doesn't work in my case is the tuple values are hard coded.

One solution is to use string concatenation:

```<code>SELECT *
FROM mytable
WHERE group_id + STR(group_type, 1) IN ("1234-5672", "4321-7653", "1111-2225")
</code>```

But the problem is that the table is quite big and doing a string concatenation and conversion for each record would be very expensive.

Any suggestion?

答:
select * from table_name where 1=1 and (column_a, column_b) in ((28,1),(25,1))
```

Title: Using tuples in SQL "IN" clause

Body:
I have a table containing the fields group_id and group_type and I want to query the table for all the records having any tuple (group id, group type) from a list of tuples. For example, I want to be able to do something like:

SELECT *
FROM mytable
WHERE (group_id, group_type) IN (("1234-567", 2), ("4321-765", 3), ("1111-222", 5))

A very similar question is already asked at: using tuples in sql in clause , but the solution proposed there presumes the tuple list is to be fetched from another table. This doesn't work in my case is the tuple values are hard coded.

One solution is to use string concatenation:

SELECT *
FROM mytable
WHERE group_id + STR(group_type, 1) IN ("1234-5672", "4321-7653", "1111-2225")

But the problem is that the table is quite big and doing a string concatenation and conversion for each record would be very expensive.

Any suggestion?


问:
ASP.NET custom control for short term memory
I'm reasonably new to web programming, and I'm still struggling to get to grips with the fact that the server has a terrible short term memory, forgetting about what's on screen by the time you see it.

I'm currently trying to create a custom control that allows you to edit data fields inside a repeater. Depending on the format of the fields (The ElementFormat property), either a text box or a drop down list should be generated. Inside the markup of my page I have:

```<code><custom:EditFieldControl ID="EditFieldControl"
    runat="server"
    ElementId='<%#Eval("Id")%>'
    ElementValue='<%#Eval("Value")%>'
    ElementFormat='<%#Eval("Format")%>'
    Visible="false" />
</code>```

Control code-behind looks like this:

```<code>public class EditFieldControl : WebControl
{
    private TextBox textBox;
    private DropDownList dropDownList;

    protected override void CreateChildControls()
    {
        switch (The Format of the field)
        {
            case "Text":
            {
                textBox = new TextBox
                {
                    Text = The existing value,
                    CssClass = "FieldTextBox"
                };
                this.Controls.Add(textBox);
                break;
            }
            case "DropDownList":
            {
                dropDownList = new DropDownList
                {
                    //go get possible values from the database
                    CssClass = "FieldDropDown"
                };
                this.Controls.Add(dropDownList);
                break;
            }
            default:
                throw new ArgumentException("Invalid Format Type");
        }
        base.CreateChildControls();
    }

    public string Value
    {
        get
        {
            switch (ElementFormat)
            {
                case "DropDownList":
                    return dropDownList.SelectedValue;
                default:
                    return textBox.Text;
            }
        }
    }
}
</code>```

The problem is, when a "save this field" button is clicked, the server looks for the EditFieldControl in that bit of the repeater, finds it, and then calls the value method, which promptly errors because it is trying to access either a text box or drop down list that no longer exist. My question is, how do I get at the value that the user has type in/selected? I presume I have to recreate the control earlier in the lifecycle, I'm just not sure when.

答:
The asp:Repeater is not an ideal control to edit data, it's more used to display. Suitable for editing are FormView, DetailsView and the best in your case is probably the ListView control. You can define separate templates for display (ItemTemplate), editing (EditItemTemplate) and Inserting (InsertItemTemplate). The Value property needs a setter to allow two-way binding. Use Bind instead of Eval.

Hope this helps.

Body:
I'm reasonably new to web programming, and I'm still struggling to get to grips with the fact that the server has a terrible short term memory, forgetting about what's on screen by the time you see it.

I'm currently trying to create a custom control that allows you to edit data fields inside a repeater. Depending on the format of the fields (The ElementFormat property), either a text box or a drop down list should be generated. Inside the markup of my page I have:

<custom:EditFieldControl ID="EditFieldControl"
    runat="server"
    ElementId='<%#Eval("Id")%>'
    ElementValue='<%#Eval("Value")%>'
    ElementFormat='<%#Eval("Format")%>'
    Visible="false" />

Control code-behind looks like this:

public class EditFieldControl : WebControl
{
    private TextBox textBox;
    private DropDownList dropDownList;

    protected override void CreateChildControls()
    {
        switch (The Format of the field)
        {
            case "Text":
            {
                textBox = new TextBox
                {
                    Text = The existing value,
                    CssClass = "FieldTextBox"
                };
                this.Controls.Add(textBox);
                break;
            }
            case "DropDownList":
            {
                dropDownList = new DropDownList
                {
                    //go get possible values from the database
                    CssClass = "FieldDropDown"
                };
                this.Controls.Add(dropDownList);
                break;
            }
            default:
                throw new ArgumentException("Invalid Format Type");
        }
        base.CreateChildControls();
    }

    public string Value
    {
        get
        {
            switch (ElementFormat)
            {
                case "DropDownList":
                    return dropDownList.SelectedValue;
                default:
                    return textBox.Text;
            }
        }
    }
}

The problem is, when a "save this field" button is clicked, the server looks for the EditFieldControl in that bit of the repeater, finds it, and then calls the value method, which promptly errors because it is trying to access either a text box or drop down list that no longer exist. My question is, how do I get at the value that the user has type in/selected? I presume I have to recreate the control earlier in the lifecycle, I'm just not sure when.


问:
Integrating PDFJS in Angular
I'm creating a new component in Angular to show PDF file  , in order to that ,I used ng2-pdfjs-viewer following these steps in the link "https://www.npmjs.com/package/ng2-pdfjs-viewer" but it's not working. I don't know exactly where the problem.
here the html component:

<ng2-pdfjs-viewer
  #pdfViewer
 [pdfJsFolder]="'https://www.emse.fr/~picard/cours/1A/java/livretJava.pdf'"
  [externalWindow]="true"
  [downloadFileName]="'mytestfile.pdf'"
  [openFile]="false"
  [viewBookmark]="false"
  [download]="false">
 </ng2-pdfjs-viewer>
```

Can anyone explain where is the problem?

I have another Question is it possible to load pdf from an external link for example "D:\file.pdf".

答:
As per documentation of ng2-pdfjs-viewer(https://www.npmjs.com/package/ng2-pdfjs-viewer),  [pdfJsFolder] is used to set path to PDF.JS's web and build folders.

You should use pdfSrc attribute to set pdf's path. It is mentioned under usage section of documentation

E.g.

<ng2-pdfjs-viewer pdfSrc="your pdf file path"></ng2-pdfjs-viewer>

The documentation also states that uses Mozilla's PDF.JS behind the scenes.

Irrespective of that, glad you got the issue resolved

Title: Integrating PDFJS in Angular

Body:
I'm creating a new component in Angular to show PDF file  , in order to that ,I used ng2-pdfjs-viewer following these steps in the link "https://www.npmjs.com/package/ng2-pdfjs-viewer" but it's not working. I don't know exactly where the problem.
here the html component:

<ng2-pdfjs-viewer
  #pdfViewer
 [pdfJsFolder]="'https://www.emse.fr/~picard/cours/1A/java/livretJava.pdf'"
  [externalWindow]="true"
  [downloadFileName]="'mytestfile.pdf'"
  [openFile]="false"
  [viewBookmark]="false"
  [download]="false">
 </ng2-pdfjs-viewer>

Can anyone explain where is the problem?

I have another Question is it possible to load pdf from an external link for example "D:\file.pdf".


问:
seaborn/matplotlib change number of columns in legend object
I've seen Creating multi column legend in python seaborn plot but I think my question is a bit different. In short, I've got a dataframe that I'm plotting in seaborn's lmplot and getting a FacetGrid. Trouble is, there are tons of values for hue so I get a super long, single column legend. Code example below:

```<code>ers = sns.lmplot(
    data=emorb,
    x="Pb",
    y="Nd",
    row="Ridge Sys",
    hue="Seg Name",
    scatter=True,
    fit_reg=False,
    scatter_kws={"alpha":0.7, "edgecolor": "w"},
    palette=sns.color_palette("bright", 20),
    legend=True
)

ers.set(ylim=(0.5122,0.5134))

</code>```

I can access the legend object that is created by calling ers._legend and this returns an object with type Legend (basically, a matplotlib object). However, I can't then call to this legend object to change the number of columns, e.g., with:

```<code>l = ers._legend
l(ncols=9)
</code>```

Any suggestions, or am I missing something perhaps more obvious, such as a way to redraw the legend and specify any parameters?

Thanks.

答:
Whoops, figured it out:

The FacetGrid object has an attribute fig, i.e.

```<code>g = sns.lmplot()
parent_mpl_figure = g.fig
</code>```

And so if I set legend=False in sns.lmplot(), I can then specify parent_mpl_figure.legend(labels=[], ncol=9, bbox_to_anchor=(1,1)).

Written cleanly:

```<code>g = sns.lmplot(legend = False)
parent_mpl_figure = g.fig
parent_mpl_figure.legend(labels = [], ncol = 9, bbox_to_anchor = (1,1))
</code>```

Hope this is instructive for someone else / now to figure out how to have each Facet span the full color palette so that different hue groups within each Facet group are easier to distinguish...

Body:
I've seen Creating multi column legend in python seaborn plot but I think my question is a bit different. In short, I've got a dataframe that I'm plotting in seaborn's lmplot and getting a FacetGrid. Trouble is, there are tons of values for hue so I get a super long, single column legend. Code example below:

ers = sns.lmplot(
    data=emorb,
    x="Pb",
    y="Nd",
    row="Ridge Sys",
    hue="Seg Name",
    scatter=True,
    fit_reg=False,
    scatter_kws={"alpha":0.7, "edgecolor": "w"},
    palette=sns.color_palette("bright", 20),
    legend=True
)

ers.set(ylim=(0.5122,0.5134))

I can access the legend object that is created by calling ers._legend and this returns an object with type Legend (basically, a matplotlib object). However, I can't then call to this legend object to change the number of columns, e.g., with:

l = ers._legend
l(ncols=9)

Any suggestions, or am I missing something perhaps more obvious, such as a way to redraw the legend and specify any parameters?

Thanks.

Body:
Whoops, figured it out:

The FacetGrid object has an attribute fig, i.e.

g = sns.lmplot()
parent_mpl_figure = g.fig

And so if I set legend=False in sns.lmplot(), I can then specify parent_mpl_figure.legend(labels=[], ncol=9, bbox_to_anchor=(1,1)).

Written cleanly:

g = sns.lmplot(legend = False)
parent_mpl_figure = g.fig
parent_mpl_figure.legend(labels = [], ncol = 9, bbox_to_anchor = (1,1))

Hope this is instructive for someone else / now to figure out how to have each Facet span the full color palette so that different hue groups within each Facet group are easier to distinguish...


问:
Can Strapi be launched into AWS lambda?
i want a good cms/backend application to create/manage API on AWS.
strapi fits well for my requirement.
but i dont want to use EC2, lightsail, beanstalk etc

i want to use strapi on aws lambda
is it possible to deploy strapi on aws lambda?

答:
Since strapi is a nodejs project, you can use this project to deploy to aws lambda Apex up.

You can still deploy a monolith to aws lambda, but it is not suggested.

Title: Can Strapi be launched into AWS lambda?


问:
Django Query for Total Count of Records In ManyToMany Field
Given two models joined by a ManyToMany without a through table:

```<code>class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)
</code>```

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

```<code>count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()
</code>```

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?

答:
```<code>Recipe.ingredients.through.objects.filter(ingredient=YOUR_INGREDIENT_HERE).count()
</code>```

Recipe.through is the "secret" table that holds the objects for the many_to_many field, a new
Recipe_ingredients(django's default name) object is created. If you want to use how many recipes use the given ingredient you can just filter that table with your ingredient and get the count of it.

For your example these are created: (pseudo)

```<code>Recipe_ingredients(ingredient=sugar, recipe=apple_pie)
Recipe_ingredients(ingredient=sugar, recipe=doughnut)
Recipe_ingredients(ingredient=apple, recipe=apple_pie)
</code>```

from here you can calculate about anything with that table, if you want to know to the total uses of all the ingredients it is as simple as

```<code>Recipe.ingredients.through.objects.count()
</code>```

Body:
Given two models joined by a ManyToMany without a through table:

class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?

Body:
Recipe.ingredients.through.objects.filter(ingredient=YOUR_INGREDIENT_HERE).count()

Recipe.through is the "secret" table that holds the objects for the many_to_many field, a new
Recipe_ingredients(django's default name) object is created. If you want to use how many recipes use the given ingredient you can just filter that table with your ingredient and get the count of it.

For your example these are created: (pseudo)

Recipe_ingredients(ingredient=sugar, recipe=apple_pie)
Recipe_ingredients(ingredient=sugar, recipe=doughnut)
Recipe_ingredients(ingredient=apple, recipe=apple_pie)

from here you can calculate about anything with that table, if you want to know to the total uses of all the ingredients it is as simple as

Recipe.ingredients.through.objects.count()


问:
Disable HttpClient logging
I´m using commons-httpclient 3.1 in an integration test suite. The default logging for HttpClient is extremely noisy and I can't seem to turn it off. I've tried following the instructions here but none of them make any difference.

Mostly I just need to make the org.apache.http.wire logger shut up. Part of the problem is that I don't know what type of logger HttpClient is trying to use. I've never used this library before. I tried creating a log4j.properties file and dropping it in my test/resources folder, modifying the master logging.properties file in jre/lib, and sending in the various logging options to Maven as specified on the logging page, and none of them make any difference.

UPDATE: A correction: it appears the output in question is actually originating through jwebunit's usage of HttpClient, not my own.  Either way, it's not desirable.

UPDATE: Thanks for the attempts so far.  I've tried everything suggested below but still no luck.  I have a file commons-logging.properties in my src/test/resources folder with the following contents

```<code>org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.Log4jFactory
log4j.configuration=log4j.properties
</code>```

and a file log4j.properties in the same folder with the following contents

```<code>log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n

#This is the line that should make httpclient shut up
log4j.logger.org.apache.http=ERROR
</code>```

However, when I run my tests I still get a bunch of output like this:

```<code>21:57:41.413 [main] DEBUG org.apache.http.wire - << "                                   [\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "                                   [\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "                               </ul>[\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "    [\n]"
21:57:41.424 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "                   </div>[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "                </li>[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "            [\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "            [\r][\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "        </ul>[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "<div class="details">[\n]"
21:57:41.442 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "<div class="details-body details-precis  ">[\n]
"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "<div class="details-state">[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "</div>[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
Destroying 1 processes21:57:41.465 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
</code>```

This output for everything that comes across the wire is making this library unusable for me...that is until I can figure out how to turn it off.  Is there anything special I need to do to get this log configuration read in?

答:
With:

Log2J 2 2.11.2

HttpClient 4.5.7 (elasticsearch 7.0.0 rest client)

Using properties file to configure

One can add:

```<code>logger.httpclient.name=org.apache.http
logger.httpclient.level=info
</code>```

With 'httpclient' in the above example being a logical name you choose.

(Tested on Java 11 OpenFX application.)

Title: Disable HttpClient logging

Body:
I´m using commons-httpclient 3.1 in an integration test suite. The default logging for HttpClient is extremely noisy and I can't seem to turn it off. I've tried following the instructions here but none of them make any difference.

Mostly I just need to make the org.apache.http.wire logger shut up. Part of the problem is that I don't know what type of logger HttpClient is trying to use. I've never used this library before. I tried creating a log4j.properties file and dropping it in my test/resources folder, modifying the master logging.properties file in jre/lib, and sending in the various logging options to Maven as specified on the logging page, and none of them make any difference.

UPDATE: A correction: it appears the output in question is actually originating through jwebunit's usage of HttpClient, not my own.  Either way, it's not desirable.

UPDATE: Thanks for the attempts so far.  I've tried everything suggested below but still no luck.  I have a file commons-logging.properties in my src/test/resources folder with the following contents

org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.Log4jFactory
log4j.configuration=log4j.properties

and a file log4j.properties in the same folder with the following contents

log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n

#This is the line that should make httpclient shut up
log4j.logger.org.apache.http=ERROR

However, when I run my tests I still get a bunch of output like this:

21:57:41.413 [main] DEBUG org.apache.http.wire - << "                                   [\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "                                   [\r][\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.413 [main] DEBUG org.apache.http.wire - << "    [\n]"
21:57:41.424 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "
[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "
[\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "            [\r][\n]"
21:57:41.425 [main] DEBUG org.apache.http.wire - << "            [\r][\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.433 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.442 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "
[\n]
"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.443 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "
[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\n]"
21:57:41.455 [main] DEBUG org.apache.http.wire - << "[\r][\n]"
Destroying 1 processes21:57:41.465 [main] DEBUG org.apache.http.wire - << "[\r][\n]"

This output for everything that comes across the wire is making this library unusable for me...that is until I can figure out how to turn it off.  Is there anything special I need to do to get this log configuration read in?

Body:
With:

Log2J 2 2.11.2

HttpClient 4.5.7 (elasticsearch 7.0.0 rest client)

Using properties file to configure

One can add:

logger.httpclient.name=org.apache.http
logger.httpclient.level=info

With 'httpclient' in the above example being a logical name you choose.

(Tested on Java 11 OpenFX application.)


问:
how can i add a css file to body of a page?
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window. </p>

<p>Thanks </p>

答:
When including your stylesheet, use this:</p>

```<code><link rel="stylesheet" media="print" href="stylesheet.css" />
</code>```

Body:
I am working on a page which has a print view so when the user clicks on "Print" a new window pops up and I want to add a .css file just for that window.

Thanks

Body:
When including your stylesheet, use this:

<link rel="stylesheet" media="print" href="stylesheet.css" />


问:
I'm having trouble installing TestNG on eclipse Photon Release (4.8.0), OS-win10, java version 10.0.2
I'm having trouble installing TestNG on eclipse Photon Release (4.8.0), OS-win10, java version 10.0.2

I get the below error. Also when I tried to access testng.org it says "Service Temporarily Unavailable". Please help. Thank you.

"HTTP Server 'Service Unavailable': http://beust.com/eclipse/content.xml
HttpComponents connection error response code 503."

Scrrenshot of the error

答:
I had also faced same issue in latest version of Eclipse(as of today) and following is the workaround that worked for me

In Install new Software dialog of Eclipse enter URL http://beust.com/eclipse instead of https://beust.com/eclipse

Happy testing :-)


问:
Check checked checkbox in Laravel
I have this code:

```<code>$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]
</code>```

And I have checkbox :

```<code>@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}">
<label for="input-15">{{ $language->name }}</label>
</fieldset>
@endforeach
</code>```

How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?

答:
If $language->id value you are looking for, and you create an array of checked language ids from $arrayWithSelectedValues you can do:

```<code><input
    type="checkbox"
    @if(in_array($language->id, $languages))
       checked
    @endif
>
</code>```

You can collected the language IDs like so:

```<code>$languages = [];
foreach ($arrayWithSelectedValues as $selectedValues) {
    $languages[] = $selectedValues['language_id'];
}
</code>```

Title: Check checked checkbox in Laravel

Body:
I have this code:

$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]

And I have checkbox :

@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="{{ $language->id }}">
{{ $language->name }}
</fieldset>
@endforeach

How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?

Body:
If $language->id value you are looking for, and you create an array of checked language ids from $arrayWithSelectedValues you can do:

<input
    type="checkbox"
    @if(in_array($language->id, $languages))
       checked
    @endif
>

You can collected the language IDs like so:

$languages = [];
foreach ($arrayWithSelectedValues as $selectedValues) {
    $languages[] = $selectedValues['language_id'];
}


问:
Resetting MySQL Root Password with XAMPP on Localhost
So for the past hour I've been trying to figure out how to reset my 'root' password for MySQL as I cannot log into PHPMyAdmin. I've tried changing the password in the config.inc.php file and searching through other methods. I cannot find a successful way. A few months ago I changed it as a test password but now I forget what it was. If anyone can help, that would be great. (I'm running on a Windows computer).</p>

答:
Start the Apache Server and MySQL instances from the XAMPP control panel.

Now goto to your localhost.

Click on user accounts -> Click on Edit privileges -> You will find an option change password just change password as you want click on go. Image are given below

If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.

Open terminal window (not mac default terminal please check attached image)

Then Run apt-get update in the newly opened terminal.

Then run apt-get install nano this will install nano

CD to cd ../opt/lampp/phpmyadmin

Open and Edit nano config.inc.php and save.


问:
Extract value inside square brackets within another square bracket based on key
I have a data like below from where I need to extract data by key.

```<code>string filter=[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]
</code>```

I checked similar cases and able to get below code only which is not giving results based on key

I have tried

```<code>Regex.Match(filter, @"\[(.*?)\]")
</code>```

if I gives Regn, I need to get Rasna

and if I gives LUB, it should give COMMERCIAL and like that

答:
If you want to match that single value you could use a positive lookbehind and a negated character class:

```<code>(?<=\[Regn,=,)[^]\r\n]+(?=\])
</code>```

Explanation

(?<=\[Regn,=,)

[^]\r\n]+ Negated character class, match not a ] or newline (Add what you also would not want to match(

(?=\]) Assert what is on the right is a ]

See a .NET regex demo or a C# DEMO

```<code>string[] strings = { "LUB", "Pgm", "Regn", "Month", "Year", "Bywhat" };

foreach (string s in strings)
{
    string filter = @"[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";
    string pattern = string.Format(@"(?<=\[{0},=,)[^]\r\n]+(?=\])", s);
    var m = Regex.Match(filter, pattern);
    Console.WriteLine(m.Value);
}
</code>```

Result

```<code>COMMERCIAL
PRIVATE
Rasna
06
2018
M
</code>```

Body:
I have a data like below from where I need to extract data by key.

string filter=[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]

I checked similar cases and able to get below code only which is not giving results based on key

I have tried

Regex.Match(filter, @"\[(.*?)\]")

if I gives Regn, I need to get Rasna

and if I gives LUB, it should give COMMERCIAL and like that

Body:
If you want to match that single value you could use a positive lookbehind and a negated character class:

(?<=\[Regn,=,)[^]\r\n]+(?=\])

Explanation

(?<=\[Regn,=,)

[^]\r\n]+ Negated character class, match not a ] or newline (Add what you also would not want to match(

(?=\]) Assert what is on the right is a ]

See a .NET regex demo or a C# DEMO

string[] strings = { "LUB", "Pgm", "Regn", "Month", "Year", "Bywhat" };

foreach (string s in strings)
{
    string filter = @"[[LUB,=,COMMERCIAL],AND,[Pgm,=,PRIVATE],AND,[Regn,=,Rasna],AND,[Month,=,06],AND,[Year,=,2018],AND,[Bywhat,=,M]]";
    string pattern = string.Format(@"(?<=\[{0},=,)[^]\r\n]+(?=\])", s);
    var m = Regex.Match(filter, pattern);
    Console.WriteLine(m.Value);
}

Result

COMMERCIAL
PRIVATE
Rasna
06
2018
M


问:
Can code-first Entity Framework do cross database queries with SQL Server DBs on the same box?
I know there have been a lot of questions about Entity Framework doing cross database queries on the same server posted to stackoverflow. Mostly the answer seems to be 'no', and this link from way back in 2008 is referenced.  However, Entity Framework is changing all the time and with CTP5 out, I'm wondering if the answer is still the same - that you can't do it, or you can do it if you manually edit the edmx file, or you have to use views.  This feature alone is the reason I'm still tied to Linq-to-SQL, as we have multiple SQL Server 2008 databases on the same server and need to query across them.  Polluting our databases with hundreds of select * views is not an option, and with code-first development I don't have an edmx file to edit.  I was playing with the pubs database to see if I could get somewhere, but I'm stuck.  Any suggestions?

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;

namespace DbSchema {
    public class Employee {
        [Key]
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public short JobID { get; set; }
        public Job Job { get; set; }
    }

    public class Job {
        [Key]
        public short ID { get; set; }
        public string Description { get; set; }
    }

    public class PubsRepository : DbContext {
        public DbSet<Employee> Employee { get; set; }
        public DbSet<Job> Job { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            // employee
            var eeMap = modelBuilder.Entity<Employee>();
            eeMap.ToTable("employee", "dbo"); // <-- how do I reference another database?
            eeMap.Property(e => e.ID).HasColumnName("emp_id");
            eeMap.Property(e => e.FirstName).HasColumnName("fname");
            eeMap.Property(e => e.LastName).HasColumnName("lname");
            eeMap.Property(e => e.JobID).HasColumnName("job_id");

            // job
            var jobMap = modelBuilder.Entity<Job>();
            jobMap.Property(j => j.ID).HasColumnName("job_id");
            jobMap.Property(j => j.Description).HasColumnName("job_desc");
        }

        public List<Employee> GetManagers() {
            var qry = this.Employee.Where(x => x.Job.Description.Contains("manager"));
            Debug.WriteLine(qry.ToString());
            return qry.ToList(); // <-- error here when referencing another database!
        }
    }
}
</code>```

答:
There are two ways to do it.

One is, of course, to create a view in one of the databases which does the cross database query, then access the veiw from your model as you would any other view.

The other was it to create the same cross database query view within the model itself by creating a DefiningQuery. This is most similar to how you would do it with SQLClient. In SQLClient, you'd create the view in T-SQL as the text of a SQLCommand, then execute the command to create a data reader or data table. Here you use the same T-SQL to create a DefiningQuery, then link it up with an Entity that you create manually. It's a bit of work, but it does exactly what you'd want it to.

Here's a link on using DefiningQuerys: http://msdn.microsoft.com/en-us/library/cc982038.aspx.

If you happen to have the book "Programming Entity Framework" by Lerman from O'Reilly, there a good example in chapter 16.

So you have to jump through a few hoops to do what you used to do directly with SQLClient, BUT you get the modeled Entity.

ContentLicense: CC BY-SA 2.5

Body:
I know there have been a lot of questions about Entity Framework doing cross database queries on the same server posted to stackoverflow. Mostly the answer seems to be 'no', and this link from way back in 2008 is referenced.  However, Entity Framework is changing all the time and with CTP5 out, I'm wondering if the answer is still the same - that you can't do it, or you can do it if you manually edit the edmx file, or you have to use views.  This feature alone is the reason I'm still tied to Linq-to-SQL, as we have multiple SQL Server 2008 databases on the same server and need to query across them.  Polluting our databases with hundreds of select * views is not an option, and with code-first development I don't have an edmx file to edit.  I was playing with the pubs database to see if I could get somewhere, but I'm stuck.  Any suggestions?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;

namespace DbSchema {
    public class Employee {
        [Key]
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public short JobID { get; set; }
        public Job Job { get; set; }
    }

    public class Job {
        [Key]
        public short ID { get; set; }
        public string Description { get; set; }
    }

    public class PubsRepository : DbContext {
        public DbSet<Employee> Employee { get; set; }
        public DbSet<Job> Job { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            // employee
            var eeMap = modelBuilder.Entity<Employee>();
            eeMap.ToTable("employee", "dbo"); // <-- how do I reference another database?
            eeMap.Property(e => e.ID).HasColumnName("emp_id");
            eeMap.Property(e => e.FirstName).HasColumnName("fname");
            eeMap.Property(e => e.LastName).HasColumnName("lname");
            eeMap.Property(e => e.JobID).HasColumnName("job_id");

            // job
            var jobMap = modelBuilder.Entity<Job>();
            jobMap.Property(j => j.ID).HasColumnName("job_id");
            jobMap.Property(j => j.Description).HasColumnName("job_desc");
        }

        public List<Employee> GetManagers() {
            var qry = this.Employee.Where(x => x.Job.Description.Contains("manager"));
            Debug.WriteLine(qry.ToString());
            return qry.ToList(); // <-- error here when referencing another database!
        }
    }
}


问:
DatabaseError: ORA-00900: invalid SQL statement
please help new to coding

I keep getting an error

in getSidsWithStatusX
      sip.execute(query) DatabaseError: ORA-00900: invalid SQL statement

```<code>def getSidsWithStatusX(startDate, statusX, endDate=None):
    query = cfg.GET_STARTDATE_QUERY.format(startDate=startDate)
    if (endDate):
        query += cfg.GET_ENDDATE_QUERY.format(endDate=endDate)

    query += cfg.GET_STATUSID_QUERY.format(statusX=statusX)
    logger.debug(query)

    sip = rdb.getCursor('sip')
    sip.execute(query)
    data = sip.fetchall()
    sip.rollback()
    sids = []
</code>```

Im passing :

```<code>GET_STARTDATE_QUERY = """
                        select sid
                        from contact_requests
                        where entry_date > '{startDate:'%d-%b-%Y'}'
                    """

GET_ENDDATE_QUERY = """
                    and entry_date < '{endDate:'%d-%b-%Y'}'
                """

GET_STATUSID_QUERY = """
                           and request_status_id = '{statusX:s}'
                       """
</code>```

答:
You shouldn't have quotes around the format specification in the format string. Those quotes are being copied into the result, so you end up with two sets of quotes, one from the quote before { and after }, and the other from the quotes around %d-%b-%Y.

```<code>GET_STARTDATE_QUERY = """
                        select sid
                        from contact_requests
                        where entry_date > '{startDate:%d-%b-%Y}'
                    """
</code>```

Body:
please help new to coding

I keep getting an error

in getSidsWithStatusX
      sip.execute(query) DatabaseError: ORA-00900: invalid SQL statement

def getSidsWithStatusX(startDate, statusX, endDate=None):
    query = cfg.GET_STARTDATE_QUERY.format(startDate=startDate)
    if (endDate):
        query += cfg.GET_ENDDATE_QUERY.format(endDate=endDate)

    query += cfg.GET_STATUSID_QUERY.format(statusX=statusX)
    logger.debug(query)

    sip = rdb.getCursor('sip')
    sip.execute(query)
    data = sip.fetchall()
    sip.rollback()
    sids = []

Im passing :

GET_STARTDATE_QUERY = """
                        select sid
                        from contact_requests
                        where entry_date > '{startDate:'%d-%b-%Y'}'
                    """

GET_ENDDATE_QUERY = """
                    and entry_date < '{endDate:'%d-%b-%Y'}'
                """

GET_STATUSID_QUERY = """
                           and request_status_id = '{statusX:s}'
                       """

Body:
You shouldn't have quotes around the format specification in the format string. Those quotes are being copied into the result, so you end up with two sets of quotes, one from the quote before { and after }, and the other from the quotes around %d-%b-%Y.

GET_STARTDATE_QUERY = """
                        select sid
                        from contact_requests
                        where entry_date > '{startDate:%d-%b-%Y}'
                    """


问:
UIPrintInteractionController always shows current WKWebView instead of iFrame content
I've got two web pages: /invoice_display, which shows an invoice and has a "Print" button. The "Print" button creates a hidden iFrame and sets the source to /invoice_printable which has a window.print() embedded in the page that executes on page load.

This all works great in a web browser, but I'm having an issue when loading in a WKWebView on iOS. The issue is that the UIPrintInteractionController preview always shows /invoice_display instead of /invoice_printable.

Here's the current code:

/invoice_printable

```<code><script type="text/javascript">
    window.onload = function () {
        window.print();
    }
</script>
</code>```

UIViewController

```<code>- (void)createWebView {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserScript *script = [[WKUserScript alloc] initWithSource:@"window.print = function() { window.webkit.messageHandlers.print.postMessage('print') }"
                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
                                               forMainFrameOnly:NO];
    [config.userContentController addUserScript:script];
    [config.userContentController addScriptMessageHandler:self name:@"print"];

    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;

    [self.view addSubview:webView];
    self.webView = webView;
}

- (void)printCurrentPage {
    UIPrintInteractionController *printInteractionController = [UIPrintInteractionController sharedPrintController];
    printInteractionController.printFormatter = self.webView.viewPrintFormatter;
    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed) {
            if (error) {
                NSLog(@"Print failed: %@", error);
            } else {
                NSLog(@"Print cancelled");
            }
        }
    };

    [printInteractionController presentAnimated:YES completionHandler:completionHandler];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"print"]) {
        NSLog(@"Got a 'print' message from the web page");
        [self printCurrentPage];
    } else {
        NSLog(@"Got a web page message other than 'print'");
    }
}
</code>```

How can I get the printable iFrame content to show up in UIPrintInteractionController instead of the originating web page?

答:
I figured out a solution. I'm using webView:decidePolicyForNavigationAction:decisionHandler: to detect the iFrame. I then use the iFrame's NSURLRequest to get the web page as NSData, which I then pass into a UIMarkupTextPrintFormatter as an NSString. Finally, that formatter gets passed to the UIPrintInteractionController. Whew.

Here's the working code:

```<code>-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (!navigationAction.targetFrame.isMainFrame) {
        NSLog(@"Got an iFrame: %@", navigationAction.request.URL.absoluteString);
        // Save this request so we can use it later for invoice printing
        self.printRequest = navigationAction.request;
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
</code>```

And then once the web page calls window.print()...

```<code>- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"print"]) {
        NSLog(@"Got a 'print' message from the web page");
        [self GETWebDataWithRequest:self.printRequest];
    } else {
        NSLog(@"Got a web page message other than 'print'");
    }
}

- (void)GETWebDataWithRequest:(NSURLRequest *)request {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    NSURLSessionDataTask *getDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if(!error) {
            NSLog(@"Got web data for url: %@", request.URL);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self printCurrentPageWithData:data];
            });
        } else {
            NSLog(@"Web data error: %@", error);
        }
    }];

    [getDataTask resume];
}

- (void)printCurrentPageWithData:(NSData *)webData {
    NSString *htmlString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
    UIMarkupTextPrintFormatter *markupTextPrintFormatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:htmlString];
    UIPrintInteractionController *printInteractionController = [UIPrintInteractionController sharedPrintController];
    printInteractionController.printFormatter = markupTextPrintFormatter;

    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed) {
            if (error) {
                NSLog(@"Print failed: %@", error);
            } else {
                NSLog(@"Print cancelled");
            }
        }
    };
}
</code>```

Body:
I've got two web pages: /invoice_display, which shows an invoice and has a "Print" button. The "Print" button creates a hidden iFrame and sets the source to /invoice_printable which has a window.print() embedded in the page that executes on page load.

This all works great in a web browser, but I'm having an issue when loading in a WKWebView on iOS. The issue is that the UIPrintInteractionController preview always shows /invoice_display instead of /invoice_printable.

Here's the current code:

/invoice_printable

UIViewController

- (void)createWebView {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserScript *script = [[WKUserScript alloc] initWithSource:@"window.print = function() { window.webkit.messageHandlers.print.postMessage('print') }"
                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
                                               forMainFrameOnly:NO];
    [config.userContentController addUserScript:script];
    [config.userContentController addScriptMessageHandler:self name:@"print"];

    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;

    [self.view addSubview:webView];
    self.webView = webView;
}

- (void)printCurrentPage {
    UIPrintInteractionController *printInteractionController = [UIPrintInteractionController sharedPrintController];
    printInteractionController.printFormatter = self.webView.viewPrintFormatter;
    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed) {
            if (error) {
                NSLog(@"Print failed: %@", error);
            } else {
                NSLog(@"Print cancelled");
            }
        }
    };

    [printInteractionController presentAnimated:YES completionHandler:completionHandler];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"print"]) {
        NSLog(@"Got a 'print' message from the web page");
        [self printCurrentPage];
    } else {
        NSLog(@"Got a web page message other than 'print'");
    }
}

How can I get the printable iFrame content to show up in UIPrintInteractionController instead of the originating web page?

Body:
I figured out a solution. I'm using webView:decidePolicyForNavigationAction:decisionHandler: to detect the iFrame. I then use the iFrame's NSURLRequest to get the web page as NSData, which I then pass into a UIMarkupTextPrintFormatter as an NSString. Finally, that formatter gets passed to the UIPrintInteractionController. Whew.

Here's the working code:

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (!navigationAction.targetFrame.isMainFrame) {
        NSLog(@"Got an iFrame: %@", navigationAction.request.URL.absoluteString);
        // Save this request so we can use it later for invoice printing
        self.printRequest = navigationAction.request;
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

And then once the web page calls window.print()...

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"print"]) {
        NSLog(@"Got a 'print' message from the web page");
        [self GETWebDataWithRequest:self.printRequest];
    } else {
        NSLog(@"Got a web page message other than 'print'");
    }
}

- (void)GETWebDataWithRequest:(NSURLRequest *)request {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    NSURLSessionDataTask *getDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if(!error) {
            NSLog(@"Got web data for url: %@", request.URL);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self printCurrentPageWithData:data];
            });
        } else {
            NSLog(@"Web data error: %@", error);
        }
    }];

    [getDataTask resume];
}

- (void)printCurrentPageWithData:(NSData *)webData {
    NSString *htmlString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
    UIMarkupTextPrintFormatter *markupTextPrintFormatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:htmlString];
    UIPrintInteractionController *printInteractionController = [UIPrintInteractionController sharedPrintController];
    printInteractionController.printFormatter = markupTextPrintFormatter;

    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed) {
            if (error) {
                NSLog(@"Print failed: %@", error);
            } else {
                NSLog(@"Print cancelled");
            }
        }
    };
}


问:
@ng-bootstrap, *ngFor and dynamic columns
I have an array of items which I want to display in a grid, and have 3 items per row. I'm using @ng-bootstrap/ng-bootstrap in my Angular 7 application. Using an *ngFor I can't figure out how to have it actually do that.  I've got a small stackblitz which just does this:

      <input type="checkbox" >{{ name }}

```

I had assumed that since each label said col-4 that it would end up forcing a new row after every third item.

答:
Fixed it stackblitz

you forgot to add class row and bootstrap to stackblitz

```<code><div class="container">
  <div class='row'>
    <label class="col-4" *ngFor="let name of items">
      <input type="checkbox" >{{ name }}
    </label>
  </div>
</div>
</code>```

EDIT
 ng-bootstrap is just the javascript for dropdown etc, but you need to install the bootstrap.css file too  check New blitzy in angular.json

```<code>    ],
    "styles": [
      "src/styles.css",
      "src/bootstrap.min.css"
    ],
</code>```

on your machine you will do ( if using npm)

```<code>npm i bootstrap --save
</code>```

then in angular.json

```<code>            "styles": [
...
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
...
            ],
</code>```

Body:
I have an array of items which I want to display in a grid, and have 3 items per row. I'm using @ng-bootstrap/ng-bootstrap in my Angular 7 application. Using an *ngFor I can't figure out how to have it actually do that.  I've got a small stackblitz which just does this:

      <input type="checkbox" >{{ name }}

I had assumed that since each label said col-4 that it would end up forcing a new row after every third item.

Body:
Fixed it stackblitz

you forgot to add class row and bootstrap to stackblitz

<div class="container">
  <div class='row'>
    <label class="col-4" *ngFor="let name of items">
      <input type="checkbox" >{{ name }}
    </label>
  </div>
</div>

EDIT
 ng-bootstrap is just the javascript for dropdown etc, but you need to install the bootstrap.css file too  check New blitzy in angular.json

    ],
    "styles": [
      "src/styles.css",
      "src/bootstrap.min.css"
    ],

on your machine you will do ( if using npm)

npm i bootstrap --save

then in angular.json

            "styles": [
...
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
...
            ],


问:
Whats the other way to write this code? Any shortcuts in SQL?
My first week with SQL, and in class, we are going over some tasks. Can you suggest how to eliminate time by writing this code a little bit shorter (if possible).

TASK: Best Customers Per Employee

Create a query that retrieves the total sales to each customer who spent more than $5,000 by each employee (Hint: use the Order Subtotals query already in the database). The result should be sorted ascending for employee last name and then the total descending within each employee.

```<code>SELECT Employees.EmployeeID, LastName, FirstName, CompanyName,
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders

JOIN Customers ON Orders.CustomerID = Customers.CustomerID
JOIN [Order Details] ON [Order Details].OrderID = [Orders].OrderID
JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID

GROUP BY Customers.CompanyName, Employees.EmployeeID, Employees.LastName, Employees.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY Employees.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC
</code>```

答:
Do the allies like Customers c  Orders o Employee e Order Details od.</p>

```<code>SELECT E.EmployeeID, LastName, FirstName, CompanyName,
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders O

JOIN Customers C ON O.CustomerID = C.CustomerID
JOIN [Order Details] OD ON OD.OrderID = O.OrderID
JOIN Employees E ON O.EmployeeID=E.EmployeeID

GROUP BY C.CompanyName, E.EmployeeID, E.LastName, E.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY E.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC
</code>```

Body:
My first week with SQL, and in class, we are going over some tasks. Can you suggest how to eliminate time by writing this code a little bit shorter (if possible).

TASK: Best Customers Per Employee

Create a query that retrieves the total sales to each customer who spent more than $5,000 by each employee (Hint: use the Order Subtotals query already in the database). The result should be sorted ascending for employee last name and then the total descending within each employee.

SELECT Employees.EmployeeID, LastName, FirstName, CompanyName,
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders

JOIN Customers ON Orders.CustomerID = Customers.CustomerID
JOIN [Order Details] ON [Order Details].OrderID = [Orders].OrderID
JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID

GROUP BY Customers.CompanyName, Employees.EmployeeID, Employees.LastName, Employees.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY Employees.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC

Body:
Do the allies like Customers c  Orders o Employee e Order Details od.

SELECT E.EmployeeID, LastName, FirstName, CompanyName,
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders O

JOIN Customers C ON O.CustomerID = C.CustomerID
JOIN [Order Details] OD ON OD.OrderID = O.OrderID
JOIN Employees E ON O.EmployeeID=E.EmployeeID

GROUP BY C.CompanyName, E.EmployeeID, E.LastName, E.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY E.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC


问:
Communication between two POST requests

Question

I have a Django form in which the user submits a text search string (full example setup below).

Question: how can (and should) two POST requests, currently handled by the same view tied to the same URL pattern, "talk" to each other via the first post request passing off data to the second?

The crux of the problem is in the block elif request.POST["router"] == "csv" below: I need to to access the results object from the first POST request, but basic Python scoping/control flow prevents me from doing that.

Currently, everything lives within the same URLconf path and is handled differently based on (1) whether the request is GET/POST, (2) what the POST request name/value attributes are from its <input> tag.

Setup

Imports:

```<code>import csv
from time import time_ns

from django import forms
from django import models
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import path
</code>```

In my_app/urls.py:

```<code>urlpatterns = [
    path("run/<uuid:pk>", views.run),
]
</code>```

In my_app/forms.py:

```<code>class RunForm(forms.Form):
    start = forms.DateTimeField()
    query = forms.CharField()
</code>```

In my_app/templates/my_app/run.html:

```<code><form method="post">
    {% csrf_token %}
    <h1>Launch a search</h1>
    <table>
    {{ form.as_table }}
    </table>
    <input type="hidden" name="router" value="run">
    <input type="submit" value="Submit">
</form>
</code>```

In my_app/templates/my_app/results.html:

```<code><table>
{% for row in results %}
<tr>
{% for val in row %}
<td>{{ val }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

<form method="post">
  {% csrf_token %}
  <input type="hidden" name="router" value="csv">
  <input type="submit" value="Download to CSV">
</form>
</code>```

In my_app/views.py:

```<code>def run(request, pk):
    if request.method == "POST":
        if request.POST["router"] == "run":
            form = RunForm(request.POST)
            if form.is_valid():
                obj = get_object_or_404(MyModel, pk=pk)
                # Get some dynamic results from database based
                # on `obj` and the form fields.
                # The Python output is a lists of lists
                # that should be rendered to a downloadable HTML <table>
                results = [
                    [1, 2, 3],
                    [4, 5, 6],
                ]
                return render(request, "my_app/results.html", {"results": results})
        elif request.POST["router"] == "csv":
            response = HttpResponse(content_type="text/csv")
            response["Content-Disposition"] = f"attachment; filename=results-{time_ns():d}.csv"
            writer = csv.writer(response)
            # Ah!  Now I need to access `results` from above.  Do I inject
            # `results` into another <form> on my_app/results.html?
            # i.e.:
            # for row in results:
            #     writer.writerow(row)
            return response
    else:
        form = RunForm()
    return render(request, "my_app/run.html", {"form": form})
</code>```

In my_app/models.py:

```<code>class MyModel(models.Model):
    # Not important what this does for this example,
    # just a placeholder.
</code>```

答:
You have a few options that I can think of:

Return the results and send them back with the second request

You could have the first path in the view (the one that handles the router="run" branch) return back JSONResponse instead of the HTTPResponse object that that generates or render the form with results already plugged into the <form> element. Either way, the idea is to then store the results on the frontend, and return them back as a parameter to the other router="csv" branch

Store to a Django Session

You could also utilize a Django session, storing the stringified results list to request.session['results'] and then check against request.session['results'] in the router="csv" branch. Then just check against request.session['results'] in the CSV branch.

Title: Communication between two POST requests

Body:
Question

I have a Django form in which the user submits a text search string (full example setup below).

Question: how can (and should) two POST requests, currently handled by the same view tied to the same URL pattern, "talk" to each other via the first post request passing off data to the second?

The crux of the problem is in the block elif request.POST["router"] == "csv" below: I need to to access the results object from the first POST request, but basic Python scoping/control flow prevents me from doing that.

Currently, everything lives within the same URLconf path and is handled differently based on (1) whether the request is GET/POST, (2) what the POST request name/value attributes are from its <input> tag.

Setup

Imports:

import csv
from time import time_ns

from django import forms
from django import models
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import path

In my_app/urls.py:

urlpatterns = [
    path("run/<uuid:pk>", views.run),
]

In my_app/forms.py:

class RunForm(forms.Form):
    start = forms.DateTimeField()
    query = forms.CharField()

In my_app/templates/my_app/run.html:

<form method="post">
    {% csrf_token %}

Launch a search

    {{ form.as_table }}

    <input type="hidden" name="router" value="run">
    <input type="submit" value="Submit">
</form>

In my_app/templates/my_app/results.html:

{% for row in results %}

{% for val in row %}
{{ val }}
{% endfor %}

{% endfor %}

<form method="post">
  {% csrf_token %}
  <input type="hidden" name="router" value="csv">
  <input type="submit" value="Download to CSV">
</form>

In my_app/views.py:

def run(request, pk):
    if request.method == "POST":
        if request.POST["router"] == "run":
            form = RunForm(request.POST)
            if form.is_valid():
                obj = get_object_or_404(MyModel, pk=pk)
                # Get some dynamic results from database based
                # on `obj` and the form fields.
                # The Python output is a lists of lists
                # that should be rendered to a downloadable HTML

                results = [
                    [1, 2, 3],
                    [4, 5, 6],
                ]
                return render(request, "my_app/results.html", {"results": results})
        elif request.POST["router"] == "csv":
            response = HttpResponse(content_type="text/csv")
            response["Content-Disposition"] = f"attachment; filename=results-{time_ns():d}.csv"
            writer = csv.writer(response)
            # Ah!  Now I need to access `results` from above.  Do I inject
            # `results` into another <form> on my_app/results.html?
            # i.e.:
            # for row in results:
            #     writer.writerow(row)
            return response
    else:
        form = RunForm()
    return render(request, "my_app/run.html", {"form": form})

In my_app/models.py:

class MyModel(models.Model):
    # Not important what this does for this example,
    # just a placeholder.


问:
Debugging not hit breakpoints in .NET CORE MVC 6 application
I am working on .NET CORE 1.0 MVC 6 application and I stuck with the debugging point as it stopping hitting yesterday. with number of try I delete project and start again. First time it load symbols even due I have uncheck in Tool --> Debugging  --> symbols, however it hit breakpoints. Now it only hitting C# class  'Startup.cs' if I choose 'Enable Just My Code' but in controller. I have Debug option from dropdown, not really sure why. Need help here.

I change as

Select Debug->Options->Debugging->General

Tick Enable .NET Framework source stepping.

but still no success

Module

Trying to Hit in Controller home class for MVC Core in Index and about

```<code> public class HomeController : Controller
{
    public IActionResult Index()
    {
        var x = 2 + 3;

        return View();
    }

    public IActionResult About()
    {
        var x3 = 2 + 6;
        var xx = "dd";

        ViewData["Message"] = "Your application description page.";

        return View();
    }
</code>```

Debugging output

答:
I thought I was running into this same behavior except in my case it was caused by Temporal Coupling in the Startup.cs class of my .NET Core MVC application.

I had included my app.UseMiddleware() call below my app.UseMvc() call and because of this my middleware component would initialize but was never hit by requests coming into my application. Moving my call to app.UseMiddleware call above the app.UseMvc call fixed this and now my requests are being properly routed through my custom middleware.

app.UseMVC MUST BE THE LAST  "app.Use()" call in the Configure method of your Startup.cs class

Body:
I am working on .NET CORE 1.0 MVC 6 application and I stuck with the debugging point as it stopping hitting yesterday. with number of try I delete project and start again. First time it load symbols even due I have uncheck in Tool --> Debugging  --> symbols, however it hit breakpoints. Now it only hitting C# class  'Startup.cs' if I choose 'Enable Just My Code' but in controller. I have Debug option from dropdown, not really sure why. Need help here.

I change as

Select Debug->Options->Debugging->General

Tick Enable .NET Framework source stepping.

but still no success

Module

Trying to Hit in Controller home class for MVC Core in Index and about

 public class HomeController : Controller
{
    public IActionResult Index()
    {
        var x = 2 + 3;

        return View();
    }

    public IActionResult About()
    {
        var x3 = 2 + 6;
        var xx = "dd";

        ViewData["Message"] = "Your application description page.";

        return View();
    }

Debugging output