问:
Iterate over functions in Swift
I am feeling a bit stupid... I want to get rid of code duplication and so I need to iterate over some functions (a couple of Darwin geometric ones).
But when I try

```<code>for function in [Darwin.acos, Darwin.cos, Darwin.sin] { print(function(1.0)) }
</code>```

I get the error "Ambiguous use of 'acos'". I also tried Darwin.acos(Double) and got "Ambiguous reference to member 'acos'" and Darwin.acos { $0 } (and similar) without any luck.

Is it possible to do this? Thank you!

答:
In addition to what Sulthan said:

In a future version of Swift these functions are also available as static functions on the floating point types, compare SE-0246 Generic Math(s) Functions:

```<code>let functions = [Double.acos, Double.cos, Double.sin]
for function in functions { print(function(1.0)) }
</code>```

You can try this now with a current Swift developer snapshot from https://swift.org/download/#snapshots.

Title: Iterate over functions in Swift

Body:
I am feeling a bit stupid... I want to get rid of code duplication and so I need to iterate over some functions (a couple of Darwin geometric ones).
But when I try

for function in [Darwin.acos, Darwin.cos, Darwin.sin] { print(function(1.0)) }

I get the error "Ambiguous use of 'acos'". I also tried Darwin.acos(Double) and got "Ambiguous reference to member 'acos'" and Darwin.acos { $0 } (and similar) without any luck.

Is it possible to do this? Thank you!

Body:
In addition to what Sulthan said:

In a future version of Swift these functions are also available as static functions on the floating point types, compare SE-0246 Generic Math(s) Functions:

let functions = [Double.acos, Double.cos, Double.sin]
for function in functions { print(function(1.0)) }

You can try this now with a current Swift developer snapshot from https://swift.org/download/#snapshots.


来源: stackexchange

问:
How to send notifications by email automatically on a date?
I have a little problem, I don't know how to program a function in .NET MVC to send emails on a date.

For example: Every 25th of each Month send an email to my team partners to remember them update the stock. And the 27th of each Month send and email to his boss to check the stock.

I tried to do this, but i code a function that every time that someone's enter to the WebApp checks the date and if is the 25th sends the email.

The problems:

It sends like thousands of emails, because it is executed every time
when a person is inside the app.

If no ones enter to the app the function can be executed :(

答:
Take a look at the Windows Task Scheduler and use it to schedule your e-mail task. The Windows Task Scheduler does not care if your app is running or not.

This could also be a good candidate for an Azure function app.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-scheduled-function

ContentLicense: CC BY-SA 4.0


问:
How to set SOAP version using HttpWebRequest
I'm getting "(415) Unsupported Media Type" when trying to send the following WSDL:

```<code>Dim xml1 As String = String.Empty
xml1 = "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" "
xml1 += "xmlns:ser=""http://client_server.com/"">"
xml1 += "<soapenv:Header/>"
xml1 += "<soapenv:Body>"
xml1 += "XML_CONTENT"
xml1 += "</soapenv:Body>"
xml1 += "</soapenv:Envelope>"
'----------------------------
Dim a As New System.Text.ASCIIEncoding()
Dim buffer As Byte() = a.GetBytes(xml1)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://server.com?wsdl"), HttpWebRequest)
request.ServicePoint.Expect100Continue = False
request.KeepAlive = False
request.Headers.Add("SOAPAction", "")
request.Method = "POST"
request.ContentType = "application/soap+xml; charset=""UTF-8"""
request.Accept = "text/xml"
Dim stm As Stream = request.GetRequestStream()
stm.Write(buffer, 0, buffer.Length)
stm.Close()
Dim resp As WebResponse = request.GetResponse()
stm = resp.GetResponseStream()
</code>```

From what I understand, the reason for the exception is because the server is using a different SOAP version ("1.1") than the one on my request ("1.2", I guess).
How do I set the SOAP version?
Or is there another way to solve this "Unsupported Media Type" error?

答: It worked by removing the line where I fill the "ContentType" property ("request.ContentType = "application/soap+xml; charset=UTF-8"")</p>

Body:
I'm getting "(415) Unsupported Media Type" when trying to send the following WSDL:

Dim xml1 As String = String.Empty
xml1 = "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" "
xml1 += "xmlns:ser=""http://client_server.com/"">"
xml1 += "<soapenv:Header/>"
xml1 += "<soapenv:Body>"
xml1 += "XML_CONTENT"
xml1 += "</soapenv:Body>"
xml1 += "</soapenv:Envelope>"
'----------------------------
Dim a As New System.Text.ASCIIEncoding()
Dim buffer As Byte() = a.GetBytes(xml1)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://server.com?wsdl"), HttpWebRequest)
request.ServicePoint.Expect100Continue = False
request.KeepAlive = False
request.Headers.Add("SOAPAction", "")
request.Method = "POST"
request.ContentType = "application/soap+xml; charset=""UTF-8"""
request.Accept = "text/xml"
Dim stm As Stream = request.GetRequestStream()
stm.Write(buffer, 0, buffer.Length)
stm.Close()
Dim resp As WebResponse = request.GetResponse()
stm = resp.GetResponseStream()

From what I understand, the reason for the exception is because the server is using a different SOAP version ("1.1") than the one on my request ("1.2", I guess).
How do I set the SOAP version?
Or is there another way to solve this "Unsupported Media Type" error?


问:
How to fix this script to change the value from true to false
This is my first question on your forum, and I wish to find an answer, maybe it's a dumb question for everyone of you but I'm beginning with a JavaScript boot-camp and I'm curious how to do change the highlighted value with TamperMonkey

Another little question: Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

HTML

    <meta content="width=device-width,initial-scale=1.0,user-scalable=no"
    name="viewport">
    <meta id="fedora-keys" data-commit
    sha="f232f03c4db92d93cff3bee17185864b56d67336" data-env="production"
```

<p><strong>TamperMonkey Script</strong></p>

<pre class="lang-js prettyprint-override"><code>(function() {
  'use strict';
   var link = document.createElement('meta');
   link.setAttribute('name', 'data-env');
   link.content = "development";
   document.getElementsByTagName('head')[0].appendChild(link);
})();
</code>```

I'm trying to change "production" to "development" with TamperMonkey, but I blame my ignorance of the programming language.

Regards

答:
```<code>document.getElementById('fedora-keys')
        .setAttribute('data-env', 'development')
</code>```

Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

I don't think TamperMonkey supports that:

provides features like a clear overview over the running scripts, a built-in editor, ZIP-based import and export, automatic update checks and browser and cloud storage based synchronization.

Body:
This is my first question on your forum, and I wish to find an answer, maybe it's a dumb question for everyone of you but I'm beginning with a JavaScript boot-camp and I'm curious how to do change the highlighted value with TamperMonkey

Another little question: Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

HTML

    <meta content="width=device-width,initial-scale=1.0,user-scalable=no"
    name="viewport">
    <meta id="fedora-keys" data-commit
    sha="f232f03c4db92d93cff3bee17185864b56d67336" data-env="production"

TamperMonkey Script

(function() {
  'use strict';
   var link = document.createElement('meta');
   link.setAttribute('name', 'data-env');
   link.content = "development";
   document.getElementsByTagName('head')[0].appendChild(link);
})();

I'm trying to change "production" to "development" with TamperMonkey, but I blame my ignorance of the programming language.

Regards

Body:
document.getElementById('fedora-keys')
        .setAttribute('data-env', 'development')

Is there any macro recorder for TamperMonkey, like the one provided in Microsoft Office products to record a VB macro then edit it later?

I don't think TamperMonkey supports that:

provides features like a clear overview over the running scripts, a built-in editor, ZIP-based import and export, automatic update checks and browser and cloud storage based synchronization.


答:
Add an extra column in the selection part as below-</p>

```<code>SELECT
INVOICE_NUMBER,
INVOICE_SEQ_NUMBER,
FILE_NUMBER,
(
    SELECT COUNT(*)
    FROM TABLE1 A
    JOIN TABLE2 B
    ON A.INVOICE_NUMBER = B.INVOICE_NUMBER
    AND A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
    AND A.INVOICE_NUMBER = t.INVOICE_NUMBER
)MAX_INV_SEQ_NUMBER
FROM  ........
</code>```

Title: How to get max sequence number?

Body:
This is a continuation of my previous post : here

I have this query:

SELECT INVOICE_NUMBER, INVOICE_SEQ_NUMBER, FILE_NUMBER
FROM (SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER,
             DENSE_RANK() OVER (ORDER BY A.INVOICE_NUMBER) as seqnum
      FROM TABLE1 A JOIN
           TABLE2 B
           ON A.INVOICE_NUMBER = B.INVOICE_NUMBER AND
              A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
     ) t
WHERE seqnum <= 3;

And this result:

-----------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |
------------------------------------------------------
|1111111111-1    |          1         | P4324324525 |
-----------------------------------------------------
|1111111111-1    |          2         | P4565674574 |
-----------------------------------------------------
|1111111111-1    |          3         | V4324552557 |
-----------------------------------------------------
|1111111111-1    |          4         | V4324552525 |
-----------------------------------------------------
|2222222222-2    |          1         | S4563636574 |
-----------------------------------------------------
|3333333333-3    |          1         | Q4324325675 |
-----------------------------------------------------
|3333333333-3    |          2         | Q4565674574 |
-----------------------------------------------------

So the new requirement is how do I get the maximum invoice sequence number for the same invoice number? The result should be like this:

------------------------------------------------------------------------
| INVOICE_NUMBER | INVOICE_SEQ_NUMBER | FILE_NUMBER |MAX_INV_SEQ_NUMBER|
------------------------------------------------------------------------
|1111111111-1    |          1         | P4324324525 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          2         | P4565674574 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          3         | V4324552557 |        4         |
------------------------------------------------------------------------
|1111111111-1    |          4         | V4324552525 |        4         |
------------------------------------------------------------------------
|2222222222-2    |          1         | S4563636574 |        1         |
------------------------------------------------------------------------
|3333333333-3    |          1         | Q4324325675 |        2         |
------------------------------------------------------------------------
|3333333333-3    |          2         | Q4565674574 |        2         |
------------------------------------------------------------------------

Body:
Add an extra column in the selection part as below-

SELECT
INVOICE_NUMBER,
INVOICE_SEQ_NUMBER,
FILE_NUMBER,
(
    SELECT COUNT(*)
    FROM TABLE1 A
    JOIN TABLE2 B
    ON A.INVOICE_NUMBER = B.INVOICE_NUMBER
    AND A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
    AND A.INVOICE_NUMBER = t.INVOICE_NUMBER
)MAX_INV_SEQ_NUMBER
FROM  ........


问:
How to extract numbers from a string and dumping them as a comma separated values?
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

```<code>MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut
</code>```

shows me the following

```<code>output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

my expected results would be a string variable

```<code>123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96
</code>```

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

```<code>numbers=$(echo $MyOut | grep -o -E '[0-9]+')
</code>```

gives me

```<code>192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

```<code>#!/bin/bash

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

</code>```

Thanks
Ash

答:
Try this Shellcheck-clean pure Bash code:

```<code>#! /bin/bash -p

myout=$(./my_test_file.sh)
read -r -d '' -a parts <<<"$myout"
numlist=${parts[*]: -16}
result=${numlist// /,}

printf '%s\n' "$result"
</code>```

Using the my_test_file.sh given in the question it prints 123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96.

The code assumes that IFS has its default value.

The read puts the whitespace-separated parts of the value of myout into the array parts.  The -d '' causes read to continue through newlines (otherwise it would stop after reading the first line)  The -r option disables weird handling of backslashes in the input (which shouldn't matter here, but it's safest to always use -r with read, and Shellcheck will warn if it is missing).

numlist=${parts[*]: -16} sets the numlist string to the last 16 elements of the parts array, separated by the first character of $IFS (by default, a space character).

result=${numlist// /,} sets result to the value of numlist with all space characters replaced by commas.

Body:
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut

shows me the following

output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

my expected results would be a string variable

123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

numbers=$(echo $MyOut | grep -o -E '[0-9]+')

gives me

192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

#!/bin/bash

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

Thanks
Ash

Body:
Try this Shellcheck-clean pure Bash code:

#! /bin/bash -p

myout=$(./my_test_file.sh)
read -r -d '' -a parts <<<"$myout"
numlist=${parts[*]: -16}
result=${numlist// /,}

printf '%s\n' "$result"

Using the my_test_file.sh given in the question it prints 123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96.

The code assumes that IFS has its default value.

The read puts the whitespace-separated parts of the value of myout into the array parts.  The -d '' causes read to continue through newlines (otherwise it would stop after reading the first line)  The -r option disables weird handling of backslashes in the input (which shouldn't matter here, but it's safest to always use -r with read, and Shellcheck will warn if it is missing).

numlist=${parts[*]: -16} sets the numlist string to the last 16 elements of the parts array, separated by the first character of $IFS (by default, a space character).

result=${numlist// /,} sets result to the value of numlist with all space characters replaced by commas.


答:
```<code>SELECT INVOICE_NUMBER, INVOICE_SEQ_NUMBER, FILE_NUMBER, MAX(INVOICE_SEQ_NUMBER) OVER (PARTITION BY INVOICE_NUMBER)
FROM (SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER,
             DENSE_RANK() OVER (ORDER BY A.INVOICE_NUMBER) as seqnum
      FROM TABLE1 A JOIN
           TABLE2 B
           ON A.INVOICE_NUMBER = B.INVOICE_NUMBER AND
              A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
     ) t
WHERE seqnum <= 3;
</code>```

Essentially, you just need this in your select statement:

```<code>MAX(INVOICE_SEQ_NUMBER) OVER (PARTITION BY INVOICE_NUMBER)
</code>```

Title: How to get max sequence number?

Body:
SELECT INVOICE_NUMBER, INVOICE_SEQ_NUMBER, FILE_NUMBER, MAX(INVOICE_SEQ_NUMBER) OVER (PARTITION BY INVOICE_NUMBER)
FROM (SELECT A.INVOICE_NUMBER, A.INVOICE_SEQ_NUMBER, B.FILE_NUMBER,
             DENSE_RANK() OVER (ORDER BY A.INVOICE_NUMBER) as seqnum
      FROM TABLE1 A JOIN
           TABLE2 B
           ON A.INVOICE_NUMBER = B.INVOICE_NUMBER AND
              A.INVOICE_SEQ_NUMBER = B.INVOICE_SEQ_NUMBER
     ) t
WHERE seqnum <= 3;

Essentially, you just need this in your select statement:

MAX(INVOICE_SEQ_NUMBER) OVER (PARTITION BY INVOICE_NUMBER)


问:
Function input-output template type
I have seen the following valid template function type defined like this:

```<code>type func = <I, O>(data: I) => O;
</code>```

I understand this template is somehow for generic input and output types, but I cannot figure out how it can actually be used...

Any examples? I couldn't come up with a declaration that would match such a template. Or is it not a template at all? I am confused here as to the syntax.

答:
I'm not sure where you saw that type being used, but it is a concrete type representing a generic function:

```<code>type Funky = <I, O>(data: I) => O;
</code>```

If you had a function of type Funky, you could call it on absolutely any single argument of any type you want (as I is not constrained), and it could produce an output of any type you want (O is not constrained either).

As you noticed, it's difficult to imagine such a function.  In a more soundly-typed language like Haskell, it would be impossible to implement that without some evil magic.  TypeScript lets you assert just about anything, so you could write an implementation with no compiler warnings, but it would still be a very unsafe function:

```<code>const unsafeCoerce: Funky = (x: any) => x; // any is an escape-hatch from the type system
</code>```

Here, unsafeCoerce just returns its input, meaning that it supposedly allows the caller to coerce its input to any type you want, even if that is a lie:

```<code>const threeAsString: string = unsafeCoerce(3); // DANGER
// const unsafeCoerce: <number, string>(data: number) => string

threeAsString.charAt(0); // no error at compile time, TypeError at runtime
</code>```

So I don't see much use for that function either.

A similar looking type with a very different meaning is:

```<code>type Func<I, O> = (data: I) => O;
</code>```

This is a generic type representing a concrete function (or, a family of concrete functions).  You can't have a function of type Func, because it hasn't specified its generic parameters:

```<code>const nope: Func = (x: any) => x; // error!
//          ~~~~ <-- Generic type 'Func' requires 2 type argument(s).
</code>```

Instead, you would need to specify the parameters, which becomes a function from some specific input type to some specific output type, which are much easier to come by:

```<code>const stringLength: Func<string, number> = x => x.length; // okay
</code>```

If all you were doing was plugging in concrete values for I and O when declaring a function, there wouldn't be much point in doing this.  But there are reasons why you might want to use a generic type like Func, most obviously in higher-order typed data types.

For example, if you wanted to make a higher-order function apply(f, x) which takes a function f and a parameter x and returns f(x), you find yourself wanting to use a type like Func:

```<code>function apply<I, O>(f: Func<I, O>, x: I): O {
  return f(x); // okay
}
const out = apply((x: number) => x.toLocaleString(), 123); // string
</code>```

It's possible that you saw something like Func and remembered it like Funky.  Or maybe someone is actually using a Funky type like that, for some nefarious purpose that only they know (unless you look at what it's doing or link it in your question).

Anyway, hope that helps.  Good luck!

Link to code

Title: Function input-output template type

Body:
I have seen the following valid template function type defined like this:

type func = (data: I) => O;

I understand this template is somehow for generic input and output types, but I cannot figure out how it can actually be used...

Any examples? I couldn't come up with a declaration that would match such a template. Or is it not a template at all? I am confused here as to the syntax.

Body:
I'm not sure where you saw that type being used, but it is a concrete type representing a generic function:

type Funky = <I, O>(data: I) => O;

If you had a function of type Funky, you could call it on absolutely any single argument of any type you want (as I is not constrained), and it could produce an output of any type you want (O is not constrained either).

As you noticed, it's difficult to imagine such a function.  In a more soundly-typed language like Haskell, it would be impossible to implement that without some evil magic.  TypeScript lets you assert just about anything, so you could write an implementation with no compiler warnings, but it would still be a very unsafe function:

const unsafeCoerce: Funky = (x: any) => x; // any is an escape-hatch from the type system

Here, unsafeCoerce just returns its input, meaning that it supposedly allows the caller to coerce its input to any type you want, even if that is a lie:

const threeAsString: string = unsafeCoerce(3); // DANGER
// const unsafeCoerce: <number, string>(data: number) => string

threeAsString.charAt(0); // no error at compile time, TypeError at runtime

So I don't see much use for that function either.

A similar looking type with a very different meaning is:

type Func<I, O> = (data: I) => O;

This is a generic type representing a concrete function (or, a family of concrete functions).  You can't have a function of type Func, because it hasn't specified its generic parameters:

const nope: Func = (x: any) => x; // error!
//          ~~~~ <-- Generic type 'Func' requires 2 type argument(s).

Instead, you would need to specify the parameters, which becomes a function from some specific input type to some specific output type, which are much easier to come by:

const stringLength: Func<string, number> = x => x.length; // okay

If all you were doing was plugging in concrete values for I and O when declaring a function, there wouldn't be much point in doing this.  But there are reasons why you might want to use a generic type like Func<I, O>, most obviously in higher-order typed data types.

For example, if you wanted to make a higher-order function apply(f, x) which takes a function f and a parameter x and returns f(x), you find yourself wanting to use a type like Func:

function apply<I, O>(f: Func<I, O>, x: I): O {
  return f(x); // okay
}
const out = apply((x: number) => x.toLocaleString(), 123); // string

It's possible that you saw something like Func<I, O> and remembered it like Funky.  Or maybe someone is actually using a Funky type like that, for some nefarious purpose that only they know (unless you look at what it's doing or link it in your question).

Anyway, hope that helps.  Good luck!

<a href="https://typescript-play.js.org/#code/C4TwDgpgBAYgrgOwNYigXigHgJIBooDyAfABQAmAhsBQFxTYCU6RhA3AFDsDGA9ggM7AoifhQBmEAMI8IAJy4Q68ZKgwkAHnQoIQTNC3WsoAemNRtqAJb9zCKBH5cKkALQALKlzdQxsngFsoYDdoUEgofhBBCH9OXgEhYNkICABBfgBlYFlLBABzOkEc-PRhAXEpGXkIEgBmBg5TKHjBMtEJaTkFOkwEOH8AIzl8Ity80kpqOj7BuT0WUfzOJJT0rOK8gDovCllU4BIABgaTMwQee1k-WXMhXn8wSwAbUMt-CHxZRGA36AAVcAQACiVx4sk4TRcUOhMNhcPh0NOy0BsEQXBw+GIpXIVFo9HmbDifFa50gSjR2M0tl0zCghlOl2uAEJ2E0oOyORyAH48rlYKFQADiEAQcksXCCKIA5MouFKoMkAI5wSzJGwAJkl4V2eX6IoO-AYmyJCQi2TGABkRXlguSEOjFnl8DMhrIWBh1LT1JsXvlgkYmjwkBQQJwxGifnxzGAwE8QBjCKQxHb0XhE-gqYw6AQoABvdjs5LAOCyOxiDQNdgAXxNrR4cCEGGcsZAJA0036roJ3uAPAtPCcL3WYxIDHwAEZ1fUA2ZHewgA" rel="nofollow noreferrer">Link to code


问:
How to select (slice) in Pandas multiple rows and multiple non continuous columns?
I have a dataFrame and I want a range of specific rows and at the same time a range that is composed of a continuous range of columns plus an additional one.  Included is a piece of code that produces such a dataFrame

```<code>import pandas as pd
import numpy as np
np.random.seed(5)
dF = pd.DataFrame(np.random.randint(100, size=(100, 6)),
              columns=list('ABCDEF'),
              index=['R{}'.format(i) for i in range(100)])
dF.head()
</code>```

This works fine:

```<code>dF.loc[:, 'C':'E']
</code>```

But I need something like this, that produces an error:

```<code>dF.loc['R95':, ['A':'C', 'F']]
</code>```

The expected result has to include from row 'R95' onwards and columns 'A', 'C' and 'F'

Body:
I have a dataFrame and I want a range of specific rows and at the same time a range that is composed of a continuous range of columns plus an additional one.  Included is a piece of code that produces such a dataFrame

import pandas as pd
import numpy as np
np.random.seed(5)
dF = pd.DataFrame(np.random.randint(100, size=(100, 6)),
              columns=list('ABCDEF'),
              index=['R{}'.format(i) for i in range(100)])
dF.head()

This works fine:

dF.loc[:, 'C':'E']

But I need something like this, that produces an error:

dF.loc['R95':, ['A':'C', 'F']]

The expected result has to include from row 'R95' onwards and columns 'A', 'C' and 'F'

Body:
If you can just use the index you can do:

dF.iloc[95:, np.r_[0:3, -1]]

    A   B   C   F
R95 19  7   76  0
R96 57  31  86  64
R97 51  12  59  33
R98 24  7   68  69
R99 81  20  86  70

which is a lot cleaner.


问:
Breeze js calls metadata but doesn't make a second call to the server
am writing an angular application using breeze js and asp.net odata controller. Breeze JS makes the first call to the server for metadata successfully but doesn't make the second call to actually get the data. What i can see in Chrome is

```<code>XHR finished loading: GET "http://localhost:31549/Odata/ClientInvestments/$metadata".
</code>```

which returns

```<code><?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
  <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <Schema Namespace="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
      <EntityType Name="ClientInvestment">
        <Property Name="InvestmentNumber" Type="Edm.String" />
        <Property Name="Initials" Type="Edm.String" />
        <Property Name="InvestorFirstName" Type="Edm.String" />
        <Property Name="InvestorLastName" Type="Edm.String" />
        <Property Name="InvestorNumber" Type="Edm.String" />
        <Property Name="BrokerCode" Type="Edm.String" />
        <Property Name="UnclearedUnits" Type="Edm.Decimal" />
        <Property Name="UnclearedMarketValue" Type="Edm.Decimal" />
        <Property Name="BlockedUnits" Type="Edm.Decimal" />
        <Property Name="BlockedMarketValue" Type="Edm.Decimal" />
        <Property Name="TotalUnits" Type="Edm.Decimal" />
        <Property Name="NavDate" Type="Edm.DateTime" />
        <Property Name="NavCents" Type="Edm.Decimal" />
        <Property Name="CurrentValue" Type="Edm.Decimal" />
        <Property Name="FundName" Type="Edm.String" />
        <Property Name="FundCode" Type="Edm.String" />
        <Property Name="ProductName" Type="Edm.String" />
        <Property Name="ProductCode" Type="Edm.String" />
        <Property Name="ProductType" Type="Edm.String" />
        <Property Name="EntityCode" Type="Edm.String" />
        <Property Name="InvestmentType" Type="Edm.String" />
      </EntityType>
      <EntityType Name="ClientTransaction">
        <Property Name="TransactionId" Type="Edm.Int32" />
        <Property Name="BrokerCode" Type="Edm.String" />
        <Property Name="InvestorNumber" Type="Edm.String" />
        <Property Name="InvestmentNumber" Type="Edm.String" />
        <Property Name="TransactionDate" Type="Edm.DateTime" />
        <Property Name="Description" Type="Edm.String" />
        <Property Name="GrossAmount" Type="Edm.Decimal" />
        <Property Name="AgentFee" Type="Edm.Decimal" />
        <Property Name="VatOnFees" Type="Edm.Decimal" />
        <Property Name="TotalAgentFees" Type="Edm.Decimal" />
        <Property Name="NetAmount" Type="Edm.Decimal" />
        <Property Name="NavPrice" Type="Edm.Decimal" />
        <Property Name="Units" Type="Edm.Decimal" />
        <Property Name="Wauc" Type="Edm.Decimal" />
      </EntityType>
      <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
        <EntitySet Name="ClientInvestments" EntityType="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment" />
        <EntitySet Name="ClientTransactions" EntityType="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientTransaction" />
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>
</code>```

then nothing

my wep api is configured like so

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapODataServiceRoute("Odata", "Odata/ClientInvestments", CreateClientInvestmentEdmModel());
        config.Routes.MapODataServiceRoute("OdataCommission", "Odata/Commission", CreateCommissionEdmModel());
        config.Routes.MapODataServiceRoute("OdataAssetsUnderManagement", "Odata/AssetsUnderManagement", CreateAssetsUnderManagementEdmModel());

        config.Routes.MapHttpRoute(
            name: "Reports",
            routeTemplate: "api/reports/{action}",
            defaults: new { controller = "Reports" }

        );

        config.Routes.MapHttpRoute(
            name: "SecondaryMarket",
            routeTemplate: "api/secondarymarket/{action}",
            defaults: new { controller = "SecondaryMarket" }

        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.Add(new CsvMediaTypeFormatter());
        config.Formatters.Add(new ExcelMediaTypeFormatter());

        config.MessageHandlers.Add(new LogRequestHandler());

        config.Filters.Add(new HandleErrorFilter());

        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;
    }

    public static IEdmModel CreateClientInvestmentEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment>(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.ClientInvestmentsServiceConstants.ClientInvestmentsQuery);
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientTransaction>(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.ClientInvestmentsServiceConstants.ClientTransactionsQuery);

        return builder.GetEdmModel();
    }

    public static IEdmModel CreateCommissionEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionDetail).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionDetail>(Cadiz.Services.CadizOnline.Contracts.CommissionService.CommissionServiceConstants.CommissionDetailsQuery);
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionSummary>(Cadiz.Services.CadizOnline.Contracts.CommissionService.CommissionServiceConstants.CommissionSummaryQuery);

        return builder.GetEdmModel();
    }

    public static IEdmModel CreateAssetsUnderManagementEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.DataContracts.ClientAsset).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.DataContracts.ClientAsset>(Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.AssetsUnderManagementServiceConstants.AssetsUnderManagementQuery);

        return builder.GetEdmModel();
    }
}
</code>```

my javascript is configured like so

```<code>        breeze.config.initializeAdapterInstances({
            dataService: "OData"
        });

       var dataService = new breeze.DataService({
                    serviceName: '/Odata/ClientInvestments'
       });
       var manager = new breeze.EntityManager({ dataService: dataService });
       var query = new breeze.EntityQuery('ClientInvestments');
       manager.executeQuery(query).then(function(data){
           var results = data;
       });
</code>```

my odata controller looks like

```<code>namespace Cadiz.Web.CadizOnline.Controllers.Odata.ClientInvestments
{
    [Authorize]
    public class ClientInvestmentsController : ODataController
    {
        #region Private Members

        private readonly IClientInvestmentsService dataContext;

        #endregion

        #region Constructors

        public ClientInvestmentsController(IClientInvestmentsService dataContext)
        {
            this.dataContext = dataContext;
        }

        #endregion

        #region Methods

        [EnableQuery(MaxOrderByNodeCount = 1)]
        [ClaimsAuthorise(CadizSecurityConstants.Operations.Read, CadizSecurityConstants.Resources.Client)]
        public IHttpActionResult Get()
        {
            var query = dataContext.ClientInvestments;
            return Ok(query);
        }

        #endregion

        #region Virtual Methods

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                dataContext.Dispose();
            }

            base.Dispose(disposing);
        }

        #endregion
    }
}
</code>```

答: check your cors configuration sometimes breeze will fail silently if cors is not configured correctly</p>

ContentLicense: CC BY-SA 3.0

Body:
am writing an angular application using breeze js and asp.net odata controller. Breeze JS makes the first call to the server for metadata successfully but doesn't make the second call to actually get the data. What i can see in Chrome is

XHR finished loading: GET "http://localhost:31549/Odata/ClientInvestments/$metadata".

which returns

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
  <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <Schema Namespace="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
      <EntityType Name="ClientInvestment">
        <Property Name="InvestmentNumber" Type="Edm.String" />
        <Property Name="Initials" Type="Edm.String" />
        <Property Name="InvestorFirstName" Type="Edm.String" />
        <Property Name="InvestorLastName" Type="Edm.String" />
        <Property Name="InvestorNumber" Type="Edm.String" />
        <Property Name="BrokerCode" Type="Edm.String" />
        <Property Name="UnclearedUnits" Type="Edm.Decimal" />
        <Property Name="UnclearedMarketValue" Type="Edm.Decimal" />
        <Property Name="BlockedUnits" Type="Edm.Decimal" />
        <Property Name="BlockedMarketValue" Type="Edm.Decimal" />
        <Property Name="TotalUnits" Type="Edm.Decimal" />
        <Property Name="NavDate" Type="Edm.DateTime" />
        <Property Name="NavCents" Type="Edm.Decimal" />
        <Property Name="CurrentValue" Type="Edm.Decimal" />
        <Property Name="FundName" Type="Edm.String" />
        <Property Name="FundCode" Type="Edm.String" />
        <Property Name="ProductName" Type="Edm.String" />
        <Property Name="ProductCode" Type="Edm.String" />
        <Property Name="ProductType" Type="Edm.String" />
        <Property Name="EntityCode" Type="Edm.String" />
        <Property Name="InvestmentType" Type="Edm.String" />
      </EntityType>
      <EntityType Name="ClientTransaction">
        <Property Name="TransactionId" Type="Edm.Int32" />
        <Property Name="BrokerCode" Type="Edm.String" />
        <Property Name="InvestorNumber" Type="Edm.String" />
        <Property Name="InvestmentNumber" Type="Edm.String" />
        <Property Name="TransactionDate" Type="Edm.DateTime" />
        <Property Name="Description" Type="Edm.String" />
        <Property Name="GrossAmount" Type="Edm.Decimal" />
        <Property Name="AgentFee" Type="Edm.Decimal" />
        <Property Name="VatOnFees" Type="Edm.Decimal" />
        <Property Name="TotalAgentFees" Type="Edm.Decimal" />
        <Property Name="NetAmount" Type="Edm.Decimal" />
        <Property Name="NavPrice" Type="Edm.Decimal" />
        <Property Name="Units" Type="Edm.Decimal" />
        <Property Name="Wauc" Type="Edm.Decimal" />
      </EntityType>
      <EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
        <EntitySet Name="ClientInvestments" EntityType="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment" />
        <EntitySet Name="ClientTransactions" EntityType="Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientTransaction" />
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>

then nothing

my wep api is configured like so

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapODataServiceRoute("Odata", "Odata/ClientInvestments", CreateClientInvestmentEdmModel());
        config.Routes.MapODataServiceRoute("OdataCommission", "Odata/Commission", CreateCommissionEdmModel());
        config.Routes.MapODataServiceRoute("OdataAssetsUnderManagement", "Odata/AssetsUnderManagement", CreateAssetsUnderManagementEdmModel());

        config.Routes.MapHttpRoute(
            name: "Reports",
            routeTemplate: "api/reports/{action}",
            defaults: new { controller = "Reports" }

        );

        config.Routes.MapHttpRoute(
            name: "SecondaryMarket",
            routeTemplate: "api/secondarymarket/{action}",
            defaults: new { controller = "SecondaryMarket" }

        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.Add(new CsvMediaTypeFormatter());
        config.Formatters.Add(new ExcelMediaTypeFormatter());

        config.MessageHandlers.Add(new LogRequestHandler());

        config.Filters.Add(new HandleErrorFilter());

        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;
    }

    public static IEdmModel CreateClientInvestmentEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientInvestment>(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.ClientInvestmentsServiceConstants.ClientInvestmentsQuery);
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.DataContracts.ClientTransaction>(Cadiz.Services.CadizOnline.Contracts.ClientInvestmentsService.ClientInvestmentsServiceConstants.ClientTransactionsQuery);

        return builder.GetEdmModel();
    }

    public static IEdmModel CreateCommissionEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionDetail).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionDetail>(Cadiz.Services.CadizOnline.Contracts.CommissionService.CommissionServiceConstants.CommissionDetailsQuery);
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.CommissionService.DataContracts.CommissionSummary>(Cadiz.Services.CadizOnline.Contracts.CommissionService.CommissionServiceConstants.CommissionSummaryQuery);

        return builder.GetEdmModel();
    }

    public static IEdmModel CreateAssetsUnderManagementEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.Namespace = typeof(Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.DataContracts.ClientAsset).Namespace;
        builder.EntitySet<Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.DataContracts.ClientAsset>(Cadiz.Services.CadizOnline.Contracts.AssetsUnderManagementService.AssetsUnderManagementServiceConstants.AssetsUnderManagementQuery);

        return builder.GetEdmModel();
    }
}

my javascript is configured like so

        breeze.config.initializeAdapterInstances({
            dataService: "OData"
        });

       var dataService = new breeze.DataService({
                    serviceName: '/Odata/ClientInvestments'
       });
       var manager = new breeze.EntityManager({ dataService: dataService });
       var query = new breeze.EntityQuery('ClientInvestments');
       manager.executeQuery(query).then(function(data){
           var results = data;
       });

my odata controller looks like

namespace Cadiz.Web.CadizOnline.Controllers.Odata.ClientInvestments
{
    [Authorize]
    public class ClientInvestmentsController : ODataController
    {
        #region Private Members

        private readonly IClientInvestmentsService dataContext;

        #endregion

        #region Constructors

        public ClientInvestmentsController(IClientInvestmentsService dataContext)
        {
            this.dataContext = dataContext;
        }

        #endregion

        #region Methods

        [EnableQuery(MaxOrderByNodeCount = 1)]
        [ClaimsAuthorise(CadizSecurityConstants.Operations.Read, CadizSecurityConstants.Resources.Client)]
        public IHttpActionResult Get()
        {
            var query = dataContext.ClientInvestments;
            return Ok(query);
        }

        #endregion

        #region Virtual Methods

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                dataContext.Dispose();
            }

            base.Dispose(disposing);
        }

        #endregion
    }
}


问:
How to limit memory usage in docker-compose?
Here is part of my docker-compose.yaml file

```<code>version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M
</code>```

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

```<code>CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%
</code>```

答:
deploy key only works in swarm mode and with docker-compose file version 3 and above.

In your case, use docker-compose file version 2 and define resource limits:

```<code>version: "2.2"

services:
  app:
    image: foo
    cpus: "0.5"
    mem_limit: 23m
</code>```

See official docs here

Body:
Here is part of my docker-compose.yaml file

version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%

Body:
deploy key only works in swarm mode and with docker-compose file version 3 and above.

In your case, use docker-compose file version 2 and define resource limits:

version: "2.2"

services:
  app:
    image: foo
    cpus: "0.5"
    mem_limit: 23m

See official docs here


问:
.net remoting over USB
Is it possible to control an app that exposes a .NET Remoting interface from a client connected via USB? How would I do that...a custom transport channel? Both client and server run on Windows platforms.

Thanks,
Jim

答:
after this here, it's just plain ol' TCP/IP :)

Edit 13 April 2011 20:53 EEST

I guess you could set a static IP on the server and a DHCP service to give automatic IP addresses to clients, however I saw your update that it's a standard host/device cable, which changes everything.

I am however still unable to understand how this will work, as Windows PCs can only be hosts, not devices (I may be wrong, but I'm certain Linux can support this - http://www.linux-usb.org/gadget/). You may be better served with i.e. http://usblan.belcarra.com/p/usblan-deployment-guide.html and hand out installation CDs with your device, if you can configure Windows as a client (device).

Title: .net remoting over USB


问:
Why does std::unordered_set not take CComBSTR type as a key?
When I try to use std::unordered_set<CComBSTR> (or std::unordered_set<CAdapt<CComBSTR>>), I get the error

```<code>c:\apps\vs2017pro\vc\tools\msvc\14.16.27023\include\unordered_set(105) : error C2280 : 'std::hash<_Kty>::hash(const std::hash<_Kty> &)' : attempting to reference a deleted function
with
[
    _Kty = ATL::CComBSTR
]
</code>```

But std::set<CComBSTR> (or std::set<CAdapt<CComBSTR>>) is fine. I am using Visual Studio 2017.

<s>What can I do to still achieve the O(1) time complexity for search?</s> (Of course, we can use a custom hash function to achieve O(1) time complexity for search.)

The minimal reproducible example is given as below.

```<code>#include "atlbase.h"
#include <unordered_set>
#include <set>

int main()
{
    //std::unordered_set<CComBSTR> s;    // compile error
    //std::unordered_set<CAdapt<CComBSTR>> s;    // compile error

    //std::set<CComBSTR> s;    // ok
    //std::set<CAdapt<CComBSTR>> s;    // ok

    return 0;
}
</code>```

EDIT (06/02/2019):

I understood the error that there was no hash function for CComBSTR and we can create a custom one. What I meant to ask was what is the design reason for std::set to have a hash function but not std::unordered_set?

答:
The problem here is that the compiler doesn't know how to hash your key.  To fix this, you need to provide a custom hash function:</p>

```<code>#include "atlbase.h"
#include <unordered_set>
#include <set>
#include <string>

struct HashBSTR
{
    size_t operator () (const CComBSTR &bstr)
    {
        return std::hash <std::wstring> () (bstr.m_str);
    }
};

int main()
{
    std::unordered_set <CComBSTR, HashBSTR> s;
    return 0;
}
</code>```

Body:
When I try to use std::unordered_set<CComBSTR> (or std::unordered_set<CAdapt<CComBSTR>>), I get the error

c:\apps\vs2017pro\vc\tools\msvc\14.16.27023\include\unordered_set(105) : error C2280 : 'std::hash<_Kty>::hash(const std::hash<_Kty> &)' : attempting to reference a deleted function
with
[
    _Kty = ATL::CComBSTR
]

But std::set<CComBSTR> (or std::set<CAdapt<CComBSTR>>) is fine. I am using Visual Studio 2017.

<s>What can I do to still achieve the O(1) time complexity for search?</s> (Of course, we can use a custom hash function to achieve O(1) time complexity for search.)

The minimal reproducible example is given as below.

#include "atlbase.h"
#include <unordered_set>
#include <set>

int main()
{
    //std::unordered_set<CComBSTR> s;    // compile error
    //std::unordered_set<CAdapt<CComBSTR>> s;    // compile error

    //std::set<CComBSTR> s;    // ok
    //std::set<CAdapt<CComBSTR>> s;    // ok

    return 0;
}

EDIT (06/02/2019):

I understood the error that there was no hash function for CComBSTR and we can create a custom one. What I meant to ask was what is the design reason for std::set to have a hash function but not std::unordered_set?

Body:
The problem here is that the compiler doesn't know how to hash your key.  To fix this, you need to provide a custom hash function:

#include "atlbase.h"
#include <unordered_set>
#include <set>
#include <string>

struct HashBSTR
{
    size_t operator () (const CComBSTR &bstr)
    {
        return std::hash <std::wstring> () (bstr.m_str);
    }
};

int main()
{
    std::unordered_set <CComBSTR, HashBSTR> s;
    return 0;
}


问:
npm ERR! Unexpected end of JSON input while parsing near '...registry.npmjs.org/@i'
I am new to ionic and i am still trying to install it. Everytime i write an ionic command like npm install -g ionic cordova i receive this error

```<code>    npm ERR! Unexpected end of JSON input while parsing near '...de":"0.6.2","express"'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DwayneT\AppData\Roaming\npm-cache\_logs\2019-05-31T01_51_23_542Z-debug.log
</code>```

'

this is my log file

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli
'C:\\Users\\DwayneT\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-
cli.js',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   'ionic',
1 verbose cli   'cordova' ]
2 info using npm@6.9.0
3 info using node@v8.11.1
4 verbose npm-session bf0a16c3729a6897
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 304 http://registry.npmjs.org/cordova 1407ms (from cache)
8 silly fetchPackageMetaData error for cordova@latest Unexpected end of JSON
input while parsing near '...de":"0.6.2","express"'
9 http fetch GET 304 http://registry.npmjs.org/ionic 1418ms (from cache)
10 silly pacote tag manifest for ionic@latest fetched in 1452ms
11 timing stage:rollbackFailedOptional Completed in 1ms
12 timing stage:runTopLevelLifecycles Completed in 1466ms
13 verbose stack SyntaxError: Unexpected end of JSON input while parsing
near '...de":"0.6.2","express"'
13 verbose stack     at JSON.parse (<anonymous>)
13 verbose stack     at parseJson
(C:\Users\DwayneT\AppData\Roaming\npm\node_modules\npm\node_modules\json-
parse-better-errors\index.js:7:17)
13 verbose stack     at consumeBody.call.then.buffer
(C:\Users\DwayneT\AppData\Roaming\npm\node_modules\npm\node_modules\node-
fetch-npm\src\body.js:96:50)
13 verbose stack     at <anonymous>
13 verbose stack     at process._tickCallback
(internal/process/next_tick.js:188:7)
14 verbose cwd C:\Users\DwayneT
15 verbose Windows_NT 10.0.18362
16 verbose argv "C:\\Program Files\\nodejs\\node.exe"
"C:\\Users\\DwayneT\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-
cli.js" "install" "-g" "ionic" "cordova"
17 verbose node v8.11.1
18 verbose npm  v6.9.0
19 error Unexpected end of JSON input while parsing near
'...de":"0.6.2","express"'
20 verbose exit [ 1, true ]
</code>```

I have tried many solutions including

```<code>npm cache clean --force
</code>```

but nothing seems to work and i am now now. Kindly assist please. I am using node v 8

答:
Try cleaning the npm cache use the below command. This will clean your existing npm entries and start from the beginning. I think the one file may be corrupt during the installation that's why you are facing this issue.

```<code>npm cache clean
</code>```

Then try

```<code>npm install ionic -g
</code>```

Body:
I am new to ionic and i am still trying to install it. Everytime i write an ionic command like npm install -g ionic cordova i receive this error

    npm ERR! Unexpected end of JSON input while parsing near '...de":"0.6.2","express"'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DwayneT\AppData\Roaming\npm-cache\_logs\2019-05-31T01_51_23_542Z-debug.log

'

this is my log file

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli
'C:\\Users\\DwayneT\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-
cli.js',
1 verbose cli   'install',
1 verbose cli   '-g',
1 verbose cli   'ionic',
1 verbose cli   'cordova' ]
2 info using npm@6.9.0
3 info using node@v8.11.1
4 verbose npm-session bf0a16c3729a6897
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 304 http://registry.npmjs.org/cordova 1407ms (from cache)
8 silly fetchPackageMetaData error for cordova@latest Unexpected end of JSON
input while parsing near '...de":"0.6.2","express"'
9 http fetch GET 304 http://registry.npmjs.org/ionic 1418ms (from cache)
10 silly pacote tag manifest for ionic@latest fetched in 1452ms
11 timing stage:rollbackFailedOptional Completed in 1ms
12 timing stage:runTopLevelLifecycles Completed in 1466ms
13 verbose stack SyntaxError: Unexpected end of JSON input while parsing
near '...de":"0.6.2","express"'
13 verbose stack     at JSON.parse (<anonymous>)
13 verbose stack     at parseJson
(C:\Users\DwayneT\AppData\Roaming\npm\node_modules\npm\node_modules\json-
parse-better-errors\index.js:7:17)
13 verbose stack     at consumeBody.call.then.buffer
(C:\Users\DwayneT\AppData\Roaming\npm\node_modules\npm\node_modules\node-
fetch-npm\src\body.js:96:50)
13 verbose stack     at <anonymous>
13 verbose stack     at process._tickCallback
(internal/process/next_tick.js:188:7)
14 verbose cwd C:\Users\DwayneT
15 verbose Windows_NT 10.0.18362
16 verbose argv "C:\\Program Files\\nodejs\\node.exe"
"C:\\Users\\DwayneT\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-
cli.js" "install" "-g" "ionic" "cordova"
17 verbose node v8.11.1
18 verbose npm  v6.9.0
19 error Unexpected end of JSON input while parsing near
'...de":"0.6.2","express"'
20 verbose exit [ 1, true ]

I have tried many solutions including

npm cache clean --force

but nothing seems to work and i am now now. Kindly assist please. I am using node v 8

Body:
Try cleaning the npm cache use the below command. This will clean your existing npm entries and start from the beginning. I think the one file may be corrupt during the installation that's why you are facing this issue.

npm cache clean

Then try

npm install ionic -g


问:
How to scale the fonts in a Button
I'm trying to complete my first app in Swift and I met with the problem.
I have some buttons with the tittles and background image. Running the simulation on different devices makes them scale, so the tittles goes out of buttons frame.
There is no "Dynamic Type Automatically Adjust Font" checkbox in my Xcode attributes inspector so I made the custom UIButton class and made the inspectable var

```<code>@IBInspectable var adjustFontSize : Bool {
    set { titleLabel?.adjustsFontForContentSizeCategory = newValue }
    get { return titleLabel!.adjustsFontForContentSizeCategory  }
</code>```

but this does't helps and I got "Automatically adjusts font requires using a dynamic type text style" warning

So how can I make my button title scale to fit the Button frame when the button changes size and proportions on different devices?

答:
This worked for me.</p>

```<code> btn.titleLabel?.minimumScaleFactor = 0.1
 btn.titleLabel?.numberOfLines = 1
 btn.titleLabel?.adjustsFontSizeToFitWidth = true
</code>```

Title: How to scale the fonts in a Button

Body:
I'm trying to complete my first app in Swift and I met with the problem.
I have some buttons with the tittles and background image. Running the simulation on different devices makes them scale, so the tittles goes out of buttons frame.
There is no "Dynamic Type Automatically Adjust Font" checkbox in my Xcode attributes inspector so I made the custom UIButton class and made the inspectable var

@IBInspectable var adjustFontSize : Bool {
    set { titleLabel?.adjustsFontForContentSizeCategory = newValue }
    get { return titleLabel!.adjustsFontForContentSizeCategory  }

but this does't helps and I got "Automatically adjusts font requires using a dynamic type text style" warning

So how can I make my button title scale to fit the Button frame when the button changes size and proportions on different devices?

Body:
This worked for me.

 btn.titleLabel?.minimumScaleFactor = 0.1
 btn.titleLabel?.numberOfLines = 1
 btn.titleLabel?.adjustsFontSizeToFitWidth = true


问:
Loop through 2 list of dictionaries
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

```<code>list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']
</code>```

The output I'm getting is

```<code>A
B
B
</code>```

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

答:
You iterate over and print in every cases where the match is not found.

You can instead use a lookup in a set which is more effective:

```<code>for x in list1:
    if x['name'] not in {y['name'] for y in list2}:
        print(x['name'])
</code>```

Using all(), you can do:

```<code>for x in list1:
    if all(x['name'] != y['name'] for y in list2):
        print(x['name'])
</code>```

Title: Loop through 2 list of dictionaries

Body:
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']

The output I'm getting is

A
B
B

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

Body:
You iterate over and print in every cases where the match is not found.

You can instead use a lookup in a set which is more effective:

for x in list1:
    if x['name'] not in {y['name'] for y in list2}:
        print(x['name'])

Using all(), you can do:

for x in list1:
    if all(x['name'] != y['name'] for y in list2):
        print(x['name'])


问:
HTML5 input pattern attribute - regex fails
I'm a bit stumped trying to get the following regex to work

```<code><!DOCTYPE html>
<html>
<body>

<form action="/....php">
  Amount: <input type="text" name="amount" pattern="^\$(\d{1,3}(\,\d{3})*|(\d+))(^\.\d{2})?$" title="Please enter as $XXX,XXX no decimal">
  <input type="submit">
</form>

</body>
</html>
</code>```

I tried dropping the leading carrot and trailing dollar too, as I know these are implied, but it still won't validate the the number entered is of the form $XXX,XXX with no decimal. Other regex parsers are working fine and validate the regex should work: https://regex101.com/r/BZKMK4/1

Are there published limitations to the input regex you can use in the pattern attribute?

答:
Thanks. That got me where I need to be. Here's my final regex:

```<code>   ^\$[1-9]\d{0,2}((,\d{3})*|\d*)$
</code>```

Support with or without comma, ie $10,000 is valid, and so is $10000

Body:
I'm a bit stumped trying to get the following regex to work

<!DOCTYPE html>

<form action="/....php">
  Amount: <input type="text" name="amount" pattern="^\$(\d{1,3}(\,\d{3})*|(\d+))(^\.\d{2})?$" title="Please enter as $XXX,XXX no decimal">
  <input type="submit">
</form>

I tried dropping the leading carrot and trailing dollar too, as I know these are implied, but it still won't validate the the number entered is of the form $XXX,XXX with no decimal. Other regex parsers are working fine and validate the regex should work: https://regex101.com/r/BZKMK4/1

Are there published limitations to the input regex you can use in the pattern attribute?

Body:
Thanks. That got me where I need to be. Here's my final regex:

   ^\$[1-9]\d{0,2}((,\d{3})*|\d*)$

Support with or without comma, ie $10,000 is valid, and so is $10000


问:
Line breaks in directory using knitr/R Markdown
I'm currently working with R Markdown and trying to get the code, results and documentation to one pdf-file with the knit function in the end.

Within in the document, I want to set my directory with the setwd command.

```<code>setwd("C:/Users/Testuser/Documents/Testfolder/Testsubfolder/Testsubfolder2/Testsubfolder3/Testsubfolder4/Testsubfolder5")
</code>```

However, the file path exceeds the width of the pdf and there is no line break so part of it is cut off at the right side. When I try to insert a page break manually, for example by pressing Enter after "Testdubfolder2", I get the following Error message:

"Fehler in setwd("C:/Users/Testuser/Documents/Testfolder/Testsubfolder/Testsubfolder2/\n
  Testsubfolder3/Testsubfolder4/Testsubfolder5") : kann Arbeitsverzeichnis nicht wechseln."

, which in English simply means, that the directory can't be changed. Is there any way to display the file path over two lines using the knit function? I'd be grateful for any solution or hint.

答:
You can use file.path to construct paths from multiple subpaths, for example:

```<code>setwd(file.path(
  "C:/Users/Testuser/Documents",
  "Testfolder/Testsubfolder/Testsubfolder2",
  "Testsubfolder3/Testsubfolder4/Testsubfolder5"
))
</code>```

Body:
I'm currently working with R Markdown and trying to get the code, results and documentation to one pdf-file with the knit function in the end.

Within in the document, I want to set my directory with the setwd command.

setwd("C:/Users/Testuser/Documents/Testfolder/Testsubfolder/Testsubfolder2/Testsubfolder3/Testsubfolder4/Testsubfolder5")

However, the file path exceeds the width of the pdf and there is no line break so part of it is cut off at the right side. When I try to insert a page break manually, for example by pressing Enter after "Testdubfolder2", I get the following Error message:

"Fehler in setwd("C:/Users/Testuser/Documents/Testfolder/Testsubfolder/Testsubfolder2/\n
  Testsubfolder3/Testsubfolder4/Testsubfolder5") : kann Arbeitsverzeichnis nicht wechseln."

, which in English simply means, that the directory can't be changed. Is there any way to display the file path over two lines using the knit function? I'd be grateful for any solution or hint.

Body:
You can use file.path to construct paths from multiple subpaths, for example:

setwd(file.path(
  "C:/Users/Testuser/Documents",
  "Testfolder/Testsubfolder/Testsubfolder2",
  "Testsubfolder3/Testsubfolder4/Testsubfolder5"
))


答:
This is a bit convoluted,
but for this problem I think you could do the following:

```<code>zs <- unique(DT$z)

sum_div <- function(dt) {
  ans <- dt[, .(div = sum(d1) / sum(d2)), by = .(z)]
  split(ans$div, factor(ans$z, levels = zs), drop = FALSE)
}

DT[, sum_div(.SD), by = .(x, y), .SDcols = c("z", "d1", "d2")]
</code>```

What happens is that .SD ends up having the 3 columns specified in .SDcols,
but with different subsets for the possible combinations of x and y values.
Then, sum_div performs your desired operation only on that subset,
and splits the result to return a list so that each possible value of z gets its own column in the final data.table.

It's important to do factor(ans$z, levels = zs) in order to get the same number of list elements every time
(data.table expects that);
by specifying how many levels we expect,
split will return an empty vector if there are no values for a level,
but it will definitely return something for each.

Note that you could achieve the same with:

```<code>dcast(DT[, .(div = sum(d1) / sum(d2)), by = .(x, y, z)], x + y ~ z, value.var = "div")
</code>```

I'm not sure if you gain considerable performance by doing everything in one step.

EDIT: you probably don't:

```<code>library(data.table)
library(microbenchmark)

n <- 2e5
DT = data.table(x = sample(5L, n, TRUE),
                y = sample(3L, n, TRUE),
                z = sample(letters[1:2], n, TRUE),
                d1 = runif(n),
                d2 = 1L)

zs <- sort(unique(DT$z))

sum_div <- function(dt) {
  ans <- dt[, .(div = sum(d1) / sum(d2)), by = .(z)]
  split(ans$div, factor(ans$z, levels = zs), drop = FALSE)
}

microbenchmark(
  one = DT[, sum_div(.SD), keyby = .(x, y), .SDcols = c("z", "d1", "d2")],
  two = dcast(DT[, .(div = sum(d1) / sum(d2)), by = .(x, y, z)], x + y ~ z, value.var = "div"),
  times = 10L
)
Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval
  one 24.37323 25.74273 26.72413 25.99279 26.62943 34.40309    10
  two 11.31050 11.91650 12.66345 12.51094 13.01364 15.35549    10
</code>```

Title: Is it possible to operate on the aggregated dcast values?

Body:
dcast.data.table has the feature to aggregate on multiple value.var. Is it possible to somehow reference the aggregated values being created and then perform an operation within the fun ?

This creates the 4 variables

DT = data.table(x=sample(5,20,TRUE), y=sample(2,20,TRUE),
                z=sample(letters[1:2], 20,TRUE), d1 = runif(20), d2=1L)

> head(DT)
   x y z        d1 d2
1: 3 2 a 0.6166590  1
2: 3 1 a 0.1891611  1
3: 5 2 a 0.3061658  1
4: 3 1 a 0.7233832  1
5: 2 1 b 0.6799675  1
6: 2 1 b 0.5144392  1

dcast(DT, x + y ~ z, fun=sum, value.var=c("d1", "d2"))

   x y      d1_a      d1_b d2_a d2_b
1: 1 1 1.0400277 0.3835004    2    1
2: 2 1 0.7032111 1.3713884    1    2
3: 3 1 0.9759893 2.0853103    1    3
4: 3 2 0.5210792 0.0000000    1    0
5: 4 1 1.0971931 0.4417819    2    1
6: 4 2 0.5009533 0.0000000    1    0
7: 5 1 0.9372943 0.0000000    4    0
8: 5 2 0.7671728 0.0000000    1    0

And the operation(s) on the aggregated values can be performed in the second step

dcast(DT, x + y ~ z, fun=sum, value.var=c("d1", "d2"))[,.(div1 = d1_a/d2_a
                                                          ,div2 = d1_b/d2_b)]

        div1      div2
1: 0.5200139 0.3835004
2: 0.7032111 0.6856942
3: 0.9759893 0.6951034
4: 0.5210792       NaN
5: 0.5485965 0.4417819
6: 0.5009533       NaN
7: 0.2343236       NaN
8: 0.7671728       NaN

Body:
This is a bit convoluted,
but for this problem I think you could do the following:

zs <- unique(DT$z)

sum_div <- function(dt) {
  ans <- dt[, .(div = sum(d1) / sum(d2)), by = .(z)]
  split(ans$div, factor(ans$z, levels = zs), drop = FALSE)
}

DT[, sum_div(.SD), by = .(x, y), .SDcols = c("z", "d1", "d2")]

What happens is that .SD ends up having the 3 columns specified in .SDcols,
but with different subsets for the possible combinations of x and y values.
Then, sum_div performs your desired operation only on that subset,
and splits the result to return a list so that each possible value of z gets its own column in the final data.table.

It's important to do factor(ans$z, levels = zs) in order to get the same number of list elements every time
(data.table expects that);
by specifying how many levels we expect,
split will return an empty vector if there are no values for a level,
but it will definitely return something for each.

Note that you could achieve the same with:

dcast(DT[, .(div = sum(d1) / sum(d2)), by = .(x, y, z)], x + y ~ z, value.var = "div")

I'm not sure if you gain considerable performance by doing everything in one step.

EDIT: you probably don't:

library(data.table)
library(microbenchmark)

n <- 2e5
DT = data.table(x = sample(5L, n, TRUE),
                y = sample(3L, n, TRUE),
                z = sample(letters[1:2], n, TRUE),
                d1 = runif(n),
                d2 = 1L)

zs <- sort(unique(DT$z))

sum_div <- function(dt) {
  ans <- dt[, .(div = sum(d1) / sum(d2)), by = .(z)]
  split(ans$div, factor(ans$z, levels = zs), drop = FALSE)
}

microbenchmark(
  one = DT[, sum_div(.SD), keyby = .(x, y), .SDcols = c("z", "d1", "d2")],
  two = dcast(DT[, .(div = sum(d1) / sum(d2)), by = .(x, y, z)], x + y ~ z, value.var = "div"),
  times = 10L
)
Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval
  one 24.37323 25.74273 26.72413 25.99279 26.62943 34.40309    10
  two 11.31050 11.91650 12.66345 12.51094 13.01364 15.35549    10


问:
Android Studio Packet Parsing issue .apk
Ive build an all of my Android Project for School, and cant find a solution for it online. The releases  apk was installing normally on the emulator, but cant get it to work on a real android Device. I wonder which step i did wrong or in which file i have to look closer to fix this issue. Maybe i did something very wrong in the Building Process.I used the grandle build for a  Single apk which was fully signed. Any Suggestion where i should look closer into? I Start to think maybe it has something to do with the Manifest.xml, might be there a Problem?

答:
Use the following properties in your build.gradle file:

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release
    }
}
</code>```

Now generate APK again and send me the result.

Body:
Use the following properties in your build.gradle file:

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release
    }
}

Now generate APK again and send me the result.


问:
Acess to node modules in Electron 5
Since Electron's recent version 5 have nodeIntegration default to false due to security reasons, which is the recommended way to access node modules? Is there a way to communicate with the main process without nodeIntegration?</p>

答:
Using preload script you can communicate with the main process, by importing only the ipcRenderer object to the window.

To do that you have to specify the preload script absolute path in the browserWindow webPreferences.

```<code>
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload : path.join(__dirname , '/preload_script.js')
    }
  })
</code>```

and in preload_script.js inject the ipcRenderer object

```<code>window.ipcRenderer = require('electron').ipcRenderer;

</code>```

you can use the window.ipcRenderer object in the html script for communication with main process/ or with another renderer process.

Title: Acess to node modules in Electron 5

Body:
Using preload script you can communicate with the main process, by importing only the ipcRenderer object to the window.

To do that you have to specify the preload script absolute path in the browserWindow webPreferences.

  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload : path.join(__dirname , '/preload_script.js')
    }
  })

and in preload_script.js inject the ipcRenderer object

window.ipcRenderer = require('electron').ipcRenderer;

you can use the window.ipcRenderer object in the html script for communication with main process/ or with another renderer process.


问:
React Hooks Dependencies - Infinite Loop
I have the following code:

```<code>import React from "react";

export const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback((...args) => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise, state]);

  React.useEffect(() => {
    if (options.now) {
      fetch(...args);
    }
  }, [args, fetch, options.now]);

  return {
    fetch,
    ...state
  };
};
</code>```

But I'm getting an infinite console.log loop when I try to use like this:

```<code>const allUsers = () => Promise.resolve([{ name: 'Bruno' }])

function App() {
  const { data } = useFetch(allUsers, [], { now: true })
  console.log('->', data)
  return (
    <span>Testing hook</span>
  )
}
</code>```

All the deps and the useCallback was suggestions from the lint react-hooks/exhaustive-deps. So, what I'm doing wrong?

Thanks for your help.

答:
There are 2 problems.
1. Your fetch is getting a new value every time as it has state as a dependency and that is causing useEffect run every time, so infinite loop.
2.useEffect has args as a dependency which is also not the same every time, you don't need to pass args to fetch as it's already available because of closure.

here is an updated code that doesn't go in an infinite loop. you might get lint issue but you should ignore them for now until this linter becomes more standard.

```<code>const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback(() => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise]);

  React.useEffect(() => {
    if (options.now) {
      fetch();
    }
  }, [fetch, options.now]);

  return {
    fetch,
    ...state
  };
};

const allUsers = () => Promise.resolve([{ name: 'Bruno' }])

const App = props => {
  const { data } = useFetch(allUsers, [], { now: true });
  console.log(data, "=>");
  return <input name="name" onChange={this.handleInputChange} />;
}
</code>```

Body:
I have the following code:

import React from "react";

export const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback((...args) => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise, state]);

  React.useEffect(() => {
    if (options.now) {
      fetch(...args);
    }
  }, [args, fetch, options.now]);

  return {
    fetch,
    ...state
  };
};

But I'm getting an infinite console.log loop when I try to use like this:

const allUsers = () => Promise.resolve([{ name: 'Bruno' }])

function App() {
  const { data } = useFetch(allUsers, [], { now: true })
  console.log('->', data)
  return (
    Testing hook
  )
}

All the deps and the useCallback was suggestions from the lint react-hooks/exhaustive-deps. So, what I'm doing wrong?

Thanks for your help.

Body:
There are 2 problems.
1. Your fetch is getting a new value every time as it has state as a dependency and that is causing useEffect run every time, so infinite loop.
2.useEffect has args as a dependency which is also not the same every time, you don't need to pass args to fetch as it's already available because of closure.

here is an updated code that doesn't go in an infinite loop. you might get lint issue but you should ignore them for now until this linter becomes more standard.

const useFetch = (promise, args = [], options = {}) => {
  const [state, setState] = React.useState({
    loading: false,
    data: null,
    error: null
  });

  if (!args) args = [];

  const fetch = React.useCallback(() => {
    setState({
      ...state,
      loading: true,
      error: null
    });

    return promise(...args)
      .then(response => {
        setState({
          ...state,
          loading: false,
          data: response
        });
        return response;
      })
      .catch(error => {
        setState({
          ...state,
          loading: false,
          error
        });
      });
  }, [promise]);

  React.useEffect(() => {
    if (options.now) {
      fetch();
    }
  }, [fetch, options.now]);

  return {
    fetch,
    ...state
  };
};

const allUsers = () => Promise.resolve([{ name: 'Bruno' }])

const App = props => {
  const { data } = useFetch(allUsers, [], { now: true });
  console.log(data, "=>");
  return <input name="name" onChange={this.handleInputChange} />;
}


问:
Tracking state using ASP.NET AJAX / ICallbackEventHandler
I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call.

This seems to be a common problem, but I will describe my scenario to help explain:

I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event ("OnColumnMoved" or "OnRowMoved").

ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked.

However, since the AJAX call does not update the page, the ViewState reflects the original state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the first state of the control, not the state after the first column or row was moved.

This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side.

And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change.

So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired.

答: I found a fairly elegant solution with Telerik's RadAjaxManager. It works quite nicely. Essentially you register each control which might invoke a postback, and then register each control which should be re-drawn after that postback is performed asynchronously. The RadAjaxManager will update the DOM after the async postback and rewrite the ViewState and all affected controls. After taking a peek in Reflector, it looks a little kludgy under the hood, but it suits my purposes.

ContentLicense: CC BY-SA 2.5


问:
How to disable the back button in browser when user logout in asp.net c#
Our problem is we are able to clear session on logout.

But if a user clicks the back button then he/she can go through all previous screens.

But the advantage is that on a single click on any of of such previously surf page bring user to login page back ,we had done that. But our requirement is we should no allow user to go through the previously surf page.

答:
This is the solution I found on Coding Solutions

in the master page

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ClearHeaders();
        Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
        Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
        Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
        Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
    }
</code>```

Control LoginStatus

```<code>    protected void LoginStatusUser_LoggedOut(object sender, EventArgs e)
    {
        Session.Abandon();
        FormsAuthentication.SignOut();
    }
</code>```

OwnerDisplayName: sunny shukla

Body:
This is the solution I found on Coding Solutions

in the master page

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ClearHeaders();
        Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
        Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
        Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
        Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
        Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
    }

Control LoginStatus

    protected void LoginStatusUser_LoggedOut(object sender, EventArgs e)
    {
        Session.Abandon();
        FormsAuthentication.SignOut();
    }


问:
Efficient way to obtain matrix with pairwise maximum between two values
I want to create a matrix that for the entry i,j it returns the maximum between D[i,1] and D[j,1].

I have a vector of numbers that in a MWE can be reduced to this:

```<code>set.seed(10)
n <- 2000
D <- matrix(runif(n,0,100), ncol=1)
</code>```

With a double for loop in Base R it is extremely inefficient:

```<code>X <- Matrix::Matrix(0, nrow = n, ncol = n, sparse = T)

for (i in 1:n) {
  for (j in 1:n) {
    X[i,j] <- max(D[i,1], D[j,1])
  }
}
</code>```

I also tried with dplyr:

```<code>library(dplyr)

X <- tibble(i = 1:n, D = D)

X <- expand.grid(i = 1:n, j = 1:n)

X <- X %>%
  as_tibble() %>%
  left_join(X, by = "i") %>%
  left_join(X, by = c("j" = "i")) %>%
  rowwise() %>%
  mutate(D = max(D.x, D.y)) %>%
  ungroup()
</code>```

it returns Error: std::bad_alloc before I can do X <- Matrix::Matrix(X$D, nrow = n, ncol = n, sparse = T)

My last try was to use RcppArmadillo in a way it also works with Windows:

```<code>#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat pairwise_max(arma::mat x, arma::mat y) {
  // Constants
  int n = (int) x.n_rows;

  // Output
  arma::mat z(n,n);

  // Filling with ones
  z.ones();

  for (int i=0; i<n; i++)
    for (int j=0; j<=i; j++) {
      // Fill the lower part
      z.at(i,j) = std::max(y(i,0), y(j,0));
      // Fill the upper part
      z.at(j,i) = z.at(i,j);
    }

    return z;
}
</code>```

it works almost flawlessy, but I'm quite sure there is an efficient way with base R that I am not seeing.

答:
In base R, I would do

```<code>D2 <- drop(D)
X2 <- outer(D2, D2, pmax)
</code>```

which is ~20 times as fast as the double for loop.

Body:
I want to create a matrix that for the entry i,j it returns the maximum between D[i,1] and D[j,1].

I have a vector of numbers that in a MWE can be reduced to this:

set.seed(10)
n <- 2000
D <- matrix(runif(n,0,100), ncol=1)

With a double for loop in Base R it is extremely inefficient:

X <- Matrix::Matrix(0, nrow = n, ncol = n, sparse = T)

for (i in 1:n) {
  for (j in 1:n) {
    X[i,j] <- max(D[i,1], D[j,1])
  }
}

I also tried with dplyr:

library(dplyr)

X <- tibble(i = 1:n, D = D)

X <- expand.grid(i = 1:n, j = 1:n)

X <- X %>%
  as_tibble() %>%
  left_join(X, by = "i") %>%
  left_join(X, by = c("j" = "i")) %>%
  rowwise() %>%
  mutate(D = max(D.x, D.y)) %>%
  ungroup()

it returns Error: std::bad_alloc before I can do X <- Matrix::Matrix(X$D, nrow = n, ncol = n, sparse = T)

My last try was to use RcppArmadillo in a way it also works with Windows:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat pairwise_max(arma::mat x, arma::mat y) {
  // Constants
  int n = (int) x.n_rows;

  // Output
  arma::mat z(n,n);

  // Filling with ones
  z.ones();

  for (int i=0; i<n; i++)
    for (int j=0; j<=i; j++) {
      // Fill the lower part
      z.at(i,j) = std::max(y(i,0), y(j,0));
      // Fill the upper part
      z.at(j,i) = z.at(i,j);
    }

    return z;
}

it works almost flawlessy, but I'm quite sure there is an efficient way with base R that I am not seeing.

Body:
In base R, I would do

D2 <- drop(D)
X2 <- outer(D2, D2, pmax)

which is ~20 times as fast as the double for loop.


问:
sonata admin Variable "form_helper" does not exist. after twig update
before update (no errors)

```<code>symfony/twig-bridge v4.2.8  v4.3.0  Symfony Twig Bridge
symfony/twig-bundle v4.2.8  v4.3.0  Symfony TwigBundle
twig/extensions     v1.5.4  v1.5.4  Common additional features for Twig that do not directly belong in core
twig/twig           v2.10.0 v2.11.0 Twig, the flexible, fast, and secure template language for PHP
</code>```

after update (error sonata admin Variable "form_helper" does not exist.)

```<code>symfony/twig-bridge v4.3.0  v4.3.0  Symfony Twig Bridge
symfony/twig-bundle v4.3.0  v4.3.0  Symfony TwigBundle
twig/extensions     v1.5.4  v1.5.4  Common additional features for Twig that do not directly belong in core
twig/twig           v2.11.0 v2.11.0 Twig, the flexible, fast, and secure template language for PHP
</code>```

error:

```<code>Variable "form_helper" does not exist.

in vendor/sonata-project/admin-bundle/src/Resources/views/CRUD/base_edit_form.html.twig (line 63)
</code>```

sonata:

```<code>composer show --latest 'sonata-project/*'
sonata-project/admin-bundle              3.48.3 3.48.3 The missing Symfony Admin Generator
sonata-project/block-bundle              3.15.0 3.15.0 Symfony SonataBlockBundle
sonata-project/cache                     1.1.1  2.0.1  Cache library
sonata-project/cache-bundle              2.4.2  3.0.1  This bundle provides caching services
sonata-project/core-bundle               3.17.0 3.17.0 Symfony SonataCoreBundle
sonata-project/datagrid-bundle           2.5.0  3.0.0  Symfony SonataDatagridBundle
sonata-project/doctrine-extensions       1.3.0  1.3.0  Doctrine2 behavioral extensions
sonata-project/doctrine-orm-admin-bundle 3.9.0  3.9.0  Symfony Sonata / Integrate Doctrine ORM into the SonataAdminBundle
sonata-project/easy-extends-bundle       2.5.0  2.5.0  Symfony SonataEasyExtendsBundle
sonata-project/exporter                  2.0.1  2.0.1  Lightweight Exporter library
sonata-project/notification-bundle       3.6.1  3.6.1  Symfony SonataNotificationBundle
sonata-project/page-bundle               3.11.1 3.11.1 This bundle provides a Site and Page management through container and block services
sonata-project/seo-bundle                2.7.0  2.7.0  Symfony SonataSeoBundle
sonata-project/translation-bundle        2.4.1  2.4.1  SonataTranslationBundle
sonata-project/user-bundle               4.3.0  4.3.0  Symfony SonataUserBundle
</code>```

答:
I don't know how to correct fix it, but I just reverted

```<code>symfony/twig-bridge to v4.2.8
twig/twig to v2.10.0
</code>```

And all ok for me now. I hope it help you.

I set in composer.json

```<code>"symfony/twig-bridge": "4.2.8",
"twig/twig": "2.10"
</code>```

and updated composer.

Body:
before update (no errors)

symfony/twig-bridge v4.2.8  v4.3.0  Symfony Twig Bridge
symfony/twig-bundle v4.2.8  v4.3.0  Symfony TwigBundle
twig/extensions     v1.5.4  v1.5.4  Common additional features for Twig that do not directly belong in core
twig/twig           v2.10.0 v2.11.0 Twig, the flexible, fast, and secure template language for PHP

after update (error sonata admin Variable "form_helper" does not exist.)

symfony/twig-bridge v4.3.0  v4.3.0  Symfony Twig Bridge
symfony/twig-bundle v4.3.0  v4.3.0  Symfony TwigBundle
twig/extensions     v1.5.4  v1.5.4  Common additional features for Twig that do not directly belong in core
twig/twig           v2.11.0 v2.11.0 Twig, the flexible, fast, and secure template language for PHP

error:

Variable "form_helper" does not exist.

in vendor/sonata-project/admin-bundle/src/Resources/views/CRUD/base_edit_form.html.twig (line 63)

sonata:

composer show --latest 'sonata-project/*'
sonata-project/admin-bundle              3.48.3 3.48.3 The missing Symfony Admin Generator
sonata-project/block-bundle              3.15.0 3.15.0 Symfony SonataBlockBundle
sonata-project/cache                     1.1.1  2.0.1  Cache library
sonata-project/cache-bundle              2.4.2  3.0.1  This bundle provides caching services
sonata-project/core-bundle               3.17.0 3.17.0 Symfony SonataCoreBundle
sonata-project/datagrid-bundle           2.5.0  3.0.0  Symfony SonataDatagridBundle
sonata-project/doctrine-extensions       1.3.0  1.3.0  Doctrine2 behavioral extensions
sonata-project/doctrine-orm-admin-bundle 3.9.0  3.9.0  Symfony Sonata / Integrate Doctrine ORM into the SonataAdminBundle
sonata-project/easy-extends-bundle       2.5.0  2.5.0  Symfony SonataEasyExtendsBundle
sonata-project/exporter                  2.0.1  2.0.1  Lightweight Exporter library
sonata-project/notification-bundle       3.6.1  3.6.1  Symfony SonataNotificationBundle
sonata-project/page-bundle               3.11.1 3.11.1 This bundle provides a Site and Page management through container and block services
sonata-project/seo-bundle                2.7.0  2.7.0  Symfony SonataSeoBundle
sonata-project/translation-bundle        2.4.1  2.4.1  SonataTranslationBundle
sonata-project/user-bundle               4.3.0  4.3.0  Symfony SonataUserBundle

Body:
I don't know how to correct fix it, but I just reverted

symfony/twig-bridge to v4.2.8
twig/twig to v2.10.0

And all ok for me now. I hope it help you.

I set in composer.json

"symfony/twig-bridge": "4.2.8",
"twig/twig": "2.10"

and updated composer.


问:
How to add HTML tag to the last word of a string?
How can add I HTML tags (   ) to the last word of a string?

The word is different for each result.

Language used : PHP
The string is a 1 line string ( the local market of city ) and inserted in a link

```<code>echo '<a href="'.$marche_permalink.'">'. $marche_title . '</a> ['. $hdebut .' - '. $hfin .']<br />';
</code>```

The string is $marche_title.

答:
I think the simplest interpretation of your question is this:

```<code>$formatted = preg_replace('/\S+$/', '<b>$0</b>', $string);
</code>```

It will wrap any sequence of non-whitespace characters before the end of the string in the  tag. If there aren't any spaces, it will wrap the entire string in the tag, which should be okay because the entire string is the last word of the string.

Body:
How can add I HTML tags (   ) to the last word of a string?

The word is different for each result.

Language used : PHP
The string is a 1 line string ( the local market of city ) and inserted in a link

echo ''. $marche_title . ' ['. $hdebut .' - '. $hfin .']
';

The string is $marche_title.

Body:
I think the simplest interpretation of your question is this:

$formatted = preg_replace('/\S+$/', '<b>$0</b>', $string);

It will wrap any sequence of non-whitespace characters before the end of the string in the <b> tag. If there aren't any spaces, it will wrap the entire string in the tag, which should be okay because the entire string is the last word of the string.


问:
Can Python object instances have different logger levels at the same time?
I wanted different objects in my program to have different logging levels. Is that possible?

I made a base class as shown below containing methods to set the logging levels.

```<code>class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        logging.getLogger().setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        logging.getLogger().setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        logging.getLogger().setLevel(logging.INFO)

    print('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity
</code>```

My other two classes inherit from the 'Logging' class and I have following in their respective init methods:

```<code>self.verbosity = verbosity
</code>```

However, what I observed is that whenever an instance of either class is used to set the logging level, the logging level is set globally.
Is there any way to restrict logging levels to specific class instances?

Edited:
Using the suggestion from John Gordon, I was able to come up with a solution. Please see below.

答:
```<code>if verbosity == 'DEBUG':
    logging.getLogger().setLevel(logging.DEBUG)

elif verbosity == 'INFO':
    logging.getLogger().setLevel(logging.INFO)

elif verbosity == 'WARNING':
    logging.getLogger().setLevel(logging.INFO)
</code>```

Calling getLogger() without a name returns the root logger.

So, all of these calls operate on the root logger, erasing any previous setting.

One way around this is to supply a name when calling getLogger(), and ensure the name is different for each class instance.

Body:
I wanted different objects in my program to have different logging levels. Is that possible?

I made a base class as shown below containing methods to set the logging levels.

class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        logging.getLogger().setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        logging.getLogger().setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        logging.getLogger().setLevel(logging.INFO)

    print('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity

My other two classes inherit from the 'Logging' class and I have following in their respective init methods:

self.verbosity = verbosity

However, what I observed is that whenever an instance of either class is used to set the logging level, the logging level is set globally.
Is there any way to restrict logging levels to specific class instances?

Edited:
Using the suggestion from John Gordon, I was able to come up with a solution. Please see below.

Body:
if verbosity == 'DEBUG':
    logging.getLogger().setLevel(logging.DEBUG)

elif verbosity == 'INFO':
    logging.getLogger().setLevel(logging.INFO)

elif verbosity == 'WARNING':
    logging.getLogger().setLevel(logging.INFO)

Calling getLogger() without a name returns the root logger.

So, all of these calls operate on the root logger, erasing any previous setting.

One way around this is to supply a name when calling getLogger(), and ensure the name is different for each class instance.