问:
Resetting an iterator, which is a map object?
I'm learning Python by myself.

I've come across the following

```<code>sol=map(pow,[1,2,3],[4,5,6])
</code>```

sol is an iterator.

When I run consecutively next(sol), I will iterate along the elements of sol, until I get StopIteration error.

However, how can I restart the iteration?

I've tried iter_1=itertools.cycle(sol), but I need to restart sol by running sol=map(pow,[1,2,3],[4,5,6]) and only then iter_1=itertools.cycle(sol).

Is there another way?

答:
Iterating an iterator/generator consumes the values from it (infinite generators being an exception), meaning that they will no longer be available on future iterations (as you've seen). For a typical iterator/generator in Python, the only true way to "restart" it is to re-initialize it.

```<code>>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> list(sol)
[1, 32, 729]
>>> next(sol)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> next(sol)
1
</code>```

There are ways that you can work with the iterator to make it reusable though, such as with itertools.tee (as mentioned by one of the answers to the question linked by @JanChristophTerasa), or to convert the iterator into a list, which will persist its data.

itertools.tee

```<code>>>> from itertools import tee
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> a, b = tee(sol, 2)
>>> list(a)
[1, 32, 729]
>>> list(b)
[1, 32, 729]
>>> list(a)
[]
</code>```

with tee though, both a and b will still be iterators, so you'll have the same problem with them.

Another common way to handle this is with list()

```<code>sol = list(map(pow, [1, 2, 3], [4, 5, 6]))
>>> sol
[1, 32, 729]
>>> sol
[1, 32, 729]
</code>```

Now, sol is a list of values instead of an iterator, which means you can iterate it as many times as you want - the values will remain there. This does mean you can't use next with it (in the sense of next(sol)), but you can get an iterator back from your new list with iter(sol) if you need an iterator specifically.

Edit

I saw itertools.cycle mentioned in the comments, which is also a valid option so I thought I might add some info on it here as well.

itertools.cycle is one of those infinite generators I mentioned at the start. It is still an iterator, but in a way that you'll never run out of values.

```<code>>>> from itertools import cycle
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> infinite = cycle(sol)
>>> for _ in range(5):
...     print(next(infinite))
...
1
32
729
1
32
>>>
</code>```

A few notes on this - after iterating infinite N times, it will be positioned after whatever the last value was pulled from it. Iterating it again later will resume from that position, not from the start.

Also, and this is very important, do not iterate an infinite generator in an unbounded fashion, like list(infinite) or for x in infinite:, or you're gonna have a bad time.

Body:
I'm learning Python by myself.

I've come across the following

sol=map(pow,[1,2,3],[4,5,6])

sol is an iterator.

When I run consecutively next(sol), I will iterate along the elements of sol, until I get StopIteration error.

However, how can I restart the iteration?

I've tried iter_1=itertools.cycle(sol), but I need to restart sol by running sol=map(pow,[1,2,3],[4,5,6]) and only then iter_1=itertools.cycle(sol).

Is there another way?

Body:
Iterating an iterator/generator consumes the values from it (infinite generators being an exception), meaning that they will no longer be available on future iterations (as you've seen). For a typical iterator/generator in Python, the only true way to "restart" it is to re-initialize it.

>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> list(sol)
[1, 32, 729]
>>> next(sol)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> next(sol)
1

There are ways that you can work with the iterator to make it reusable though, such as with itertools.tee (as mentioned by one of the answers to the question linked by @JanChristophTerasa), or to convert the iterator into a list, which will persist its data.

itertools.tee

>>> from itertools import tee
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> a, b = tee(sol, 2)
>>> list(a)
[1, 32, 729]
>>> list(b)
[1, 32, 729]
>>> list(a)
[]

with tee though, both a and b will still be iterators, so you'll have the same problem with them.

Another common way to handle this is with list()

sol = list(map(pow, [1, 2, 3], [4, 5, 6]))
>>> sol
[1, 32, 729]
>>> sol
[1, 32, 729]

Now, sol is a list of values instead of an iterator, which means you can iterate it as many times as you want - the values will remain there. This does mean you can't use next with it (in the sense of next(sol)), but you can get an iterator back from your new list with iter(sol) if you need an iterator specifically.

Edit

I saw itertools.cycle mentioned in the comments, which is also a valid option so I thought I might add some info on it here as well.

itertools.cycle is one of those infinite generators I mentioned at the start. It is still an iterator, but in a way that you'll never run out of values.

>>> from itertools import cycle
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> infinite = cycle(sol)
>>> for _ in range(5):
...     print(next(infinite))
...
1
32
729
1
32
>>>

A few notes on this - after iterating infinite N times, it will be positioned after whatever the last value was pulled from it. Iterating it again later will resume from that position, not from the start.

Also, and this is very important, do not iterate an infinite generator in an unbounded fashion, like list(infinite) or for x in infinite:, or you're gonna have a bad time.


来源: stackexchange

问:
PHP Regex to match HTML code using capturing group
I'm stuck trying to write a regular expression in PHP that matches A HREF tags using capturing groups.

My current code looks like this:

$content = preg_replace_callback(
  '/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
...```
</div>
</div>
</p>

<p>The code works perfectly fine for anything like this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Test link</code>```

But I have some URLs that look like this - note the nested :

Test link```

My second capturing group matches for ^< which is why the  doesn't match. I was trying to change the group to match anything BUT . That's where I failed, thanks to my lack of regex experience :)

Could any regex expert please point me in the right direction?

答:
The current regex should help you:

```<code><a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>(?:<[^>]+>)*([^<]*)(?:</[^>]+>)*<\/a>
</code>```

This will match your example as well as this example:

```<code><a href="/go/bla" rel="sponsored noopener" target="_blank"><span><h1>Test link</h1></span></a>
</code>```

However what about this?

```<code><a href="/go/bla" rel="sponsored noopener" target="_blank"><span><h1>Test <span>link</span></h1></span></a>
</code>```

Nope!  This breaks. And now we'll have to go back and wrap our minds around tags within tags with text outside those tags to still match, we'll have to break it up some more.  At this stage it would be better to simply just fetch a list of all a tags, and then perform some substitutions to extract the data you need after the fact.

```<code>$matches = preg_match_callback('/<a[^>]*?href=(.*?")[^>]*?>(.*?)</a>/i', function($m) {
  ... more regexes
}
</code>```

It may be better to consider using a library that allows you to load html content as objects (much like a browser would) and query your results using something like xpath.

In PHP you can use the DOM and XPath to load html.  Below is an example.

$doc = new DOMDocument();
$html = <<<EOD

Test link
Test link

Test link

EOD;

$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$query = $xpath->query('//a');

if (!is_null($query)) {
    foreach ($query as $q) {
        print $q->getAttribute('href') . ' - ';
        print $q->nodeValue . "\n";
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
I'm stuck trying to write a regular expression in PHP that matches A HREF tags using capturing groups.

My current code looks like this:

$content = preg_replace_callback(
  '/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
...

The code works perfectly fine for anything like this:

Test link

But I have some URLs that look like this - note the nested :

Test link

My second capturing group matches for ^< which is why the  doesn't match. I was trying to change the group to match anything BUT . That's where I failed, thanks to my lack of regex experience :)

Could any regex expert please point me in the right direction?

Body:
The current regex should help you:

<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>(?:<[^>]+>)*([^<]*)(?:</[^>]+>)*<\/a>

This will match your example as well as this example:

<a href="/go/bla" rel="sponsored noopener" target="_blank"><span><h1>Test link</h1></span></a>

However what about this?

<a href="/go/bla" rel="sponsored noopener" target="_blank"><span><h1>Test <span>link</span></h1></span></a>

Nope!  This breaks. And now we'll have to go back and wrap our minds around tags within tags with text outside those tags to still match, we'll have to break it up some more.  At this stage it would be better to simply just fetch a list of all a tags, and then perform some substitutions to extract the data you need after the fact.

$matches = preg_match_callback('/<a[^>]*?href=(.*?")[^>]*?>(.*?)</a>/i', function($m) {
  ... more regexes
}

It may be better to consider using a library that allows you to load html content as objects (much like a browser would) and query your results using something like xpath.

In PHP you can use the DOM and XPath to load html.  Below is an example.

$doc = new DOMDocument();
$html = <<<EOD
<html>
<body>
<a href="/go/bla" rel="sponsored noopener" target="_blank">Test link</a>
<a href="/go/bla" rel="sponsored noopener" target="_blank"><span>Test link</span></a>
<a href="/go/bla" rel="sponsored noopener" target="_blank"><span><h1>Test <span>link</span></h1></span></a>
</body>
</html>
EOD;

$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$query = $xpath->query('//a');

if (!is_null($query)) {
    foreach ($query as $q) {
        print $q->getAttribute('href') . ' - ';
        print $q->nodeValue . "\n";
    }
}


问:
Java regex with replace
I need to replace string with a variable inside {} using a regex

For example:

```<code>"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"
</code>```

Inside the Strings variables inside {} can be more than 1

I need this code to allow users to modify messages. variable inside {} after @ like in the example 'US-server' are put in by users so there aren't list to check for variable. Variables could be as strange as possible ex: '{online@test-UK}' '{online@asdtest}'

```<code>public static String getReplaced(String d) {
    String result = d.split("\\{online@")[0];

    for (int i = 1; i < d.split("\\{online@").length; i++) {
        String dd = d.split("\\{online@")[i];

        Pattern p = Pattern.compile("(.*?)}(.*)");
        Matcher m = p.matcher(dd);

        if (m.lookingAt()) {
            int count = 12;

            result += count + m.group(2);
        } else {
            result += dd;
        }
    }

    return result;
}
</code>```

答:
You don't need regex for this, and probably shouldn't use it, because using user input as a regex has some potential security risks.

```<code>public String replaceTag(String tag, String replacement, String template) {
   private final String decoratedTag = "{online@" + tag + "}";

   return template.replace(decoratedTag, replacement);
}
</code>```

You can call this repeatedly:

```<code>private String template = getTemplateFromUser();
private String output = template.replace('US-server', usServerCount);
output = output.replace('asdtest', testValue);
return output;
</code>```

... or you can be more sophisticated and loop through a set of tag/value pairs, for example from a Map<String, String>

Note that String.replace() just replaces character sequences dumbly, it's not a regular expression replace, which for this problem is a good thing.

Title: Java regex with replace

Body:
I need to replace string with a variable inside {} using a regex

For example:

"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"

Inside the Strings variables inside {} can be more than 1

I need this code to allow users to modify messages. variable inside {} after @ like in the example 'US-server' are put in by users so there aren't list to check for variable. Variables could be as strange as possible ex: '{online@test-UK}' '{online@asdtest}'

public static String getReplaced(String d) {
    String result = d.split("\\{online@")[0];

    for (int i = 1; i < d.split("\\{online@").length; i++) {
        String dd = d.split("\\{online@")[i];

        Pattern p = Pattern.compile("(.*?)}(.*)");
        Matcher m = p.matcher(dd);

        if (m.lookingAt()) {
            int count = 12;

            result += count + m.group(2);
        } else {
            result += dd;
        }
    }

    return result;
}

Body:
You don't need regex for this, and probably shouldn't use it, because using user input as a regex has some potential security risks.

public String replaceTag(String tag, String replacement, String template) {
   private final String decoratedTag = "{online@" + tag + "}";

   return template.replace(decoratedTag, replacement);
}

You can call this repeatedly:

private String template = getTemplateFromUser();
private String output = template.replace('US-server', usServerCount);
output = output.replace('asdtest', testValue);
return output;

... or you can be more sophisticated and loop through a set of tag/value pairs, for example from a Map<String, String>

Note that String.replace() just replaces character sequences dumbly, it's not a regular expression replace, which for this problem is a good thing.


问:
Is it possible to do a firmware update using the Azure IoT Hub and Blob storage?
I have the azure IoT client running on an STM32H7 with Keil RTX 5 as its operating system. What I want to do is download a binary file from Azure (firmware) and update the firmware on my device (STM32H7).

What I have done:

I have uploaded a binary file to Azure blob storage.
I have got the sample "iothub_client_device_twin_and_methods_sample.c" example working and running correctly (It connects to the Azure IoT hub with no issues)

I want to go about my firmware update by downloading this binary file and then writing it to a storage area on my device, but I think I have the latter part covered.

From my current research, I believe the correct approach to this is to somehow create a cloud to device message containing the binary file.

My question is, based on the above:

What is the correct way to download a binary file from blob storage using the C sdk to my embedded device?

PS: I have seen there is an example for a firmware update using the raspberry pi but I was not able to understand it and modify it for my purpose.

Any help would be very appreciated. Thanks.

Edit: my firmware update will be firmware over the air, hence the need for a way to download it from Azure

Thanks

答:
In answer to my own question:

I found that the C sdk does support uploading files to blob storage but not downloading then. The best approach to downloading them I found was to install a HTTP library and request to download the file from Azure storage. I also found that there seems to be no way of using the C SDK to do a firmware over the air update as I had first imagined.


问:
OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079:
I am using the Azure AD B2C authentication in my ASP .NET Core web app. I also want to get notification after successful authentication of user so that I can add custom roles and for that I am trying to register OnAuthorizationCodeReceived callback. But as soon as I do it I am getting following exception...

OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

The original code in the Setup.cs which works is...

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

        services.AddControllersWithViews();
        services.AddRazorPages();
    }
</code>```

But when I add following code in ConfigureServices() function...

```<code>        services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
        {
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            };
        });

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
}
</code>```

It starts generating above mentioned exception when I click on Signin button. Looks like I am able to authenticate and I get OnAuthorizationCodeReceived callback too. But once control returns from OnAuthorizationCodeReceived that exception occurs with following stack...

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RedeemAuthorizationCodeAsync(OpenIdConnectMessage tokenEndpointRequest)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()

Please let me know what's wrong here?

答:
Thanks Nan Yu for your reply.

Finally I am able to fix that by using following code

```<code>services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnTokenValidated = OnTokenValidated
        };
    });
</code>```

So initializing options.ResponseType is really not necessary and OnTokenValidated worked for me.

Body:
I am using the Azure AD B2C authentication in my ASP .NET Core web app. I also want to get notification after successful authentication of user so that I can add custom roles and for that I am trying to register OnAuthorizationCodeReceived callback. But as soon as I do it I am getting following exception...

OpenIdConnectProtocolException: Message contains error: 'invalid_request', error_description: 'AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

The original code in the Setup.cs which works is...

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

But when I add following code in ConfigureServices() function...

        services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
        {
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            };
        });

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
}

It starts generating above mentioned exception when I click on Signin button. Looks like I am able to authenticate and I get OnAuthorizationCodeReceived callback too. But once control returns from OnAuthorizationCodeReceived that exception occurs with following stack...

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RedeemAuthorizationCodeAsync(OpenIdConnectMessage tokenEndpointRequest)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()

Please let me know what's wrong here?

Body:
Thanks Nan Yu for your reply.

Finally I am able to fix that by using following code

services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnTokenValidated = OnTokenValidated
        };
    });

So initializing options.ResponseType is really not necessary and OnTokenValidated worked for me.


问:
Problem finding duplicate numbers in array, is my technique bad?
I used a HashMap to store the occurrences of each element, and then iterated over the hash map to get duplicated element, but something doesn't feel right about this solution.

Problem statement in Firecode.io:

Write a method duplicate to find the repeated or duplicate elements in an array. This method should return a list of repeated integers in a string with the elements sorted in ascending order (as illustrated below).

duplicate({1,3,4,2,1}) --> "[1]"

duplicate({1,3,4,2,1,2,4}) --> "[1, 2, 4]"

Note: You may use toString() method to return the standard string representation of most data structures, and Arrays.sort() to sort your result.*

Here is my code:

```<code> public String duplicate(int[] numbers) {
      HashMap < Integer, Integer > hs = new HashMap < Integer, Integer > ();
      for (int i = 0; i < numbers.length; i++) {
           if (hs.get(numbers[i]) == null) {
                hs.put(numbers[i], 1);
           } else hs.put(numbers[i], (Integer) hs.get(numbers[i]) + 1);
      }

      int size = 0;
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                size++;
           }
      }
      int j = 0;
      int[] a = new int[size];
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                a[j++] = i;
           }
      }

      Arrays.sort(a);
      return Arrays.toString(a);
 }
</code>```

答:
Since you don't have to tell how many times an element is duplicated you only need a Set to remember which elements are unique and which not. If you know the element values (e.g. numbers between 1 and 10) you could further simplify Set to boolean[] or a bit vector:

```<code>int[] numbers = {1, 3, 4, 2, 2, 1, 2, 4, 4};
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int n : numbers) {
    if (!unique.add(n)) {
        duplicates.add(n);
    }
}
List<Integer> result = new ArrayList<>(duplicates);
result.sort(Integer::compareTo);
System.out.println(result); // [1, 2, 4]
</code>```

Body:
I used a HashMap to store the occurrences of each element, and then iterated over the hash map to get duplicated element, but something doesn't feel right about this solution.

Problem statement in Firecode.io:

Write a method duplicate to find the repeated or duplicate elements in an array. This method should return a list of repeated integers in a string with the elements sorted in ascending order (as illustrated below).

duplicate({1,3,4,2,1}) --> "[1]"

duplicate({1,3,4,2,1,2,4}) --> "[1, 2, 4]"

Note: You may use toString() method to return the standard string representation of most data structures, and Arrays.sort() to sort your result.*

Here is my code:

 public String duplicate(int[] numbers) {
      HashMap < Integer, Integer > hs = new HashMap < Integer, Integer > ();
      for (int i = 0; i < numbers.length; i++) {
           if (hs.get(numbers[i]) == null) {
                hs.put(numbers[i], 1);
           } else hs.put(numbers[i], (Integer) hs.get(numbers[i]) + 1);
      }

      int size = 0;
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                size++;
           }
      }
      int j = 0;
      int[] a = new int[size];
      for (int i: hs.keySet()) {
           if (hs.get(i) > 1) {
                a[j++] = i;
           }
      }

      Arrays.sort(a);
      return Arrays.toString(a);
 }

Body:
Since you don't have to tell how many times an element is duplicated you only need a Set to remember which elements are unique and which not. If you know the element values (e.g. numbers between 1 and 10) you could further simplify Set to boolean[] or a bit vector:

int[] numbers = {1, 3, 4, 2, 2, 1, 2, 4, 4};
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int n : numbers) {
    if (!unique.add(n)) {
        duplicates.add(n);
    }
}
List<Integer> result = new ArrayList<>(duplicates);
result.sort(Integer::compareTo);
System.out.println(result); // [1, 2, 4]


问:
Git command to get pull request subject body from issue number
I would like to get pull request body, subject and URL from issue number by git command especially by gitPython library. How can I do it?</p>

答:
GitPython is used for git related objects whereas a Pull Request is GitHub related and hence cannot be used to get GitHub data.

You may use GitHub's v4 GraphQL API to get the pull request details with the below query

```<code>query {
  repository(name: "gitPython",owner:"gitpython-developers"){
    pullRequest(number:974){
      body
      title
      url
    }
  }
}
</code>```

The curl request for the above query:

```<code>curl -L -X POST 'https://api.github.com/graphql' \
-H 'Authorization: bearer <token>' \
-H 'Content-Type: text/plain' \
--data-raw '{"query":"{\n repository(name: \"gitPython\",owner:\"gitpython-developers\"){\n pullRequest(number:974){\n body\n title\n url\n }\n }\n }"'
</code>```

The response for the above request:

```<code>{
  "data": {
    "repository": {
      "pullRequest": {
        "body": "Removed A from Dockerfile that I added accidentally. THIS WILL BREAK THE BUILD",
        "title": "Remove A from Dockerfile",
        "url": "https://github.com/gitpython-developers/GitPython/pull/974"
      }
    }
  }
}
</code>```

Note: You need to generate a token to access the GraphQL API, which you can generate by following the steps given here

Alternatively, you can even use GitHub's v3 API as below to get the pull request details, which would have the body, title and url fields as part of the response

```<code>GET https://api.github.com/repos/{owner}/{repoName}/pulls/{pullRequestNumber}

GET https://api.github.com/repos/gitpython-developers/GitPython/pulls/974
</code>```

Body:
GitPython is used for git related objects whereas a Pull Request is GitHub related and hence cannot be used to get GitHub data.

You may use GitHub's v4 GraphQL API to get the pull request details with the below query

query {
  repository(name: "gitPython",owner:"gitpython-developers"){
    pullRequest(number:974){
      body
      title
      url
    }
  }
}

The curl request for the above query:

curl -L -X POST 'https://api.github.com/graphql' \
-H 'Authorization: bearer <token>' \
-H 'Content-Type: text/plain' \
--data-raw '{"query":"{\n repository(name: \"gitPython\",owner:\"gitpython-developers\"){\n pullRequest(number:974){\n body\n title\n url\n }\n }\n }"'

The response for the above request:

{
  "data": {
    "repository": {
      "pullRequest": {
        "body": "Removed A from Dockerfile that I added accidentally. THIS WILL BREAK THE BUILD",
        "title": "Remove A from Dockerfile",
        "url": "https://github.com/gitpython-developers/GitPython/pull/974"
      }
    }
  }
}

Note: You need to generate a token to access the GraphQL API, which you can generate by following the steps given here

Alternatively, you can even use GitHub's v3 API as below to get the pull request details, which would have the body, title and url fields as part of the response

GET https://api.github.com/repos/{owner}/{repoName}/pulls/{pullRequestNumber}

GET https://api.github.com/repos/gitpython-developers/GitPython/pulls/974


问:
PowerShell command not run via cmd script
Here see the script, the last command should works, i mean everything's ok and it works when i run in windows Powershell.
But when i join that with 2 first commands which are bash scripts, the powershell's one won't run:</p>

```<code>Net user administrator /active:yes

Net user administrator Hardware123

Set-LocalUser -Name "administrator" -PasswordNeverExpires 1
</code>```

答:
If you want to call powershell commands from a cmd / batch file, use the following syntax. You have to call powershell to be able to run powershell commands,

```<code>Net user administrator /active:yes
Net user administrator Hardware123
powershell.exe Set-LocalUser -Name "administrator" -PasswordNeverExpires 1
</code>```

This is with assumption that you already have admin access to perform the above script.

You can also run multiple commands with powershell.exe if you intend to use variables,

```<code>powershell -Command "$local = Get-LocalUser; $local.Name; if ('Administrator' -in $local.Name) { 'Do Something' } else { 'Administrator Not Found' }"
</code>```

Body:
Here see the script, the last command should works, i mean everything's ok and it works when i run in windows Powershell.
But when i join that with 2 first commands which are bash scripts, the powershell's one won't run:

Net user administrator /active:yes

Net user administrator Hardware123

Set-LocalUser -Name "administrator" -PasswordNeverExpires 1

Body:
If you want to call powershell commands from a cmd / batch file, use the following syntax. You have to call powershell to be able to run powershell commands,

Net user administrator /active:yes
Net user administrator Hardware123
powershell.exe Set-LocalUser -Name "administrator" -PasswordNeverExpires 1

This is with assumption that you already have admin access to perform the above script.

You can also run multiple commands with powershell.exe if you intend to use variables,

powershell -Command "$local = Get-LocalUser; $local.Name; if ('Administrator' -in $local.Name) { 'Do Something' } else { 'Administrator Not Found' }"


问:
capture of ? using Lombok builder
I have this class

```<code>public class Hostel extends Hotel<Book> {
}
</code>```

and this other one

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = { "id" })
@SuperBuilder(toBuilder = true)
@JsonInclude(NON_NULL)
public class Hotel<T>  {
...
}
</code>```

but when I do

```<code>Hostel hostel = Hostel.builder().build();
</code>```

I got this compilation error

```<code> Required type: Hostel
Provided:
capture of ?
</code>```

答:
You don't have any annotations on Hostel. Hostel.builder() is really a masquerading Hotel.builder().

So the assignment would have to be

```<code>final Hotel<?> build = Hostel.builder().build();
</code>```

Or more accurately (making static methods subject to inheritance was IMO a mistake)

```<code>final Hotel<?> build = Hotel.builder().build();
</code>```

You probably want to add some Lombok annotations to the child class.

Title: capture of ? using Lombok builder

Body:
I have this class

public class Hostel extends Hotel<Book> {
}

and this other one

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = { "id" })
@SuperBuilder(toBuilder = true)
@JsonInclude(NON_NULL)
public class Hotel<T>  {
...
}

but when I do

Hostel hostel = Hostel.builder().build();

I got this compilation error

 Required type: Hostel
Provided:
capture of ?

Body:
You don't have any annotations on Hostel. Hostel.builder() is really a masquerading Hotel.builder().

So the assignment would have to be

final Hotel<?> build = Hostel.builder().build();

Or more accurately (making static methods subject to inheritance was IMO a mistake)

final Hotel<?> build = Hotel.builder().build();

You probably want to add some Lombok annotations to the child class.


答:
If you are using Java 8 or beyond you can try:</p>

```<code>public String duplicate(int[] numbers) {
    Map<Integer, Integer> hs = new HashMap<>();
    for ( int i : numbers ) {
        hs.merge( i, 1, Integer::sum);
    }
    return '[' +
             hs.entrySet()
               .stream()
               .filter( e -> e.getValue() > 1 )
               .map(Entry::getKey)
               .sorted()
               .map(i -> i.toString())
               .collect(Collectors.joining(", ")) +
           ']';
}
</code>```

Title: Problem finding duplicate numbers in array, is my technique bad?

Body:
If you are using Java 8 or beyond you can try:

public String duplicate(int[] numbers) {
    Map<Integer, Integer> hs = new HashMap<>();
    for ( int i : numbers ) {
        hs.merge( i, 1, Integer::sum);
    }
    return '[' +
             hs.entrySet()
               .stream()
               .filter( e -> e.getValue() > 1 )
               .map(Entry::getKey)
               .sorted()
               .map(i -> i.toString())
               .collect(Collectors.joining(", ")) +
           ']';
}


问:
Error creating universal sentence encoder embeddings using beam & tf transform
I have a simple beam pipline that takes some text and gets embeddings using universal sentence encoder with tf transform. Very similar to the demo made using tf 1.

import tensorflow as tf
import apache_beam as beam
import tensorflow_transform.beam as tft_beam
import tensorflow_transform.coders as tft_coders
from apache_beam.options.pipeline_options import PipelineOptions
import tempfile

model = None

def embed_text(text):
    import tensorflow_hub as hub
    global model
    if model is None:
        model = hub.load(
            'https://tfhub.dev/google/universal-sentence-encoder/4')
    embedding = model(text)
    return embedding

def get_metadata():
    from tensorflow_transform.tf_metadata import dataset_schema
    from tensorflow_transform.tf_metadata import dataset_metadata

    metadata = dataset_metadata.DatasetMetadata(dataset_schema.Schema({
        'id': dataset_schema.ColumnSchema(
            tf.string, [], dataset_schema.FixedColumnRepresentation()),
        'text': dataset_schema.ColumnSchema(
            tf.string, [], dataset_schema.FixedColumnRepresentation())
    }))
    return metadata

def preprocess_fn(input_features):

    text_integerized = embed_text(input_features['text'])
    output_features = {
        'id': input_features['id'],
        'embedding': text_integerized
    }
    return output_features

def run(pipeline_options, known_args):
    argv = None  # if None, uses sys.argv
    pipeline_options = PipelineOptions(argv)

    pipeline = beam.Pipeline(options=pipeline_options)
    with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
        articles = (
                pipeline
                | beam.Create([
            {'id':'01','text':'To be, or not to be: that is the question: '},
            {'id':'02','text':"Whether 'tis nobler in the mind to suffer "},
            {'id':'03','text':'The slings and arrows of outrageous fortune, '},
            {'id':'04','text':'Or to take arms against a sea of troubles, '},
        ]))

        articles_dataset = (articles, get_metadata())

        transformed_dataset, transform_fn = (
                articles_dataset
                | 'Extract embeddings' >> tft_beam.AnalyzeAndTransformDataset(preprocess_fn)
        )

        transformed_data, transformed_metadata = transformed_dataset

        _ = (
            transformed_data | 'Write embeddings to TFRecords' >> beam.io.tfrecordio.WriteToTFRecord(
            file_path_prefix='{0}'.format(known_args.output_dir),
            file_name_suffix='.tfrecords',
            coder=tft_coders.example_proto_coder.ExampleProtoCoder(
                transformed_metadata.schema),
            num_shards=1
            )
    )
    result = pipeline.run()
    result.wait_until_finished()
```

<p>python 3.6.8, tf==2.0, tf_transform==0.15, apache-beam[gcp]==0.16 (I tried various compatible combos from https://github.com/tensorflow/transform)</p>

<p>I am getting an error when tf_transform calls the graph analyser:</p>

```...
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 462, in process
    lambda: self._make_graph_state(saved_model_dir))
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 221, in acquire
    return _shared_map.acquire(self._key, constructor_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 184, in acquire
    result = control_block.acquire(constructor_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 87, in acquire
    result = constructor_fn()
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 462, in <lambda>
    lambda: self._make_graph_state(saved_model_dir))
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 438, in _make_graph_state
    self._exclude_outputs, self._tf_config)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 357, in __init__
    tensor_inputs = graph_tools.get_dependent_inputs(graph, inputs, fetches)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 686, in get_dependent_inputs
    sink_tensors_ready)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 499, in __init__
    table_init_op, graph_analyzer_for_table_init, translate_path_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 560, in _get_table_init_op_source_info
    if table_init_op.type not in _TABLE_INIT_OP_TYPES:
AttributeError: 'Tensor' object has no attribute 'type' [while running 'Extract embeddings/TransformDataset/Transform']
Exception ignored in: <bound method CapturableResourceDeleter.__del__ of <tensorflow.python.training.tracking.tracking.CapturableResourceDeleter object at 0x14152fbe0>>
Traceback (most recent call last):
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_core/python/training/tracking/tracking.py", line 190, in __del__
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py", line 3872, in as_default
  File "/Users/justingrace/.pyenv/versions/3.6.8/lib/python3.6/contextlib.py", line 159, in helper
TypeError: 'NoneType' object is not callable
```

<p>It appears like the graph analyser is expecting a list of operations with a type attribute but it is receiving a tensor. I can't grasp why this error is occuring other than a bug in the graph analyzer or a compatibility issue with tfx_bsl (there seem to be issues with pyarrow 0.14 so I have downgraded to 0.13)</p>

<p>Output of pip freeze:</p>

```absl-py==0.8.1
annoy==1.12.0
apache-beam==2.16.0
appnope==0.1.0
astor==0.8.1
astunparse==1.6.3
attrs==19.1.0
avro-python3==1.9.1
backcall==0.1.0
bleach==3.1.0
cachetools==3.1.1
certifi==2019.11.28
chardet==3.0.4
crcmod==1.7
cymem==1.31.2
cytoolz==0.9.0.1
decorator==4.4.1
defusedxml==0.6.0
dill==0.3.0
docopt==0.6.2
en-core-web-lg==2.0.0
en-coref-lg==3.0.0
en-ner-trained==2.0.0
entrypoints==0.3
fastavro==0.21.24
fasteners==0.15
flashtext==2.7
future==0.18.2
fuzzywuzzy==0.16.0
gast==0.2.2
google-api-core==1.16.0
google-apitools==0.5.28
google-auth==1.11.0
google-auth-oauthlib==0.4.1
google-cloud-bigquery==1.17.1
google-cloud-bigtable==1.0.0
google-cloud-core==1.3.0
google-cloud-datastore==1.7.4
google-cloud-pubsub==1.0.2
google-pasta==0.1.8
google-resumable-media==0.4.1
googleapis-common-protos==1.51.0
grpc-google-iam-v1==0.12.3
grpcio==1.24.0
h5py==2.10.0
hdfs==2.5.8
httplib2==0.12.0
idna==2.8
importlib-metadata==1.5.0
ipykernel==5.1.4
ipython==7.12.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.16.0
Jinja2==2.11.1
jsonpickle==1.2
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==5.3.4
jupyter-console==6.1.0
jupyter-core==4.6.2
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.0
lxml==4.2.1
Markdown==3.2.1
MarkupSafe==1.1.1
mistune==0.8.4
mock==2.0.0
monotonic==1.5
more-itertools==8.2.0
msgpack==0.6.2
msgpack-numpy==0.4.4
murmurhash==0.28.0
nbconvert==5.6.1
nbformat==5.0.4
networkx==2.1
nltk==3.4.5
notebook==6.0.3
numpy==1.18.1
oauth2client==3.0.0
oauthlib==3.1.0
opt-einsum==3.1.0
packaging==20.1
pandas==0.23.0
pandocfilters==1.4.2
parso==0.6.1
pathlib2==2.3.5
pbr==5.4.4
pexpect==4.8.0
pickleshare==0.7.5
plac==0.9.6
pluggy==0.13.1
preshed==1.0.1
prometheus-client==0.7.1
prompt-toolkit==3.0.3
proto-google-cloud-datastore-v1==0.90.4
protobuf==3.11.3
psutil==5.6.7
ptyprocess==0.6.0
py==1.8.1
pyahocorasick==1.4.0
pyarrow==0.13.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pydot==1.4.1
Pygments==2.5.2
PyHamcrest==1.9.0
pymongo==3.10.1
pyparsing==2.4.6
pyrsistent==0.15.7
pytest==5.3.5
python-dateutil==2.8.0
python-Levenshtein==0.12.0
pytz==2019.3
PyYAML==3.13
pyzmq==18.1.1
qtconsole==4.6.0
regex==2017.4.5
repoze.lru==0.7
requests==2.22.0
requests-oauthlib==1.3.0
rsa==4.0
scikit-learn==0.19.1
scipy==1.4.1
Send2Trash==1.5.0
six==1.14.0
spacy==2.0.12
tb-nightly==2.2.0a20200217
tensorboard==2.0.2
tensorflow==2.0.0
tensorflow-estimator==2.0.1
tensorflow-hub==0.6.0
tensorflow-metadata==0.15.2
tensorflow-serving-api==2.1.0
tensorflow-transform==0.15.0
termcolor==1.1.0
terminado==0.8.3
testpath==0.4.4
textblob==0.15.1
tf-estimator-nightly==2.1.0.dev2020012309
tf-nightly==2.2.0.dev20200217
tfx-bsl==0.15.0
thinc==6.10.3
toolz==0.10.0
tornado==6.0.3
tqdm==4.23.3
traitlets==4.3.3
typing==3.7.4.1
typing-extensions==3.7.4.1
ujson==1.35
Unidecode==1.0.22
urllib3==1.25.8
wcwidth==0.1.8
webencodings==0.5.1
Werkzeug==1.0.0
Whoosh==2.7.4
widgetsnbextension==3.5.1
wrapt==1.11.2
zipp==2.2.0
```

答: This could be an underlying issue according to this github post. Try using an updated version of tensorflow (2.1.0), or maybe even an updated version of your keras packages.</p>

Body:
I have a simple beam pipline that takes some text and gets embeddings using universal sentence encoder with tf transform. Very similar to the demo made using tf 1.

import tensorflow as tf
import apache_beam as beam
import tensorflow_transform.beam as tft_beam
import tensorflow_transform.coders as tft_coders
from apache_beam.options.pipeline_options import PipelineOptions
import tempfile

model = None

def embed_text(text):
    import tensorflow_hub as hub
    global model
    if model is None:
        model = hub.load(
            'https://tfhub.dev/google/universal-sentence-encoder/4')
    embedding = model(text)
    return embedding

def get_metadata():
    from tensorflow_transform.tf_metadata import dataset_schema
    from tensorflow_transform.tf_metadata import dataset_metadata

    metadata = dataset_metadata.DatasetMetadata(dataset_schema.Schema({
        'id': dataset_schema.ColumnSchema(
            tf.string, [], dataset_schema.FixedColumnRepresentation()),
        'text': dataset_schema.ColumnSchema(
            tf.string, [], dataset_schema.FixedColumnRepresentation())
    }))
    return metadata

def preprocess_fn(input_features):

    text_integerized = embed_text(input_features['text'])
    output_features = {
        'id': input_features['id'],
        'embedding': text_integerized
    }
    return output_features

def run(pipeline_options, known_args):
    argv = None  # if None, uses sys.argv
    pipeline_options = PipelineOptions(argv)

    pipeline = beam.Pipeline(options=pipeline_options)
    with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
        articles = (
                pipeline
                | beam.Create([
            {'id':'01','text':'To be, or not to be: that is the question: '},
            {'id':'02','text':"Whether 'tis nobler in the mind to suffer "},
            {'id':'03','text':'The slings and arrows of outrageous fortune, '},
            {'id':'04','text':'Or to take arms against a sea of troubles, '},
        ]))

        articles_dataset = (articles, get_metadata())

        transformed_dataset, transform_fn = (
                articles_dataset
                | 'Extract embeddings' >> tft_beam.AnalyzeAndTransformDataset(preprocess_fn)
        )

        transformed_data, transformed_metadata = transformed_dataset

        _ = (
            transformed_data | 'Write embeddings to TFRecords' >> beam.io.tfrecordio.WriteToTFRecord(
            file_path_prefix='{0}'.format(known_args.output_dir),
            file_name_suffix='.tfrecords',
            coder=tft_coders.example_proto_coder.ExampleProtoCoder(
                transformed_metadata.schema),
            num_shards=1
            )
    )
    result = pipeline.run()
    result.wait_until_finished()

python 3.6.8, tf==2.0, tf_transform==0.15, apache-beam[gcp]==0.16 (I tried various compatible combos from https://github.com/tensorflow/transform)

I am getting an error when tf_transform calls the graph analyser:

...
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 462, in process
    lambda: self._make_graph_state(saved_model_dir))
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 221, in acquire
    return _shared_map.acquire(self._key, constructor_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 184, in acquire
    result = control_block.acquire(constructor_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tfx_bsl/beam/shared.py", line 87, in acquire
    result = constructor_fn()
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 462, in <lambda>
    lambda: self._make_graph_state(saved_model_dir))
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 438, in _make_graph_state
    self._exclude_outputs, self._tf_config)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/beam/impl.py", line 357, in __init__
    tensor_inputs = graph_tools.get_dependent_inputs(graph, inputs, fetches)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 686, in get_dependent_inputs
    sink_tensors_ready)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 499, in __init__
    table_init_op, graph_analyzer_for_table_init, translate_path_fn)
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_transform/graph_tools.py", line 560, in _get_table_init_op_source_info
    if table_init_op.type not in _TABLE_INIT_OP_TYPES:
AttributeError: 'Tensor' object has no attribute 'type' [while running 'Extract embeddings/TransformDataset/Transform']
Exception ignored in: <bound method CapturableResourceDeleter.__del__ of <tensorflow.python.training.tracking.tracking.CapturableResourceDeleter object at 0x14152fbe0>>
Traceback (most recent call last):
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_core/python/training/tracking/tracking.py", line 190, in __del__
  File "/Users/justingrace/.pyenv/versions/hlx36/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py", line 3872, in as_default
  File "/Users/justingrace/.pyenv/versions/3.6.8/lib/python3.6/contextlib.py", line 159, in helper
TypeError: 'NoneType' object is not callable

It appears like the graph analyser is expecting a list of operations with a type attribute but it is receiving a tensor. I can't grasp why this error is occuring other than a bug in the graph analyzer or a compatibility issue with tfx_bsl (there seem to be issues with pyarrow 0.14 so I have downgraded to 0.13)

Output of pip freeze:

absl-py==0.8.1
annoy==1.12.0
apache-beam==2.16.0
appnope==0.1.0
astor==0.8.1
astunparse==1.6.3
attrs==19.1.0
avro-python3==1.9.1
backcall==0.1.0
bleach==3.1.0
cachetools==3.1.1
certifi==2019.11.28
chardet==3.0.4
crcmod==1.7
cymem==1.31.2
cytoolz==0.9.0.1
decorator==4.4.1
defusedxml==0.6.0
dill==0.3.0
docopt==0.6.2
en-core-web-lg==2.0.0
en-coref-lg==3.0.0
en-ner-trained==2.0.0
entrypoints==0.3
fastavro==0.21.24
fasteners==0.15
flashtext==2.7
future==0.18.2
fuzzywuzzy==0.16.0
gast==0.2.2
google-api-core==1.16.0
google-apitools==0.5.28
google-auth==1.11.0
google-auth-oauthlib==0.4.1
google-cloud-bigquery==1.17.1
google-cloud-bigtable==1.0.0
google-cloud-core==1.3.0
google-cloud-datastore==1.7.4
google-cloud-pubsub==1.0.2
google-pasta==0.1.8
google-resumable-media==0.4.1
googleapis-common-protos==1.51.0
grpc-google-iam-v1==0.12.3
grpcio==1.24.0
h5py==2.10.0
hdfs==2.5.8
httplib2==0.12.0
idna==2.8
importlib-metadata==1.5.0
ipykernel==5.1.4
ipython==7.12.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
jedi==0.16.0
Jinja2==2.11.1
jsonpickle==1.2
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==5.3.4
jupyter-console==6.1.0
jupyter-core==4.6.2
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.0
lxml==4.2.1
Markdown==3.2.1
MarkupSafe==1.1.1
mistune==0.8.4
mock==2.0.0
monotonic==1.5
more-itertools==8.2.0
msgpack==0.6.2
msgpack-numpy==0.4.4
murmurhash==0.28.0
nbconvert==5.6.1
nbformat==5.0.4
networkx==2.1
nltk==3.4.5
notebook==6.0.3
numpy==1.18.1
oauth2client==3.0.0
oauthlib==3.1.0
opt-einsum==3.1.0
packaging==20.1
pandas==0.23.0
pandocfilters==1.4.2
parso==0.6.1
pathlib2==2.3.5
pbr==5.4.4
pexpect==4.8.0
pickleshare==0.7.5
plac==0.9.6
pluggy==0.13.1
preshed==1.0.1
prometheus-client==0.7.1
prompt-toolkit==3.0.3
proto-google-cloud-datastore-v1==0.90.4
protobuf==3.11.3
psutil==5.6.7
ptyprocess==0.6.0
py==1.8.1
pyahocorasick==1.4.0
pyarrow==0.13.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pydot==1.4.1
Pygments==2.5.2
PyHamcrest==1.9.0
pymongo==3.10.1
pyparsing==2.4.6
pyrsistent==0.15.7
pytest==5.3.5
python-dateutil==2.8.0
python-Levenshtein==0.12.0
pytz==2019.3
PyYAML==3.13
pyzmq==18.1.1
qtconsole==4.6.0
regex==2017.4.5
repoze.lru==0.7
requests==2.22.0
requests-oauthlib==1.3.0
rsa==4.0
scikit-learn==0.19.1
scipy==1.4.1
Send2Trash==1.5.0
six==1.14.0
spacy==2.0.12
tb-nightly==2.2.0a20200217
tensorboard==2.0.2
tensorflow==2.0.0
tensorflow-estimator==2.0.1
tensorflow-hub==0.6.0
tensorflow-metadata==0.15.2
tensorflow-serving-api==2.1.0
tensorflow-transform==0.15.0
termcolor==1.1.0
terminado==0.8.3
testpath==0.4.4
textblob==0.15.1
tf-estimator-nightly==2.1.0.dev2020012309
tf-nightly==2.2.0.dev20200217
tfx-bsl==0.15.0
thinc==6.10.3
toolz==0.10.0
tornado==6.0.3
tqdm==4.23.3
traitlets==4.3.3
typing==3.7.4.1
typing-extensions==3.7.4.1
ujson==1.35
Unidecode==1.0.22
urllib3==1.25.8
wcwidth==0.1.8
webencodings==0.5.1
Werkzeug==1.0.0
Whoosh==2.7.4
widgetsnbextension==3.5.1
wrapt==1.11.2
zipp==2.2.0


问:
Create a WCF Proxy for a Rest Web Service
I have a complex WCF Rest service which take multiple inputs and objects. I cannot simply call it by doing an HTTP POST in Fiddler because there is too much data to provide (I could, but it will take me forever). So I would like to do it in code using a proxy. Is there a way to generate a proxy for a .NET 4 WCF Rest Service? Otherwise, what do you propose to allow me to easily test the service?

Thanks.

答: Though there is currently no standard way to create a proxy with a WCF REST service, you can do this with the "Paste XML as Types" tool in the REST Starter kit. This works off the xml shown in the default WCF /help page and produces a C# class which matches the structure and can be used. Also, check out this video to see it in action - Consumer Twitter in 3 minutes.</p>

ContentLicense: CC BY-SA 3.0


问:
nodejs restify with nginx reverse proxy could not get session works
so a little background first: I use restify framework for my nodejs api server, and I use react for client to interact with the server. I setup both projects in one VPS with nginx reverse proxy to take care with two different domain name: example_server.com,example_client.com and both https enabled with letsEncrypted.

so when I visite example_server.com, my nginx take me to localhost:server_port and show the correct content, the client works the same way.

Here is my problem:

my react client connected to restify server could not get session work, the server not able to setup any session for the client. it maybe related to nginx reverse proxy problem, someone use express framework for server has the same issue, but got fixed using app.set('trust proxy', 1). but in restify, there is no such option. I really don't want to change my code from restify to express, so What can I do?

my server nginx setup:

```<code>server {
    server_name server_example.com www.server_example.com;
    location / {
        proxy_pass http://127.0.0.1:6000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
}
</code>```

my client nginx setup:

```<code>server {
    server_name client_example.com www.client_example.com;
    location / {
        proxy_pass http://127.0.0.1:7000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
}
</code>```

I use express-session for handling session in my restify server, in local development it works well, but in VPS server with nginx, it is not working. here is the code Snippet:

```<code>var constant = require('./config/constant.json');
var session = require('express-session');

var restify = require('restify');

var corsMiddleware = require("restify-cors-middleware");
const cors = corsMiddleware({
  origins: constant.client_urls,
  credentials: true,
  allowHeaders: ["Authorization"],
  exposeHeaders: ["Authorization"]
});

var server = restify.createServer();
server.use(restify.plugins.queryParser());
server.use(restify.plugins.jsonp());
server.pre(restify.plugins.pre.userAgentConnection());

server.pre(cors.preflight);
server.use(cors.actual);

//server.set('trust proxy', 1);  restify didn't has such option, err: .set is not a function.
server.use(session({
  secret: constant.session_secret,
  proxy: true,
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 3600000, secure: true },
}))
</code>```

any help will be appreciate!

答:
turns out the problem is causing by the two different domains.

React client www.myReactClient.com is able to connect to Restify API server www.myRestifyServer.com with CORS enabled, then server will generate a session, keep it to itself while sent only session-id to client side with cookie.

the React client should carry that cookie and send session-id back to server whenever it makes request to, so that server will recognize this client.

However, due to using two different domains, the cookie was consider as 'third party cookie', and browser block that kind of cookie by default, so the cookie remains there but never got used, so the server won't receive the session-id.

so, Long story in short, after I change the browser setting to NOT block third party cookies, everything works as planned. Then I change my two different domains to one domains with one subdomains, www.myReactClient.com for hosting React Client, api.myReactClient.com for hosting Restify API server, the third party cookie issue be solved as well.

Body:
so a little background first: I use restify framework for my nodejs api server, and I use react for client to interact with the server. I setup both projects in one VPS with nginx reverse proxy to take care with two different domain name: example_server.com,example_client.com and both https enabled with letsEncrypted.

so when I visite example_server.com, my nginx take me to localhost:server_port and show the correct content, the client works the same way.

Here is my problem:

my react client connected to restify server could not get session work, the server not able to setup any session for the client. it maybe related to nginx reverse proxy problem, someone use express framework for server has the same issue, but got fixed using app.set('trust proxy', 1). but in restify, there is no such option. I really don't want to change my code from restify to express, so What can I do?

my server nginx setup:

server {
    server_name server_example.com www.server_example.com;
    location / {
        proxy_pass http://127.0.0.1:6000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
}

my client nginx setup:

server {
    server_name client_example.com www.client_example.com;
    location / {
        proxy_pass http://127.0.0.1:7000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
}

I use express-session for handling session in my restify server, in local development it works well, but in VPS server with nginx, it is not working. here is the code Snippet:

var constant = require('./config/constant.json');
var session = require('express-session');

var restify = require('restify');

var corsMiddleware = require("restify-cors-middleware");
const cors = corsMiddleware({
  origins: constant.client_urls,
  credentials: true,
  allowHeaders: ["Authorization"],
  exposeHeaders: ["Authorization"]
});

var server = restify.createServer();
server.use(restify.plugins.queryParser());
server.use(restify.plugins.jsonp());
server.pre(restify.plugins.pre.userAgentConnection());

server.pre(cors.preflight);
server.use(cors.actual);

//server.set('trust proxy', 1);  restify didn't has such option, err: .set is not a function.
server.use(session({
  secret: constant.session_secret,
  proxy: true,
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 3600000, secure: true },
}))

any help will be appreciate!


问:
Azure Pipelines: Dotnet publish fails with exit code 1 after migrating to .NET Core 3.1
I have an Azure Pipeline which is setup to do:

Use .NET Core SDK 3.1.x

Dotnet restore

Dotnet Build

Dotnet Publish

Use .NET Core task looks like that and it run before all others mentioned above:

All the jobs are executed successfully apart the Dotnet Publish

This job crashes with these errors:

AND

[error]Error: The process 'C:\hostedtoolcache\windows\dotnet\dotnet.exe' failed with exit code 1

[warning]Info: Azure Pipelines hosted agents have been updated to contain .Net Core 3.x SDK/Runtime along with 2.2 & 2.1. Unless you have locked down a SDK version for your project(s), 3.x SDK might be picked up which might have breaking behavior as compared to previous versions.

I tried different version variation for Use .NET Core SDK Job, however all of them lead to the same error.

Publish job:

Thanks in advance. Appreciate if someone could give me a clue what I might be doing wrong.

答:
This is what I do to install a specific version of dotnet core:

```<code>- task: UseDotNet@2
  inputs:
    packageType: 'sdk'
    version: '3.1.101'
</code>```

I the only difference I found you have to specify the SDK version exactly of the SDK build.

Body:
This is what I do to install a specific version of dotnet core:

- task: UseDotNet@2
  inputs:
    packageType: 'sdk'
    version: '3.1.101'

I the only difference I found you have to specify the SDK version exactly of the SDK build.


问:
Tunnel data-variables through env-variable with "{{" operator
Following the example from https://www.tidyverse.org/blog/2020/02/glue-strings-and-tidy-eval/

How do you pass variables into this function?

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

mean_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}

mean_by(mtcars, by = cyl, var = mpg, prefix = "avg")
#> # A tibble: 3 x 2
#>     cyl avg_mpg
#>   <dbl>   <dbl>
#> 1     4    26.7
#> 2     6    19.7
#> 3     8    15.1

# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg")

# How do you pass a variables into this function?
purrr::map(params, mean_by(mtcars, by = .x, var = mpg, prefix = "avg"))
#> Error: Column `.x` is unknown
```

Created on 2020-02-19 by the reprex package (v0.3.0)

答:
We could use ensym as the params passed are strings.  So, either convert to symbol with ensym

```<code>library(dplyr)
library(purrr)
library(stringr)
mean_by <- function(data, by, var, prefix = "avg") {

 by <- rlang::ensym(by)
 var <- rlang::ensym(var)
 data %>%
    group_by(!! by) %>%
    summarise(!!str_c(prefix, var, sep="_")  := mean(!!var, na.rm = TRUE))
  }

mean_by(mtcars, by = cyl, var = "mpg", prefix = "avg")
# A tibble: 3 x 2
#    cyl avg_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

map(params, ~mean_by(mtcars, by = !!.x, var = "mpg", prefix = "avg"))
#[[1]]
# A tibble: 3 x 2
#    cyl avg_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

#[[2]]
# A tibble: 27 x 2
#    disp avg_mpg
#   <dbl>   <dbl>
# 1  71.1    33.9
# 2  75.7    30.4
# 3  78.7    32.4
# 4  79      27.3
# 5  95.1    30.4
# 6 108      22.8
# ...
</code>```

Body:
Following the example from https://www.tidyverse.org/blog/2020/02/glue-strings-and-tidy-eval/

How do you pass variables into this function?

library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.2
#> Warning: package 'tidyr' was built under R version 3.6.2

mean_by <- function(data, by, var, prefix = "avg") {
  data %>%
    group_by({{ by }}) %>%
    summarise("{prefix}_{{ var }}" := mean({{ var }}, na.rm = TRUE))
}

mean_by(mtcars, by = cyl, var = mpg, prefix = "avg")
#> # A tibble: 3 x 2
#>     cyl avg_mpg
#>   <dbl>   <dbl>
#> 1     4    26.7
#> 2     6    19.7
#> 3     8    15.1

# Variables to pass into function
params <-  setdiff(colnames(mtcars) ,"mpg")

# How do you pass a variables into this function?
purrr::map(params, mean_by(mtcars, by = .x, var = mpg, prefix = "avg"))
#> Error: Column `.x` is unknown

Created on 2020-02-19 by the reprex package (v0.3.0)

Body:
We could use ensym as the params passed are strings.  So, either convert to symbol with ensym

library(dplyr)
library(purrr)
library(stringr)
mean_by <- function(data, by, var, prefix = "avg") {

 by <- rlang::ensym(by)
 var <- rlang::ensym(var)
 data %>%
    group_by(!! by) %>%
    summarise(!!str_c(prefix, var, sep="_")  := mean(!!var, na.rm = TRUE))
  }

mean_by(mtcars, by = cyl, var = "mpg", prefix = "avg")
# A tibble: 3 x 2
#    cyl avg_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

map(params, ~mean_by(mtcars, by = !!.x, var = "mpg", prefix = "avg"))
#[[1]]
# A tibble: 3 x 2
#    cyl avg_mpg
#  <dbl>   <dbl>
#1     4    26.7
#2     6    19.7
#3     8    15.1

#[[2]]
# A tibble: 27 x 2
#    disp avg_mpg
#   <dbl>   <dbl>
# 1  71.1    33.9
# 2  75.7    30.4
# 3  78.7    32.4
# 4  79      27.3
# 5  95.1    30.4
# 6 108      22.8
# ...


问:
how to use @Table annotation of class org.hibernate.annotations.Table in hibernate
My class name is

BatchJob

My table name is

batch_jobs

I am using @Table of the class org.hibernate.annotations.Table instead of javax.persistence

My code of the class BatchJob is

```<code>import javax.persistence.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo="batch_jobs")
public class BatchJob {
</code>```

I am getting error

org.hibernate.AnnotationException: @org.hibernate.annotations.Table
  references an unknown table: batch_jobs

when I changed the class of the @Entity notation to org.hibernate.annotations

```<code>import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo="batch_jobs")
public class BatchJob {
</code>```

I am getting error

org.hibernate.hql.internal.ast.QuerySyntaxException: BatchJob is not
  mapped [From BatchJob]

My query

```<code>allBatchJobs=session.createQuery("From BatchJob").list();
</code>```

My hibernate.cfg.xml mapping

```<code><mapping class="com.company.bmdashboard.beans.BatchJob"></mapping>
</code>```

When I am changing my class name to batch_jobs the code is working fine, but I want to use the name BatchJob and I dont want to use javax.persistence class.

Please guide me. Thanks in advance

答:
@org.hibernate.annotations.Table use value from javax.persistence.Table; and/or from javax.persistence.SecondaryTables;. For an example:

```<code>@Table(name = "batch_jobs")
@SecondaryTables({
        @SecondaryTable(name="batch")
})
@Entity
@org.hibernate.annotations.Table(inverse = true, appliesTo = "batch")
public class BatchJob {
</code>```

So, @org.hibernate.annotations.Table is not equal to javax.persistence.Table;, this is different annotations with different purpose.

Body:
My class name is

BatchJob

My table name is

batch_jobs

I am using @Table of the class org.hibernate.annotations.Table instead of javax.persistence

My code of the class BatchJob is

import javax.persistence.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo="batch_jobs")
public class BatchJob {

I am getting error

org.hibernate.AnnotationException: @org.hibernate.annotations.Table
  references an unknown table: batch_jobs

when I changed the class of the @Entity notation to org.hibernate.annotations

import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo="batch_jobs")
public class BatchJob {

I am getting error

org.hibernate.hql.internal.ast.QuerySyntaxException: BatchJob is not
  mapped [From BatchJob]

My query

allBatchJobs=session.createQuery("From BatchJob").list();

My hibernate.cfg.xml mapping

<mapping class="com.company.bmdashboard.beans.BatchJob"></mapping>

When I am changing my class name to batch_jobs the code is working fine, but I want to use the name BatchJob and I dont want to use javax.persistence class.

Please guide me. Thanks in advance

Body:
@org.hibernate.annotations.Table use value from javax.persistence.Table; and/or from javax.persistence.SecondaryTables;. For an example:

@Table(name = "batch_jobs")
@SecondaryTables({
        @SecondaryTable(name="batch")
})
@Entity
@org.hibernate.annotations.Table(inverse = true, appliesTo = "batch")
public class BatchJob {

So, @org.hibernate.annotations.Table is not equal to javax.persistence.Table;, this is different annotations with different purpose.


问:
Prevent OptionsMenu from closing when clicking on checkbox
I wanna show checkbox on top of the screen to allow the user to enable screenLock and I want to show that checkbox only if he opens the optionsMenu.
I am able to do this by overridinbg these 2 methods

```<code>@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    checkbox.setVisibility(View.VISIBLE);
    return super.onMenuOpened(featureId, menu);
}
@Override
public void onOptionsMenuClosed(Menu menu) {
    checkbox.setVisibility(View.GONE);
    super.onOptionsMenuClosed(menu);
}
</code>```

However when I touch the checkbox, in order to check it, the menu closes itself and the checkbox disappears before I can check it.

So my question si simple: How can I prevent the options menu from closing when I touch the checkbox?

答:
The Android stock browser shows a TitleBar you can click while the menu is open. So their solution should fit your problem as well.

The TitleBar is shown using WindowManager:

```<code>WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

// Add the title bar to the window manager so it can receive touches
// while the menu is up
WindowManager.LayoutParams params
        = new WindowManager.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP;
manager.addView(mFakeTitleBar, params);
</code>```

To remove it (when menu is closed, or user clicks it)

```<code>manager.removeView(mFakeTitleBar);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wanna show checkbox on top of the screen to allow the user to enable screenLock and I want to show that checkbox only if he opens the optionsMenu.
I am able to do this by overridinbg these 2 methods

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    checkbox.setVisibility(View.VISIBLE);
    return super.onMenuOpened(featureId, menu);
}
@Override
public void onOptionsMenuClosed(Menu menu) {
    checkbox.setVisibility(View.GONE);
    super.onOptionsMenuClosed(menu);
}

However when I touch the checkbox, in order to check it, the menu closes itself and the checkbox disappears before I can check it.

So my question si simple: How can I prevent the options menu from closing when I touch the checkbox?

Body:
The Android stock browser shows a TitleBar you can click while the menu is open. So their solution should fit your problem as well.

The TitleBar is shown using WindowManager:

WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

// Add the title bar to the window manager so it can receive touches
// while the menu is up
WindowManager.LayoutParams params
        = new WindowManager.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP;
manager.addView(mFakeTitleBar, params);

To remove it (when menu is closed, or user clicks it)

manager.removeView(mFakeTitleBar);


问:
How fire EXCEL event BeforeDoubleClick BEFORE SelectionChange?
I want to fire the BeforeDoubleClick-event BEFORE the SelectionChange-event for an EXCEL work-sheet.

The order is normally the other way round: SelectionChange-event first, and later BeforeDoubleClick-event.

My goal is to either run MyDoubleClickCode, if there a double-click, or if NOT, run MyChangeSelectionCode.

The problem relies in the order of event-triggering!

My best solution comes here:

```<code>    ' This Event is **MAYBE** fired secondly and runs the MyDoubleClickCode
    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
        dblFlag = true
        ...
        MyDoubleClickCode
        ...
    End Sub

    ' This event is always fired AND runs first
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        dblFlag = false
        alertTime = Now + TimeValue("00:00:01")
        Application.OnTime alertTime, "MyChangeSelectionSub"
    End Sub

    ' Userdefined subroutine which will run one second after an event ( doubleclick or not).
    public sub MyChangeSelectionSub()
        If NOT dblFlag then
            ...
            MyChangeSelectionCode
            ...
        End if
    End Sub
</code>```

I use OnTime in my SelectionChange-event to call the MyChangeSelectionSub  one second after a selection-change is triggered. This gives times to handle an  BeforeDoubleClick-event and do the MyDoubleClickCode - if the cell was also double-clicked. My wanted logic is reached , BUT...

... it is of course very clumpsy and not satisfying: I have to wait one second before the MyChangeSelectionSub starts, instead of just after the BeforeDoubleClick-event has been dealed with.

Maybee there is a kind of logic to make this happend? Any idea?

EDIT: I've edited the code-exampel to be more clear about my problem! And I know now that I can't change the order of events, but how to not use the onTime solution??

答:
This "works" for me, but it doesn't seem stable.  Probably the timing of the OnTime method causes an "uncomfortable pause" in execution that we might need to accept.  (or improve upon.)</p>

```<code>'worksheet (Name) is "Sheet17" in the VBA Properties window
'worksheet Name is "Sheet1" as shown in the worksheet tab in the application Excel

Private double_click_detected As Boolean
Private SelectionChange_target As Range

' This Event is **MAYBE** fired secondly and runs the MyDoubleClickCode
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  double_click_detected = True
  '...
  MsgBox "MyDoubleClickCode"
  '...
End Sub

' This event is always fired AND runs first
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Set SelectionChange_target = Target
    alertTime = Now + TimeValue("00:00:01")
    Application.OnTime alertTime, "Sheet17.MyChangeSelectionSub"
End Sub

' Userdefined subroutine which will run one second after an event ( doubleclick or not).
Public Sub MyChangeSelectionSub()
  If Not double_click_detected Then
    '...
    MsgBox "MyChangeSelectionCode"
    '...
  End If
End Sub
</code>```

Body:
I want to fire the BeforeDoubleClick-event BEFORE the SelectionChange-event for an EXCEL work-sheet.

The order is normally the other way round: SelectionChange-event first, and later BeforeDoubleClick-event.

My goal is to either run MyDoubleClickCode, if there a double-click, or if NOT, run MyChangeSelectionCode.

The problem relies in the order of event-triggering!

My best solution comes here:

    ' This Event is **MAYBE** fired secondly and runs the MyDoubleClickCode
    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
        dblFlag = true
        ...
        MyDoubleClickCode
        ...
    End Sub

    ' This event is always fired AND runs first
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        dblFlag = false
        alertTime = Now + TimeValue("00:00:01")
        Application.OnTime alertTime, "MyChangeSelectionSub"
    End Sub

    ' Userdefined subroutine which will run one second after an event ( doubleclick or not).
    public sub MyChangeSelectionSub()
        If NOT dblFlag then
            ...
            MyChangeSelectionCode
            ...
        End if
    End Sub

I use OnTime in my SelectionChange-event to call the MyChangeSelectionSub  one second after a selection-change is triggered. This gives times to handle an  BeforeDoubleClick-event and do the MyDoubleClickCode - if the cell was also double-clicked. My wanted logic is reached , BUT...

... it is of course very clumpsy and not satisfying: I have to wait one second before the MyChangeSelectionSub starts, instead of just after the BeforeDoubleClick-event has been dealed with.

Maybee there is a kind of logic to make this happend? Any idea?

EDIT: I've edited the code-exampel to be more clear about my problem! And I know now that I can't change the order of events, but how to not use the onTime solution??

Body:
This "works" for me, but it doesn't seem stable.  Probably the timing of the OnTime method causes an "uncomfortable pause" in execution that we might need to accept.  (or improve upon.)

'worksheet (Name) is "Sheet17" in the VBA Properties window
'worksheet Name is "Sheet1" as shown in the worksheet tab in the application Excel

Private double_click_detected As Boolean
Private SelectionChange_target As Range

' This Event is **MAYBE** fired secondly and runs the MyDoubleClickCode
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  double_click_detected = True
  '...
  MsgBox "MyDoubleClickCode"
  '...
End Sub

' This event is always fired AND runs first
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Set SelectionChange_target = Target
    alertTime = Now + TimeValue("00:00:01")
    Application.OnTime alertTime, "Sheet17.MyChangeSelectionSub"
End Sub

' Userdefined subroutine which will run one second after an event ( doubleclick or not).
Public Sub MyChangeSelectionSub()
  If Not double_click_detected Then
    '...
    MsgBox "MyChangeSelectionCode"
    '...
  End If
End Sub


问:
firefox ondrop event.dataTransfer is null after update to version 52
Introduction:

At about mid March 2017, after an update of firefox to version 52, certain functions - drop and paste - ceaced to function properly. As it shows up on debugging, the attribute "dataTransfer" of the event is nowadays set to null.

Previously to the update, onDrop and onPaste events both delivered the dataTransfer attribut set to the contents of what were to be dropped or pasted.

Questions:

How should drop and paste be handled with actual browsers?
Are there any precautions necessary these days?
Is there an explanation out there of the reasons behind the restrictive behavior of nowadays?

Is there any example out there in the internet showing how to accomplish the task with actual browsers?

I do not ask for examples prior to version 48 of firefox, since at least until that version, the whole thing worked flawlessly. I do not ask for examples with jQuery or any other library (while not rejecting those if they come as additional supplements). I do ask for examples with simple plain native javascript.

答: With the latest version of FF (currently 73.0.1) dataTransfer appears as null only when debugging the drop event handler (that is, via breakpoint or debugger statement). Not debugging the function makes it work properly.


问:
GCE "create-with-container --container-mount-disk" flag mounts disk as read-only
I am trying to use a Percona Docker image for MongoDB on GCE, however I'm running into an issue with Mongo saying the mounted path is read-only. I looked around as much as I could, but im stumped at what could be the issue.

```<code>gcloud compute instances create-with-container mongo-svr \
--create-disk name=disk-1,size=1GB \
--container-mount-disk mount-path="/data/mongodb",mode=rw \
--container-image=docker.io/percona/percona-server-mongodb:4.2
</code>```

I used the above command and it creates my instance. I then SSH into the server, connect to the running mongo instance to shutdown, then I run: docker exec -it [NAME] mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost

This spits out an error stating:

```<code>CONTROL  [initandlisten] options: { net: { bindIp: "localhost" }, replication: { replSet: "rs0" }, sharding: { clusterRole: "configsvr" }, storage: { dbPath: "/data/mongodb" } }
STORAGE  [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /data/mongodb, terminating
</code>```

At this point, I've been recreating instances with different params, but nothing has worked so far. Anyone have an idea what I'm missing?

Updated with command output

```<code>gcloud compute instances create-with-container mongo-config-f --zone us-central1-f --create-disk name=disk-1,size=1GB --container-mount-disk mount-path="/data/mongodb" --container-image=docker.io/percona/percona-server-mongodb:4.2 --machine-type=f1-micro
WARNING: Default device-name for disk name [disk-1] will be [disk-1] because it is being mounted to a container with [`--container-mount-disk`]
Created [https://www.googleapis.com/compute/v1/projects/[PROJECT_NAME]/zones/us-central1-f/instances/mongo-config-f].
NAME            ZONE           MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
mongo-config-f  us-central1-f  f1-micro                   xx.xx.xx.xx  xx.xx.xx.xx     RUNNING
</code>```

答:
I've tried to replicate your issue on my test project and found that:

persistent disk was created and mounted in read-write mode as expected;

```<code>bash-4.2$ mount
...
/dev/sdb on /data/mongodb type ext4 (rw,relatime)
</code>```

docker runs containers inside our VM properly;

the cause of the error while running docker exec -it [NAME] mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost is permissions inside mongodb container:

```<code>bash-4.2$ ls -l /data/
...
drwxr-xr-x 3 root    root 4096 Feb 19 15:33 mongodb
</code>```

As a workaround commands could be executed with root permissions:

```<code>$ docker exec -it --user root klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --db path=/data/mongodb
</code>```

Please find more details and my steps below:

create VM:

```<code>$ gcloud compute instances create-with-container mongo-svr \
--create-disk name=disk-1,size=1GB \
--container-image docker.io/percona/percona-server-mongodb:4.2 \
--container-mount-disk mount-path="/data/mongodb"
WARNING: Default device-name for disk name [disk-1] will be [disk-1] because it is being mounted to a container with [`--container-mount-disk`]
Created [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/mongo-svr].
NAME           ZONE            MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
mongo-svr-upd  europe-west3-a  n1-standard-1               10.156.0.9   35.XXX.155.XXX  RUNNING
</code>```

SSH to instance;

check if container is running:

```<code>$ docker ps
CONTAINER ID        IMAGE                                                                COMMAND                  CREATED              STATUS              PORTS               NAMES
dfad9c10235d        percona/percona-server-mongodb:4.2                                   "/entrypoint.sh mong…"   About a minute ago   Up About a minute                       klt-mongo-svr-upd-wowt
bbe02c8e8621        gcr.io/stackdriver-agents/stackdriver-logging-agent:0.2-1.5.33-1-1   "/entrypoint.sh /usr…"   About a minute ago   Up About a minute                       stackdriver-logging-agent
</code>```

everything looks good at this point;

try to run command as user:

```<code> $ docker exec -it klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost
</code>```

and observe the same error:

```<code>2020-02-19T15:37:53.176+0000 I  STORAGE  [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /data/mongodb, terminating
</code>```

here key read-only directory: /data/mongodb;

check mounts and permissions inside of the container:

```<code>$ docker exec -it klt-mongo-svr-upd-wowt /bin/bash
bash-4.2$ mount
...
/dev/sdb on /data/mongodb type ext4 (rw,relatime)
...
</code>```

as we expected disk was created and mounted in read-write mode to the container

```<code>bash-4.2$ ls -l /data/
total 8
drwxr-xr-x 4 mongodb root 4096 Feb 19 15:36 db
drwxr-xr-x 3 root    root 4096 Feb 19 15:33 mongodb
bash-4.2$
</code>```

but to work with /data/mongodb you need root permissions;

try to run command as root:

```<code>$ docker exec -it --user root klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --dbpath=/data/mongodb
2020-02-19T15:45:24.970+0000 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-02-19T15:45:24.973+0000 I  CONTROL  [initandlisten] MongoDB starting : pid=119 port=27019 dbpath=/data/mongodb 64-bit host=mongo-svr-upd
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] db version v4.2.2-3
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] git version: 2cdb6e50913583f627acc5de35dc4e04dbfe196f
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2k-fips  26 Jan 2017
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] allocator: tcmalloc
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] modules: none
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] build environment:
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten]     distarch: x86_64
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten] options: { replication: { replSet: "rs0" }, sharding: { clusterRole: "configsvr" }, storage: { dbPath: "/data/mongodb" } }
2020-02-19T15:45:24.976+0000 I  STORAGE  [initandlisten] Detected data files in /data/mongodb created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
...
</code>```

and it's working with root permissions.

Body:
I am trying to use a Percona Docker image for MongoDB on GCE, however I'm running into an issue with Mongo saying the mounted path is read-only. I looked around as much as I could, but im stumped at what could be the issue.

gcloud compute instances create-with-container mongo-svr \
--create-disk name=disk-1,size=1GB \
--container-mount-disk mount-path="/data/mongodb",mode=rw \
--container-image=docker.io/percona/percona-server-mongodb:4.2

I used the above command and it creates my instance. I then SSH into the server, connect to the running mongo instance to shutdown, then I run: docker exec -it [NAME] mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost

This spits out an error stating:

CONTROL  [initandlisten] options: { net: { bindIp: "localhost" }, replication: { replSet: "rs0" }, sharding: { clusterRole: "configsvr" }, storage: { dbPath: "/data/mongodb" } }
STORAGE  [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /data/mongodb, terminating

At this point, I've been recreating instances with different params, but nothing has worked so far. Anyone have an idea what I'm missing?

Updated with command output

gcloud compute instances create-with-container mongo-config-f --zone us-central1-f --create-disk name=disk-1,size=1GB --container-mount-disk mount-path="/data/mongodb" --container-image=docker.io/percona/percona-server-mongodb:4.2 --machine-type=f1-micro
WARNING: Default device-name for disk name [disk-1] will be [disk-1] because it is being mounted to a container with [`--container-mount-disk`]
Created [https://www.googleapis.com/compute/v1/projects/[PROJECT_NAME]/zones/us-central1-f/instances/mongo-config-f].
NAME            ZONE           MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
mongo-config-f  us-central1-f  f1-micro                   xx.xx.xx.xx  xx.xx.xx.xx     RUNNING

Body:
I've tried to replicate your issue on my test project and found that:

persistent disk was created and mounted in read-write mode as expected;

bash-4.2$ mount
...
/dev/sdb on /data/mongodb type ext4 (rw,relatime)

docker runs containers inside our VM properly;

the cause of the error while running docker exec -it [NAME] mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost is permissions inside mongodb container:

bash-4.2$ ls -l /data/
...
drwxr-xr-x 3 root    root 4096 Feb 19 15:33 mongodb

As a workaround commands could be executed with root permissions:

$ docker exec -it --user root klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --db path=/data/mongodb

Please find more details and my steps below:

create VM:

$ gcloud compute instances create-with-container mongo-svr \
--create-disk name=disk-1,size=1GB \
--container-image docker.io/percona/percona-server-mongodb:4.2 \
--container-mount-disk mount-path="/data/mongodb"
WARNING: Default device-name for disk name [disk-1] will be [disk-1] because it is being mounted to a container with [`--container-mount-disk`]
Created [https://www.googleapis.com/compute/v1/projects/test-prj/zones/europe-west3-a/instances/mongo-svr].
NAME           ZONE            MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP     STATUS
mongo-svr-upd  europe-west3-a  n1-standard-1               10.156.0.9   35.XXX.155.XXX  RUNNING

SSH to instance;

check if container is running:

$ docker ps
CONTAINER ID        IMAGE                                                                COMMAND                  CREATED              STATUS              PORTS               NAMES
dfad9c10235d        percona/percona-server-mongodb:4.2                                   "/entrypoint.sh mong…"   About a minute ago   Up About a minute                       klt-mongo-svr-upd-wowt
bbe02c8e8621        gcr.io/stackdriver-agents/stackdriver-logging-agent:0.2-1.5.33-1-1   "/entrypoint.sh /usr…"   About a minute ago   Up About a minute                       stackdriver-logging-agent

everything looks good at this point;

try to run command as user:

 $ docker exec -it klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --dbpath=/data/mongodb --bind_ip localhost

and observe the same error:

2020-02-19T15:37:53.176+0000 I  STORAGE  [initandlisten] exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /data/mongodb, terminating

here key read-only directory: /data/mongodb;

check mounts and permissions inside of the container:

$ docker exec -it klt-mongo-svr-upd-wowt /bin/bash
bash-4.2$ mount
...
/dev/sdb on /data/mongodb type ext4 (rw,relatime)
...

as we expected disk was created and mounted in read-write mode to the container

bash-4.2$ ls -l /data/
total 8
drwxr-xr-x 4 mongodb root 4096 Feb 19 15:36 db
drwxr-xr-x 3 root    root 4096 Feb 19 15:33 mongodb
bash-4.2$

but to work with /data/mongodb you need root permissions;

try to run command as root:

$ docker exec -it --user root klt-mongo-svr-upd-wowt mongod --configsvr --replSet rs0 --dbpath=/data/mongodb
2020-02-19T15:45:24.970+0000 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-02-19T15:45:24.973+0000 I  CONTROL  [initandlisten] MongoDB starting : pid=119 port=27019 dbpath=/data/mongodb 64-bit host=mongo-svr-upd
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] db version v4.2.2-3
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] git version: 2cdb6e50913583f627acc5de35dc4e04dbfe196f
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2k-fips  26 Jan 2017
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] allocator: tcmalloc
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] modules: none
2020-02-19T15:45:24.974+0000 I  CONTROL  [initandlisten] build environment:
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten]     distarch: x86_64
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-02-19T15:45:24.975+0000 I  CONTROL  [initandlisten] options: { replication: { replSet: "rs0" }, sharding: { clusterRole: "configsvr" }, storage: { dbPath: "/data/mongodb" } }
2020-02-19T15:45:24.976+0000 I  STORAGE  [initandlisten] Detected data files in /data/mongodb created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
...

and it's working with root permissions.


问:
Extracting SVN info of a branch from a older revision using CMake commands
I have an issue something related to this but more with CMake commands.

I am using find package in my project to get info about working copy revision which i need to display in my application.

```<code># Load built-in SVN module
find_package(Subversion)

if(SUBVERSION_FOUND)
    # WC_INFO will define ${PROJECT_NAME}_WC_REVISION among others
    subversion_wc_info(${PROJECT_SOURCE_DIR} ${PROJECT_NAME})

    set(${PROJECT_NAME}_VERSION_REVISION ${${PROJECT_NAME}_WC_REVISION})
endif()
</code>```

Issue:

I created a branch from an older revision (#300) to fix some bug and switched the new branch to current working copy. But when i run find_package(Subversion) command on the newly created branch it gives me the same WC copy revision #363. I was expecting to get #355 i.e. ${${PROJECT_NAME}_WC_REVISION} working copy revision for the new branch should be #355. But i am getting #363 for both the branches.

```<code>      Main
        |
   #300 |---branch
        |   |
        |   |
        |   HEAD (committed changes at #355)
        |
        |
       HEAD
       #363
</code>```

Am i missing something here? I thought ${${PROJECT_NAME}_WC_REVISION} should give me HEAD revision of currently requested branch. How do i get the svn HEAD info for respective branches?

答: When switching branches in the Subversion repository you need to remove the CMakeCache.txt and rerun CMake.

Body:
I have an issue something related to this but more with CMake commands.

I am using find package in my project to get info about working copy revision which i need to display in my application.

# Load built-in SVN module
find_package(Subversion)

if(SUBVERSION_FOUND)
    # WC_INFO will define ${PROJECT_NAME}_WC_REVISION among others
    subversion_wc_info(${PROJECT_SOURCE_DIR} ${PROJECT_NAME})

    set(${PROJECT_NAME}_VERSION_REVISION ${${PROJECT_NAME}_WC_REVISION})
endif()

Issue:

I created a branch from an older revision (#300) to fix some bug and switched the new branch to current working copy. But when i run find_package(Subversion) command on the newly created branch it gives me the same WC copy revision #363. I was expecting to get #355 i.e. ${${PROJECT_NAME}_WC_REVISION} working copy revision for the new branch should be #355. But i am getting #363 for both the branches.

      Main
        |
   #300 |---branch
        |   |
        |   |
        |   HEAD (committed changes at #355)
        |
        |
       HEAD
       #363

Am i missing something here? I thought ${${PROJECT_NAME}_WC_REVISION} should give me HEAD revision of currently requested branch. How do i get the svn HEAD info for respective branches?


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答:
We have your properties set as system properties. These are accessed by a SystemProperties class.
This class is final with a private constructor, the properties are accessed via static methods only, so it is technically a Singleton. It is itself contained in a commons.jar every other project is depending on.

So there is no need to pass anything around as the settings are available directly where you need them.