问:
Python list: Extract integers from list of strings
I have a list with the following values, which in fact are strings inside the list:

```<code>mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
</code>```

How can I extract each value and create a new list with every value inside the list above?

I need a result like:

```<code>mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]
</code>```

Thank you in advance

答:
I'd offer a solution that is verbose but may be easier to understand

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10', '1', '']

separtedList = []
for element in mylist:
    separtedList+=element.split(',')

integerList = []
for element in separtedList:
    try:
        integerList.append(int(element))
    except ValueError:
        pass # our string seems not not be an integer, do nothing

mylist = integerList
print(mylist)
```

Body:
I have a list with the following values, which in fact are strings inside the list:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']

How can I extract each value and create a new list with every value inside the list above?

I need a result like:

mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]

Thank you in advance


来源: stackexchange

问:
Count the amount of times a word is repeated
I'm pretty new to C# however I am trying to solve this question down below. Any way I can count that specific word each time even when its repeated twice in the same list element? I am trying to not use the Split() function. Thanks for the help</p>
```<code>string wordToSearch = "Pig";
List<string> sentences = new List<string>()
             {
                 "The animal I really dig,",
                 "Above all others is the pig.",
                 "Pigs are noble. Pigs are clever,",
                 "Pigs are courteous. However,",
                 "Now and then, to break this rule,",
                 "One meets a pig who is a fool.",
                 "What, for example, would you say,",
                 "If strolling through the woods one day,",
                 "Right there in front of you you saw",
                 "A pig who'd built his house of STRAW?",
                 "The Wolf who saw it licked his lips,",
                 "And said, 'That pig has had his chips.'",
                 "'Little pig, little pig, let me come in!'",
                 "'No, no, by the hairs on my chinny-chin-chin!'",
                 "'Then I'll huff and I'll puff and I'll blow your house in!'"
             };
foreach (string sentence in sentences)
{
    int count = 0;
    if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
    {
        count++;
        Console.WriteLine(sentence + " " + "[" + count + "]");

    }
    else
    {
        Console.WriteLine(sentence + " " + "[" + count + "]");
    }

}
</code>```

答:
You'll probably want to call IndexOf in a loop, until there are no more matches found:

```<code>static int CountRepeats(
    string source,
    string toFind,
    StringComparison comparison = StringComparison.OrdinalIgnoreCase)
{
    int result = 0;
    int index = source.IndexOf(toFind, comparison);
    while (index != -1)
    {
        result++;

        // Resume the search just after the end of the previous occurrence:
        index = source.IndexOf(toFind, index + toFind.Length, comparison);
    }

    return result;
}
</code>```

NB: As with your current code, this will find matches within other words. For example, it will find the pig in spiggot. That may or may not be correct, depending on the precise requirements.

If you want the total count across all sentences, you'll need to move your count variable outside of your loop:

```<code>int count = 0;
foreach (string sentence in sentences)
{
    int sentenceCount = CountRepeats(sentence, wordToSearch);
    Console.WriteLine("{0} [{1}]", sentence, sentenceCount);
    count += sentenceCount;
}

Console.WriteLine("Total count: {0}", count);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new to C# however I am trying to solve this question down below. Any way I can count that specific word each time even when its repeated twice in the same list element? I am trying to not use the Split() function. Thanks for the help

string wordToSearch = "Pig";
List<string> sentences = new List<string>()
             {
                 "The animal I really dig,",
                 "Above all others is the pig.",
                 "Pigs are noble. Pigs are clever,",
                 "Pigs are courteous. However,",
                 "Now and then, to break this rule,",
                 "One meets a pig who is a fool.",
                 "What, for example, would you say,",
                 "If strolling through the woods one day,",
                 "Right there in front of you you saw",
                 "A pig who'd built his house of STRAW?",
                 "The Wolf who saw it licked his lips,",
                 "And said, 'That pig has had his chips.'",
                 "'Little pig, little pig, let me come in!'",
                 "'No, no, by the hairs on my chinny-chin-chin!'",
                 "'Then I'll huff and I'll puff and I'll blow your house in!'"
             };
foreach (string sentence in sentences)
{
    int count = 0;
    if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
    {
        count++;
        Console.WriteLine(sentence + " " + "[" + count + "]");

    }
    else
    {
        Console.WriteLine(sentence + " " + "[" + count + "]");
    }

}

Body:
You'll probably want to call IndexOf in a loop, until there are no more matches found:

static int CountRepeats(
    string source,
    string toFind,
    StringComparison comparison = StringComparison.OrdinalIgnoreCase)
{
    int result = 0;
    int index = source.IndexOf(toFind, comparison);
    while (index != -1)
    {
        result++;

        // Resume the search just after the end of the previous occurrence:
        index = source.IndexOf(toFind, index + toFind.Length, comparison);
    }

    return result;
}

NB: As with your current code, this will find matches within other words. For example, it will find the pig in spiggot. That may or may not be correct, depending on the precise requirements.

If you want the total count across all sentences, you'll need to move your count variable outside of your loop:

int count = 0;
foreach (string sentence in sentences)
{
    int sentenceCount = CountRepeats(sentence, wordToSearch);
    Console.WriteLine("{0} [{1}]", sentence, sentenceCount);
    count += sentenceCount;
}

Console.WriteLine("Total count: {0}", count);


问:
local storage-provisioner in rancher not creating the pvc
We are trying to configure local-storage in Rancher and storage provisioner configured successfully.
But when I create pvc using local-storage sc its going in pending state with below error.

```<code>   Normal   ExternalProvisioning  4m31s (x62 over 19m)  persistentvolume-controller                                                                         waiting for a volume to be created, either by external provisioner "rancher.io/local-path" or manually created by system administrator
  Normal   Provisioning          3m47s (x7 over 19m)   rancher.io/local-path_local-path-provisioner-5f8f96cb66-8s9dj_f1bdad61-eb48-4a7a-918c-6827e75d6a27  External provisioner is provisioning volume for claim "local-path-storage/test-pod-pvc-local"
  Warning  ProvisioningFailed    3m47s (x7 over 19m)   rancher.io/local-path_local-path-provisioner-5f8f96cb66-8s9dj_f1bdad61-eb48-4a7a-918c-6827e75d6a27  failed to provision volume with StorageClass "local-path": configuration error, no node was specified
[root@n01-deployer local]#
</code>```

sc configuration

```<code>[root@n01-deployer local]# kubectl edit  sc local-path
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"storage.k8s.io/v1","kind":"StorageClass","metadata":{"annotations":{},"name":"local-path"},"provisioner":"rancher.io/local-path","reclaimPolicy":"Delete","volumeBindingMode":"Immediate"}
  creationTimestamp: "2022-02-07T16:12:58Z"
  name: local-path
  resourceVersion: "1501275"
  uid: e8060018-e4a8-47f9-8dd4-c63f28eef3f2
provisioner: rancher.io/local-path
reclaimPolicy: Delete
volumeBindingMode: Immediate
</code>```

PVC configuration

```<code>[root@n01-deployer local]# cat pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  namespace: local-path-storage
  name: test-pod-pvc-local-1

spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
  volumeMode: Filesystem

</code>```

I have mounted the local volume in all the worker node still my pvc not getting created. Can some please help me solve this issue?

答:
The key to your problem was updating PSP.

I would like to add something about PSP:

According to this documentation and this blog:

As of Kubernetes  version 1.21, PodSecurityPolicy (beta) is deprecated. The Kubernetes project aims to shut the feature down in  version 1.25.

However I haven't found any information in Rancher's case (the documentation is up to date).

Rancher ships with two default Pod Security Policies (PSPs): the restricted and unrestricted policies.

See also:

The benefits of Pod Security Policy

Secure Kubernetes cluster PSP

Pod Security Policies

Body:
We are trying to configure local-storage in Rancher and storage provisioner configured successfully.
But when I create pvc using local-storage sc its going in pending state with below error.

   Normal   ExternalProvisioning  4m31s (x62 over 19m)  persistentvolume-controller                                                                         waiting for a volume to be created, either by external provisioner "rancher.io/local-path" or manually created by system administrator
  Normal   Provisioning          3m47s (x7 over 19m)   rancher.io/local-path_local-path-provisioner-5f8f96cb66-8s9dj_f1bdad61-eb48-4a7a-918c-6827e75d6a27  External provisioner is provisioning volume for claim "local-path-storage/test-pod-pvc-local"
  Warning  ProvisioningFailed    3m47s (x7 over 19m)   rancher.io/local-path_local-path-provisioner-5f8f96cb66-8s9dj_f1bdad61-eb48-4a7a-918c-6827e75d6a27  failed to provision volume with StorageClass "local-path": configuration error, no node was specified
[root@n01-deployer local]#

sc configuration

[root@n01-deployer local]# kubectl edit  sc local-path
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"storage.k8s.io/v1","kind":"StorageClass","metadata":{"annotations":{},"name":"local-path"},"provisioner":"rancher.io/local-path","reclaimPolicy":"Delete","volumeBindingMode":"Immediate"}
  creationTimestamp: "2022-02-07T16:12:58Z"
  name: local-path
  resourceVersion: "1501275"
  uid: e8060018-e4a8-47f9-8dd4-c63f28eef3f2
provisioner: rancher.io/local-path
reclaimPolicy: Delete
volumeBindingMode: Immediate

PVC configuration

[root@n01-deployer local]# cat pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  namespace: local-path-storage
  name: test-pod-pvc-local-1

spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
  volumeMode: Filesystem

I have mounted the local volume in all the worker node still my pvc not getting created. Can some please help me solve this issue?


问:
Newman Collection Variables
It seems to me there is no solution for this, but I will still ask to see if anyone can help me.

I'm trying to use Newman to run my Postman collection, but I have a problem. Newman doesn't seems to be able to use Collection Variables. I've encountered this error while trying it:

```<code>getaddrinfo ENOTFOUND {{baseUrl}}
</code>```

This is because I use the variable {{baseUrl}} to define my base url without needing to repeat it.

```<code>"variable": [
  {
    "id": "baseUrl",
    "type": "string",
    "value": "https://dev.sonsy.io/api/v1"
  }
]
</code>```

And if I hover over the variable in Postman Collection Runner it tells me that the scope of the variable is Collection. I would like to keep using collection variables instead of creating an Environment or Global Variables.

Is there any work around? Could it be that my Collection is wrongly structured for Newman? It works just fine in the Postman Collection Runner.

Thank you and good coding ;)

答:
Update your Collection variable's Initial Value with there Current Value.
Newman only takes Initial values from Collection Variables.</p>

Title: Newman Collection Variables

Body:
It seems to me there is no solution for this, but I will still ask to see if anyone can help me.

I'm trying to use Newman to run my Postman collection, but I have a problem. Newman doesn't seems to be able to use Collection Variables. I've encountered this error while trying it:

getaddrinfo ENOTFOUND {{baseUrl}}

This is because I use the variable {{baseUrl}} to define my base url without needing to repeat it.

"variable": [
  {
    "id": "baseUrl",
    "type": "string",
    "value": "https://dev.sonsy.io/api/v1"
  }
]

And if I hover over the variable in Postman Collection Runner it tells me that the scope of the variable is Collection. I would like to keep using collection variables instead of creating an Environment or Global Variables.

Is there any work around? Could it be that my Collection is wrongly structured for Newman? It works just fine in the Postman Collection Runner.

Thank you and good coding ;)


问:
Calculate alters density in a large graph in R
I'm working with a large social network in R (560120 ties). I want to calculate the local density of nodes, as well as the density of their alters.

I achieved the former with the following code snippet, using the package igraph.

```<code> g <- graph_from_data_frame(edgelist, directed = FALSE)
 egonet_list <- make_ego_graph(g)

 dat <- data.frame(
    id = names(V(g),
    egonet_density = lapply(egonet_list, graph.density) %>% unlist()
  )
</code>```

However, I run into memory troubles when I try to calculate the network of ego's alters. I try to run the following:

```<code>alter_list <- make_ego_graph(g, order = 2, mindist = 1)
</code>```

It does work for smaller graphs, but with my network setup, it is eating up all of my RAM (>110GB) and crashing.

Does anyone have a suggestion how to solve this issue in a memory-friendly way?

答:
You can calculate the local density for one node at a time without saving the alter graphs.

```<code>library(igraph)
library(purrr)
make_ego_graph(g, order = 2, nodes = 1, mindist = 1)

V(g) %>%
map_dbl(~ make_ego_graph(g, order = 2, nodes = .x, mindist = 1)[[1]] %>%
          graph.density())

</code>```

You can take the code within map and write a function called  get_alter_density() and use lapply if you prefer.

Body:
I'm working with a large social network in R (560120 ties). I want to calculate the local density of nodes, as well as the density of their alters.

I achieved the former with the following code snippet, using the package igraph.

 g <- graph_from_data_frame(edgelist, directed = FALSE)
 egonet_list <- make_ego_graph(g)

 dat <- data.frame(
    id = names(V(g),
    egonet_density = lapply(egonet_list, graph.density) %>% unlist()
  )

However, I run into memory troubles when I try to calculate the network of ego's alters. I try to run the following:

alter_list <- make_ego_graph(g, order = 2, mindist = 1)

It does work for smaller graphs, but with my network setup, it is eating up all of my RAM (>110GB) and crashing.

Does anyone have a suggestion how to solve this issue in a memory-friendly way?

Body:
You can calculate the local density for one node at a time without saving the alter graphs.

library(igraph)
library(purrr)
make_ego_graph(g, order = 2, nodes = 1, mindist = 1)

V(g) %>%
map_dbl(~ make_ego_graph(g, order = 2, nodes = .x, mindist = 1)[[1]] %>%
          graph.density())

You can take the code within map and write a function called  get_alter_density() and use lapply if you prefer.


问:
FragmentFirstBinding Error with First Fragment XML Changes
I'm in Bumblebee v.2021.1.1. I don't have any database elements in my project. I do have defaults in the first fragment:

```<code>import com.my.app.databinding.FragmentFirstBinding
</code>```

in:

```<code>class FirstFragment : Fragment() {

private var _binding: FragmentFirstBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

    _binding = FragmentFirstBinding.inflate(inflater, container, false)
...
return binding.root
}
</code>```

When I make changes to fragment_first.xml the FirstFragment.kt file blows up: In Android Studio the problems tab reads Unresolved reference: FragmentFirstBinding and Variable expected, each several times for each occurrence. I don't understand the Logcat much at all. The only way I've found to correct it is to remove the null safety (?) from:

```<code>    private var _binding: FragmentFirstBinding? = null
</code>```

and then to just add it (the question mark) back in.

Also, I've seen about making databinding true in the build.gradle file, but it was not the default when I chose the Basic Activity template when starting the project. Is it stable to add databinding = true to the build.gradle file?

答:
Thank goodness! I believe the IDE and Kotlin code both work beautifully and I'm right. I have found the error is generated only if a fragment file and a related XML file are running at the same time.

For example: if I open FirstFragment.kt and leave it open and then open and edit fragment_first.xml then the .kt (Kotlin) file gets the error.

But I don't get the error if I don't have the fragment file open, and then change the XML and then open the fragment file for editing.

In other words, when I make changes to a related XML file and then open the related Kotlin file, it can analyze and adjust to the changes made to the XML file that it has to bind to.

In addition, in an attempt to be clear, it looks like having only one tab (one file) open in Android Studio may prevent this from happening.

Body:
I'm in Bumblebee v.2021.1.1. I don't have any database elements in my project. I do have defaults in the first fragment:

import com.my.app.databinding.FragmentFirstBinding

in:

class FirstFragment : Fragment() {

private var _binding: FragmentFirstBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

    _binding = FragmentFirstBinding.inflate(inflater, container, false)
...
return binding.root
}

When I make changes to fragment_first.xml the FirstFragment.kt file blows up: In Android Studio the problems tab reads Unresolved reference: FragmentFirstBinding and Variable expected, each several times for each occurrence. I don't understand the Logcat much at all. The only way I've found to correct it is to remove the null safety (?) from:

    private var _binding: FragmentFirstBinding? = null

and then to just add it (the question mark) back in.

Also, I've seen about making databinding true in the build.gradle file, but it was not the default when I chose the Basic Activity template when starting the project. Is it stable to add databinding = true to the build.gradle file?


问:
Not getting past GetAwaiter().GetResult()
I have a PostAsync method in an internal part of my code that doesn't seem to ever return a response. However, I use it synchronously via .GetAwaiter().GetResult(). The target framework is net45.

public async Task<TResponse> PostAsync<TResponse, TRequest>(string method, TRequest body)
{
    _logger.Log($"Method {method}, body {JsonConvert.SerializeObject(body)} on url {_configuration.ApiUrl}");
    using (var customDelegatingHandler = new HMACDelegatingHandler(_configuration, _apiId))
    {
        using (var client = new HttpClient(customDelegatingHandler))
        {
            var response = await client.PostAsync($"{_configuration.ApiUrl}/{method}",
                new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();

                return JsonConvert.DeserializeObject<TResponse>(content);
            }
            else
            {
                await Log(body, response);
            }
            return default;
        }
    }
}
```
<p>What I do is call the PostAsync in another method:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<decimal> GetBalance(Request request)
{
    // = new MyCustomClient...

    QueryFundsResponse response = await customClient.PostAsync<Response, Request>("testAction", request);
    if (response == default)
        return 0.0m;

    return response.Amount;
}
</code>```

Then, finally at the very top of the flow, I call the GetBalance method like this:

var sw = new Stopwatch();
sw.Start();
var balance = _provider
    .GetBalance(request)
    .ConfigureAwait(false)
    .GetAwaiter()
    .GetResult();
sw.Stop();
_logger.Log($"GetBalance -> method duration: { sw.ElapsedMilliseconds }");
```

I don't see the log in my logs at all, and I don't seem to ever get a response or any code executed after the .GetAwaiter().GetResult(). Switching the last block of code to be asynchronous and await the GetBalance() method is not really an option for me, sadly.

I am unable to figure out why nothing is changing, even after using the .ConfigureAwait(false) method.

答:
You're experiencing the common deadlock that happens when you block on asynchronous code (described in detail on my blog). There are a variety of ways to get around it, but they're all hacks and none of them work in every situation.

In your case, I'd say either use the direct blocking hack or use the boolean argument hack.

The direct blocking hack requires you to use ConfigureAwait(false) everywhere. Note that your current code only uses ConfigureAwait(false) where it doesn't do anything; ConfigureAwait configures the await, so it needs to go where the awaits are. All of them.

The boolean argument hack means that your code will take a bool parameter that determines whether it executes synchronously or asynchronously. Note that HttpClient (for now) has an async-only API, so your custom delegating handler will need to support direct blocking, using ConfigureAwait(false). Similarly, Log will either need a synchronous equivalent or also support direct blocking. Your code would end up looking something like this:

```<code>public Task<TResponse> PostAsync<TResponse, TRequest>(string method, TRequest body) => PostCoreAsync(method, body, sync: false);
public TResponse Post<TResponse, TRequest>(string method, TRequest body) => PostCoreAsync(method, body, sync: true).GetAwaiter().GetResult();
private async Task<TResponse> PostCoreAsync<TResponse, TRequest>(string method, TRequest body, bool sync)
{
  _logger.Log($"Method {method}, body {JsonConvert.SerializeObject(body)} on url {_configuration.ApiUrl}");
  using (var customDelegatingHandler = new HMACDelegatingHandler(_configuration, _apiId))
  {
    using (var client = new HttpClient(customDelegatingHandler))
    {
      var responseTask = client.PostAsync($"{_configuration.ApiUrl}/{method}",
         new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));
      var response = sync ? responseTask.GetAwaiter().GetResult() : await responseTask;

      if (response.StatusCode == HttpStatusCode.OK)
      {
        var content = sync ? response.Content.ReadAsStringAsync().GetAwaiter().GetResult() : await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<TResponse>(content);
      }
      else
      {
        var logTask = Log(body, response);
        if (sync)
          logTask.GetAwaiter().GetResult();
        else
          await logTask;
      }
      return default;
    }
  }
}

public Task<decimal> GetBalanceAsync(Request request) => GetBalanceCoreAsync(request, sync: false);
public decimal GetBalance(Request request) => GetBalanceCoreAsync(request, sync: true).GetAwaiter().GetResult();
private async Task<decimal> GetBalanceCoreAsync(Request request, bool sync)
{
    // = new MyCustomClient...

    QueryFundsResponse response = sync ?
        customClient.Post<Response, Request>("testAction", request) :
        await customClient.PostAsync<Response, Request>("testAction", request);
    if (response == default)
        return 0.0m;

    return response.Amount;
}

var sw = new Stopwatch();
sw.Start();
var balance = _provider
    .GetBalance(request);
sw.Stop();
_logger.Log($"GetBalance -> method duration: { sw.ElapsedMilliseconds }");
</code>```

Body:
I have a PostAsync method in an internal part of my code that doesn't seem to ever return a response. However, I use it synchronously via .GetAwaiter().GetResult(). The target framework is net45.

public async Task<TResponse> PostAsync<TResponse, TRequest>(string method, TRequest body)
{
    _logger.Log($"Method {method}, body {JsonConvert.SerializeObject(body)} on url {_configuration.ApiUrl}");
    using (var customDelegatingHandler = new HMACDelegatingHandler(_configuration, _apiId))
    {
        using (var client = new HttpClient(customDelegatingHandler))
        {
            var response = await client.PostAsync($"{_configuration.ApiUrl}/{method}",
                new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();

                return JsonConvert.DeserializeObject<TResponse>(content);
            }
            else
            {
                await Log(body, response);
            }
            return default;
        }
    }
}

What I do is call the PostAsync in another method:

public async Task<decimal> GetBalance(Request request)
{
    // = new MyCustomClient...

    QueryFundsResponse response = await customClient.PostAsync<Response, Request>("testAction", request);
    if (response == default)
        return 0.0m;

    return response.Amount;
}

Then, finally at the very top of the flow, I call the GetBalance method like this:

var sw = new Stopwatch();
sw.Start();
var balance = _provider
    .GetBalance(request)
    .ConfigureAwait(false)
    .GetAwaiter()
    .GetResult();
sw.Stop();
_logger.Log($"GetBalance -> method duration: { sw.ElapsedMilliseconds }");

I don't see the log in my logs at all, and I don't seem to ever get a response or any code executed after the .GetAwaiter().GetResult(). Switching the last block of code to be asynchronous and await the GetBalance() method is not really an option for me, sadly.

I am unable to figure out why nothing is changing, even after using the .ConfigureAwait(false) method.

Body:
You're experiencing the common deadlock that happens when you block on asynchronous code (described in detail on my blog). There are a variety of ways to get around it, but they're all hacks and none of them work in every situation.

In your case, I'd say either use the direct blocking hack or use the boolean argument hack.

The direct blocking hack requires you to use ConfigureAwait(false) everywhere. Note that your current code only uses ConfigureAwait(false) where it doesn't do anything; ConfigureAwait configures the await, so it needs to go where the awaits are. All of them.

The boolean argument hack means that your code will take a bool parameter that determines whether it executes synchronously or asynchronously. Note that HttpClient (for now) has an async-only API, so your custom delegating handler will need to support direct blocking, using ConfigureAwait(false). Similarly, Log will either need a synchronous equivalent or also support direct blocking. Your code would end up looking something like this:

public Task<TResponse> PostAsync<TResponse, TRequest>(string method, TRequest body) => PostCoreAsync(method, body, sync: false);
public TResponse Post<TResponse, TRequest>(string method, TRequest body) => PostCoreAsync(method, body, sync: true).GetAwaiter().GetResult();
private async Task<TResponse> PostCoreAsync<TResponse, TRequest>(string method, TRequest body, bool sync)
{
  _logger.Log($"Method {method}, body {JsonConvert.SerializeObject(body)} on url {_configuration.ApiUrl}");
  using (var customDelegatingHandler = new HMACDelegatingHandler(_configuration, _apiId))
  {
    using (var client = new HttpClient(customDelegatingHandler))
    {
      var responseTask = client.PostAsync($"{_configuration.ApiUrl}/{method}",
         new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));
      var response = sync ? responseTask.GetAwaiter().GetResult() : await responseTask;

      if (response.StatusCode == HttpStatusCode.OK)
      {
        var content = sync ? response.Content.ReadAsStringAsync().GetAwaiter().GetResult() : await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<TResponse>(content);
      }
      else
      {
        var logTask = Log(body, response);
        if (sync)
          logTask.GetAwaiter().GetResult();
        else
          await logTask;
      }
      return default;
    }
  }
}

public Task<decimal> GetBalanceAsync(Request request) => GetBalanceCoreAsync(request, sync: false);
public decimal GetBalance(Request request) => GetBalanceCoreAsync(request, sync: true).GetAwaiter().GetResult();
private async Task<decimal> GetBalanceCoreAsync(Request request, bool sync)
{
    // = new MyCustomClient...

    QueryFundsResponse response = sync ?
        customClient.Post<Response, Request>("testAction", request) :
        await customClient.PostAsync<Response, Request>("testAction", request);
    if (response == default)
        return 0.0m;

    return response.Amount;
}

var sw = new Stopwatch();
sw.Start();
var balance = _provider
    .GetBalance(request);
sw.Stop();
_logger.Log($"GetBalance -> method duration: { sw.ElapsedMilliseconds }");


问:
Expo App with zoomed Icon after installed
I made a simple app to convert units using Expo.
However, the icon is zoomed in once installed.

It was supposed to be like this

This is a 1024x1024 image.

The source code of my app is here -> https://github.com/Elson0509/peuc

The app in the Google Play Store is here -> https://play.google.com/store/apps/details?id=com.elsonramos.peuc

Someone can help me?

Thank you

答:
The latest Android versions support adaptive icons which scaled well for different icon layouts - Square, Round, Circle, and more.

Expo Team provide a template to design adaptive icon
https://www.figma.com/community/file/1155362909441341285


问:
Measuring OpenMP Fork/Join latency
Since MPI-3 comes with functionality for shared memory parallelism, and it seems to be perfectly matched for my application, I'm critically considering rewriting my hybrid OpemMP-MPI code into a pure MPI implementation.

In order to drive the last nail into the coffin, I decided to run a small program to test the latency of the OpenMP fork/join mechanism. Here's the code (written for Intel compiler):

```<code>void action1(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t2.data()[index]) * std::cos(t2.data()[index]);
    }
}

void action2(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * std::sin(t2.data()[index]);
    }
}

void action3(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * t2.data()[index];
    }
}

void action4(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sqrt(t2.data()[index]);
    }
}

void action5(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * 2.0;
    }
}

void all_actions(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t2.data()[index]) * std::cos(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * std::sin(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * t2.data()[index];
        t1.data()[index] = std::sqrt(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * 2.0;
    }
}

int main()
{
    // decide the process parameters
    const auto n = std::size_t{8000000};
    const auto test_count = std::size_t{500};

    // garbage data...
    auto t1 = std::vector<double>(n);
    auto t2 = std::vector<double>(n);

    //+/////////////////
    // perform actions one after the other
    //+/////////////////

    const auto sp = timer::spot_timer();
    const auto dur1 = sp.duration_in_us();
    for (auto index = std::size_t{}; index < test_count; ++index)
    {
        #pragma noinline
        action1(t1, t2);
        #pragma noinline
        action2(t1, t2);
        #pragma noinline
        action3(t1, t2);
        #pragma noinline
        action4(t1, t2);
        #pragma noinline
        action5(t1, t2);
    }
    const auto dur2 = sp.duration_in_us();

    //+/////////////////
    // perform all actions at once
    //+/////////////////
    const auto dur3 = sp.duration_in_us();
    for (auto index = std::size_t{}; index < test_count; ++index)
    {
        #pragma noinline
        all_actions(t1, t2);
    }
    const auto dur4 = sp.duration_in_us();

    const auto a = dur2 - dur1;
    const auto b = dur4 - dur3;
    if (a < b)
    {
        throw std::logic_error("negative_latency_error");
    }
    const auto fork_join_latency = (a - b) / (test_count * 4);

    // report
    std::cout << "Ran the program with " << omp_get_max_threads() << ", the calculated fork/join latency is: " << fork_join_latency << " us" << std::endl;

    return 0;
}
</code>```

As you can see, the idea is to perform a set of actions separately (each within an OpenMP loop) and to calculate the average duration of this, and then to perform all these actions together (within the same OpenMP loop) and to calculate the average duration of that. Then we have a linear system of equations in two variables, one of which is the latency of the fork/join mechanism, which can be solved to obtain the value.

Questions:

Am I overlooking something?

Currently, I am using "-O0" to prevent smarty-pants compiler from doing its funny business. Which compiler optimizations should I use, would these also have an effect on the latency itself etc etc?

On my Coffee Lake processor with 6 cores, I measured a latency of ~850 us. Does this sound about right?

Edit 3

) I've included a warm-up calculation in the beginning upon @paleonix's suggestion,

) I've reduced the number of actions for simplicity, and,

) I've switched to 'omp_get_wtime' to make it universally understandable.

I am now running the following code with flag -O3:

```<code>void action1(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t1.data()[index]);
    }
}

void action2(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] =  std::cos(t1.data()[index]);
    }
}

void action3(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::atan(t1.data()[index]);
    }
}

void all_actions(std::vector<double>& t1, std::vector<double>& t2, std::vector<double>& t3)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        #pragma optimize("", off)
        t1.data()[index] = std::sin(t1.data()[index]);
        t2.data()[index] = std::cos(t2.data()[index]);
        t3.data()[index] = std::atan(t3.data()[index]);
        #pragma optimize("", on)
    }
}

int main()
{
    // decide the process parameters
    const auto n = std::size_t{1500000}; // 12 MB (way too big for any cache)
    const auto experiment_count = std::size_t{1000};

    // garbage data...
    auto t1 = std::vector<double>(n);
    auto t2 = std::vector<double>(n);
    auto t3 = std::vector<double>(n);
    auto t4 = std::vector<double>(n);
    auto t5 = std::vector<double>(n);
    auto t6 = std::vector<double>(n);
    auto t7 = std::vector<double>(n);
    auto t8 = std::vector<double>(n);
    auto t9 = std::vector<double>(n);

    //+/////////////////
    // warum-up, initialization of threads etc.
    //+/////////////////
    for (auto index = std::size_t{}; index < experiment_count / 10; ++index)
    {
        all_actions(t1, t2, t3);
    }

    //+/////////////////
    // perform actions (part A)
    //+/////////////////

    const auto dur1 = omp_get_wtime();
    for (auto index = std::size_t{}; index < experiment_count; ++index)
    {
        action1(t4);
        action2(t5);
        action3(t6);
    }
    const auto dur2 = omp_get_wtime();

    //+/////////////////
    // perform all actions at once (part B)
    //+/////////////////

    const auto dur3 = omp_get_wtime();
    #pragma nofusion
    for (auto index = std::size_t{}; index < experiment_count; ++index)
    {
        all_actions(t7, t8, t9);
    }
    const auto dur4 = omp_get_wtime();

    const auto a = dur2 - dur1;
    const auto b = dur4 - dur3;
    const auto fork_join_latency = (a - b) / (experiment_count * 2);

    // report
    std::cout << "Ran the program with " << omp_get_max_threads() << ", the calculated fork/join latency is: "
        << fork_join_latency * 1E+6 << " us" << std::endl;

    return 0;
}
</code>```

With this, the measured latency is now 115 us. What's puzzling me now is that this value changes when the actions are changed. According to my logic, since I'm doing the same action in both parts A and B, there should actually be no change. Why is this happening?

答:
TL;DR: cores do not operate exactly at the same speed due to dynamic frequency scaling and there is a lot of noise that can impact the execution resulting in expensive synchronizations. Your benchmark mostly measures this synchronization overhead. Using a unique parallel section should solve this problem.

The benchmark is rather flawed. This code does not actually measure the "latency" of OpenMP fork/join sections. It measures a combinations of many overheads including:

load balancing and synchronizations: the split loops perform more frequent synchronizations (5 times more) than the big merged one. Synchronizations are expensive, not because of the communication overhead, but because of the actual synchronization between cores that are inherently not synchronized. Indeed, a slight work-imbalance between the threads results in other thread waiting for the completion of the slowest thread. You might think this should not happen because of static scheduling, but context switches and dynamic frequency scaling cause some threads to be slower than others. Context switches are especially important if threads are not bound to core or if some programs are scheduled by the OS during the computation. Dynamic frequency scaling (eg. Intel turbo boost) causes some (group of threads) to be faster regarding the workload, the temperature of each core and the overall package, the number of active cores, the estimated power consumption, etc. The higher the number of core, the higher the synchronization overheads. Note that this overhead is dependent of the time taken by the loops. For more information, please read the below analysis.

Performance of loop splitting: merging the 5 loops into a unique one impacts the generated assembly code (since less instructions are needed) and also impacts load/store in the cache (since the memory access pattern is a bit different). Not to mention it could theoretically impact vectorization although ICC does not vectorize this specific code. That being said, this does not appear to be the main actual issue on my machine since I am not able to reproduce the problem with Clang by running the program in sequential while I can with many threads.

To solve this problem you can use a unique parallel section. omp for loops must use the nowait clause so not to introduce synchronizations. Alternatively, task-based construct like taskloop with the nogroup can help to achieve the same thing. In both case you should be careful about dependencies since multiple for-loop/task-loos can run in parallel. This is fine in you current code.

Analysis

Analyzing the effect of short synchronizations caused by execution noise (context switches, frequency scaling, cache effect, OS interruptions, etc.) is pretty hard since it is likely never the same thread that is the slowest during synchronizations in your case (the work between thread is quite balance but they velocity is not perfectly equal).

That being said, if this hypothesis is true fork_join_latency should be dependent of n. Thus, increasing n also increase fork_join_latency. Here is was I can get with Clang 13 + IOMP (using -fopenmp -O3) on my 6-core i5-9600KF processor:

n=   80'000    fork_join_latency<0.000001
n=  800'000    fork_join_latency=0.000036
n= 8'000'000   fork_join_latency=0.000288
n=80'000'000   fork_join_latency=0.003236
```
<p>Note that the <code>fork_join_latency</code> timings are not very stable in practice but the behavior is pretty visible: the measured overhead is dependent <code>n</code>.</p>
<p>A better solution is to measure the synchronization time by measuring the time of the loop for each thread and accumulate the difference between the minimum and maximum time. Here is an example of code:</p>
<pre class="lang-cpp prettyprint-override"><code>double totalSyncTime = 0.0;

void action1(std::vector<double>& t1)
{
    constexpr int threadCount = 6;
    double timePerThread[threadCount] = {0};

    #pragma omp parallel
    {
        const double start = omp_get_wtime();
        #pragma omp for nowait schedule(static) //num_threads(std::thread::hardware_concurrency())
        #pragma nounroll
        for (auto index = std::size_t{}; index < t1.size(); ++index)
        {
            t1.data()[index] = std::sin(t1.data()[index]);
        }
        const double stop = omp_get_wtime();
        const double threadLoopTime = (stop - start);
        timePerThread[omp_get_thread_num()] = threadLoopTime;
    }

    const double mini = *std::min_element(timePerThread, timePerThread+threadCount);
    const double maxi = *std::max_element(timePerThread, timePerThread+threadCount);
    const double syncTime = maxi - mini;
    totalSyncTime += syncTime;
}
</code>```

You can then divide totalSyncTime the same way you did for fork_join_latency and print the result. I get 0.000284 with fork_join_latency=0.000398 (with n=8'000'000) which almost proves that a major part of the overhead is due to synchronizations and more especially due to a slightly different thread execution velocity. Note that this overhead does not include the implicit barrier at the end of the OpenMP parallel section.

Title: Measuring OpenMP Fork/Join latency

Body:
Since MPI-3 comes with functionality for shared memory parallelism, and it seems to be perfectly matched for my application, I'm critically considering rewriting my hybrid OpemMP-MPI code into a pure MPI implementation.

In order to drive the last nail into the coffin, I decided to run a small program to test the latency of the OpenMP fork/join mechanism. Here's the code (written for Intel compiler):

void action1(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t2.data()[index]) * std::cos(t2.data()[index]);
    }
}

void action2(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * std::sin(t2.data()[index]);
    }
}

void action3(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * t2.data()[index];
    }
}

void action4(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sqrt(t2.data()[index]);
    }
}

void action5(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = t2.data()[index] * 2.0;
    }
}

void all_actions(std::vector<double>& t1, std::vector<double>& t2)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t2.data()[index]) * std::cos(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * std::sin(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * t2.data()[index];
        t1.data()[index] = std::sqrt(t2.data()[index]);
        t1.data()[index] = t2.data()[index] * 2.0;
    }
}

int main()
{
    // decide the process parameters
    const auto n = std::size_t{8000000};
    const auto test_count = std::size_t{500};

    // garbage data...
    auto t1 = std::vector<double>(n);
    auto t2 = std::vector<double>(n);

    //+/////////////////
    // perform actions one after the other
    //+/////////////////

    const auto sp = timer::spot_timer();
    const auto dur1 = sp.duration_in_us();
    for (auto index = std::size_t{}; index < test_count; ++index)
    {
        #pragma noinline
        action1(t1, t2);
        #pragma noinline
        action2(t1, t2);
        #pragma noinline
        action3(t1, t2);
        #pragma noinline
        action4(t1, t2);
        #pragma noinline
        action5(t1, t2);
    }
    const auto dur2 = sp.duration_in_us();

    //+/////////////////
    // perform all actions at once
    //+/////////////////
    const auto dur3 = sp.duration_in_us();
    for (auto index = std::size_t{}; index < test_count; ++index)
    {
        #pragma noinline
        all_actions(t1, t2);
    }
    const auto dur4 = sp.duration_in_us();

    const auto a = dur2 - dur1;
    const auto b = dur4 - dur3;
    if (a < b)
    {
        throw std::logic_error("negative_latency_error");
    }
    const auto fork_join_latency = (a - b) / (test_count * 4);

    // report
    std::cout << "Ran the program with " << omp_get_max_threads() << ", the calculated fork/join latency is: " << fork_join_latency << " us" << std::endl;

    return 0;
}

As you can see, the idea is to perform a set of actions separately (each within an OpenMP loop) and to calculate the average duration of this, and then to perform all these actions together (within the same OpenMP loop) and to calculate the average duration of that. Then we have a linear system of equations in two variables, one of which is the latency of the fork/join mechanism, which can be solved to obtain the value.

Questions:

Am I overlooking something?

Currently, I am using "-O0" to prevent smarty-pants compiler from doing its funny business. Which compiler optimizations should I use, would these also have an effect on the latency itself etc etc?

On my Coffee Lake processor with 6 cores, I measured a latency of ~850 us. Does this sound about right?

Edit 3

) I've included a warm-up calculation in the beginning upon @paleonix's suggestion,

) I've reduced the number of actions for simplicity, and,

) I've switched to 'omp_get_wtime' to make it universally understandable.

I am now running the following code with flag -O3:

void action1(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::sin(t1.data()[index]);
    }
}

void action2(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] =  std::cos(t1.data()[index]);
    }
}

void action3(std::vector<double>& t1)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        t1.data()[index] = std::atan(t1.data()[index]);
    }
}

void all_actions(std::vector<double>& t1, std::vector<double>& t2, std::vector<double>& t3)
{
    #pragma omp parallel for schedule(static) num_threads(std::thread::hardware_concurrency())
    for (auto index = std::size_t{}; index < t1.size(); ++index)
    {
        #pragma optimize("", off)
        t1.data()[index] = std::sin(t1.data()[index]);
        t2.data()[index] = std::cos(t2.data()[index]);
        t3.data()[index] = std::atan(t3.data()[index]);
        #pragma optimize("", on)
    }
}

int main()
{
    // decide the process parameters
    const auto n = std::size_t{1500000}; // 12 MB (way too big for any cache)
    const auto experiment_count = std::size_t{1000};

    // garbage data...
    auto t1 = std::vector<double>(n);
    auto t2 = std::vector<double>(n);
    auto t3 = std::vector<double>(n);
    auto t4 = std::vector<double>(n);
    auto t5 = std::vector<double>(n);
    auto t6 = std::vector<double>(n);
    auto t7 = std::vector<double>(n);
    auto t8 = std::vector<double>(n);
    auto t9 = std::vector<double>(n);

    //+/////////////////
    // warum-up, initialization of threads etc.
    //+/////////////////
    for (auto index = std::size_t{}; index < experiment_count / 10; ++index)
    {
        all_actions(t1, t2, t3);
    }

    //+/////////////////
    // perform actions (part A)
    //+/////////////////

    const auto dur1 = omp_get_wtime();
    for (auto index = std::size_t{}; index < experiment_count; ++index)
    {
        action1(t4);
        action2(t5);
        action3(t6);
    }
    const auto dur2 = omp_get_wtime();

    //+/////////////////
    // perform all actions at once (part B)
    //+/////////////////

    const auto dur3 = omp_get_wtime();
    #pragma nofusion
    for (auto index = std::size_t{}; index < experiment_count; ++index)
    {
        all_actions(t7, t8, t9);
    }
    const auto dur4 = omp_get_wtime();

    const auto a = dur2 - dur1;
    const auto b = dur4 - dur3;
    const auto fork_join_latency = (a - b) / (experiment_count * 2);

    // report
    std::cout << "Ran the program with " << omp_get_max_threads() << ", the calculated fork/join latency is: "
        << fork_join_latency * 1E+6 << " us" << std::endl;

    return 0;
}

With this, the measured latency is now 115 us. What's puzzling me now is that this value changes when the actions are changed. According to my logic, since I'm doing the same action in both parts A and B, there should actually be no change. Why is this happening?

Body:
TL;DR: cores do not operate exactly at the same speed due to dynamic frequency scaling and there is a lot of noise that can impact the execution resulting in expensive synchronizations. Your benchmark mostly measures this synchronization overhead. Using a unique parallel section should solve this problem.

The benchmark is rather flawed. This code does not actually measure the "latency" of OpenMP fork/join sections. It measures a combinations of many overheads including:

load balancing and synchronizations: the split loops perform more frequent synchronizations (5 times more) than the big merged one. Synchronizations are expensive, not because of the communication overhead, but because of the actual synchronization between cores that are inherently not synchronized. Indeed, a slight work-imbalance between the threads results in other thread waiting for the completion of the slowest thread. You might think this should not happen because of static scheduling, but context switches and dynamic frequency scaling cause some threads to be slower than others. Context switches are especially important if threads are not bound to core or if some programs are scheduled by the OS during the computation. Dynamic frequency scaling (eg. Intel turbo boost) causes some (group of threads) to be faster regarding the workload, the temperature of each core and the overall package, the number of active cores, the estimated power consumption, etc. The higher the number of core, the higher the synchronization overheads. Note that this overhead is dependent of the time taken by the loops. For more information, please read the below analysis.

Performance of loop splitting: merging the 5 loops into a unique one impacts the generated assembly code (since less instructions are needed) and also impacts load/store in the cache (since the memory access pattern is a bit different). Not to mention it could theoretically impact vectorization although ICC does not vectorize this specific code. That being said, this does not appear to be the main actual issue on my machine since I am not able to reproduce the problem with Clang by running the program in sequential while I can with many threads.

To solve this problem you can use a unique parallel section. omp for loops must use the nowait clause so not to introduce synchronizations. Alternatively, task-based construct like taskloop with the nogroup can help to achieve the same thing. In both case you should be careful about dependencies since multiple for-loop/task-loos can run in parallel. This is fine in you current code.

Analysis

Analyzing the effect of short synchronizations caused by execution noise (context switches, frequency scaling, cache effect, OS interruptions, etc.) is pretty hard since it is likely never the same thread that is the slowest during synchronizations in your case (the work between thread is quite balance but they velocity is not perfectly equal).

That being said, if this hypothesis is true fork_join_latency should be dependent of n. Thus, increasing n also increase fork_join_latency. Here is was I can get with Clang 13 + IOMP (using -fopenmp -O3) on my 6-core i5-9600KF processor:

n=   80'000    fork_join_latency<0.000001
n=  800'000    fork_join_latency=0.000036
n= 8'000'000   fork_join_latency=0.000288
n=80'000'000   fork_join_latency=0.003236

Note that the fork_join_latency timings are not very stable in practice but the behavior is pretty visible: the measured overhead is dependent n.

A better solution is to measure the synchronization time by measuring the time of the loop for each thread and accumulate the difference between the minimum and maximum time. Here is an example of code:

double totalSyncTime = 0.0;

void action1(std::vector<double>& t1)
{
    constexpr int threadCount = 6;
    double timePerThread[threadCount] = {0};

    #pragma omp parallel
    {
        const double start = omp_get_wtime();
        #pragma omp for nowait schedule(static) //num_threads(std::thread::hardware_concurrency())
        #pragma nounroll
        for (auto index = std::size_t{}; index < t1.size(); ++index)
        {
            t1.data()[index] = std::sin(t1.data()[index]);
        }
        const double stop = omp_get_wtime();
        const double threadLoopTime = (stop - start);
        timePerThread[omp_get_thread_num()] = threadLoopTime;
    }

    const double mini = *std::min_element(timePerThread, timePerThread+threadCount);
    const double maxi = *std::max_element(timePerThread, timePerThread+threadCount);
    const double syncTime = maxi - mini;
    totalSyncTime += syncTime;
}

You can then divide totalSyncTime the same way you did for fork_join_latency and print the result. I get 0.000284 with fork_join_latency=0.000398 (with n=8'000'000) which almost proves that a major part of the overhead is due to synchronizations and more especially due to a slightly different thread execution velocity. Note that this overhead does not include the implicit barrier at the end of the OpenMP parallel section.


问:
Outer overflow div does not adjust size with scale
I have an outer div with a fixed size that uses a scroll for overflow. In it there is an inner div which is larger than the outer div. Therefore the overflow can be accessed by scrolling. This works without scaling as one would expect.

With a scaling on the inner div enabled, e. g. 0.7. The inner div is scaled down as expected. However, the scroll does not decrease in size as I would expect. There is space around the div which I can see by scrolling.

How can I fix this? Thank you very much.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.
</p>

<div class="outer">
  <div class="inner"></div>
</div>

<p>
  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.
</p>

<b>How can I fix this to adjust the size?</b>

<div class="outer">
  <div class="inner inner-scaled"></div>
</div></code>```

答:
Thank you both, with the other thread I found a solution. What I wanted was this:

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.intermediate{
    width: 702px;
    height: 702px;
    overflow: hidden;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  border: dotted #ccc 2px;
  transform: scale(0.7);
  transform-origin: 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Basically adding an intermediate div with overflow hidden does the trick. However, if the new scaling size is not known, a solution for the problem can involve javascript.</b>

<div class="outer">
 <div class="intermediate">
  <div class="inner inner-scaled"></div>
 </div>
</div></code>```

Body:
I have an outer div with a fixed size that uses a scroll for overflow. In it there is an inner div which is larger than the outer div. Therefore the overflow can be accessed by scrolling. This works without scaling as one would expect.

With a scaling on the inner div enabled, e. g. 0.7. The inner div is scaled down as expected. However, the scroll does not decrease in size as I would expect. There is space around the div which I can see by scrolling.

How can I fix this? Thank you very much.

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  transform: scale(0.7);
  transform-origin: 0 0;
}

  When I do not scale, the whole outer div is filled with the inner div. Scrolling works as expected and the red element fills all the space in the scroll.

  When I scale down, I see that the inner red element is smaller, as I would expect. However, I would also expect, that the outer div scaling range adjusts to the new size. This does not seem to be the case, as a white space around the element within the
  scroll exists.

How can I fix this to adjust the size?

Body:
Thank you both, with the other thread I found a solution. What I wanted was this:

.outer {
  overflow: scroll;
  width: 300px;
  height: 300px;
}

.intermediate{
    width: 702px;
    height: 702px;
    overflow: hidden;
}

.inner {
  width: 1000px;
  height: 1000px;
  background-color: brown;
}

.inner-scaled {
  border: dotted #ccc 2px;
  transform: scale(0.7);
  transform-origin: 0 0;
}

<b>Basically adding an intermediate div with overflow hidden does the trick. However, if the new scaling size is not known, a solution for the problem can involve javascript.</b>

<div class="outer">
 <div class="intermediate">
  <div class="inner inner-scaled"></div>
 </div>
</div>


问:
uncaught TypeError: Cannot read property 'call' of undefined using jQuery validation
i tried to apply validation system use jQuery for upload image and multiple images, check file extension and file size but it gives me error uncaught TypeError: Cannot read property 'call' of undefined

hi, i tried to apply validation system use jQuery for upload image and multiple images, check file extension and file size but it gives me error uncaught TypeError: Cannot read property 'call' of undefined

 $(document).ready(function () {
    jQuery.validator.setDefaults({
            debug: true,
            success: "valid"
          });
          $("#myform").validate({
            rules: {
              "image": {
                  extension: "jpg|jpeg|png|gif",
                  filesize:    "2048"
              },
              "images[]": {
                  extension: "jpg|jpeg|png|gif",
                  filesize:    "2048"
              },

            }
          });

});  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>rules</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    </head>
    <body>
    <div class="container">
        <form id="myform">

        <div class="form-group" id="divim">
            <label>image annonce<span class="text-hightlight">*</span></label>
            <input type="file" name="image" class="form-control @error('image') is-invalid @enderror" required autocomplete="image">
        </div>
        <div class="form-group" id="divims">
            <label>images annonce<span class="text-hightlight">*</span></label>
            <input type="file" name="images[]" class="form-control @error('images') is-invalid @enderror" required autocomplete="images" multiple>
        </div>

        <button class="btn btn-theme">valider</button>
        </form>
     </div>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    </body>
    </html></code>```

答:
Add this code to your additional-methods.js file.</p>
```<code>$.validator.addMethod('fileSize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'default message');
</code>```

Body:
i tried to apply validation system use jQuery for upload image and multiple images, check file extension and file size but it gives me error uncaught TypeError: Cannot read property 'call' of undefined

hi, i tried to apply validation system use jQuery for upload image and multiple images, check file extension and file size but it gives me error uncaught TypeError: Cannot read property 'call' of undefined

 $(document).ready(function () {
    jQuery.validator.setDefaults({
            debug: true,
            success: "valid"
          });
          $("#myform").validate({
            rules: {
              "image": {
                  extension: "jpg|jpeg|png|gif",
                  filesize:    "2048"
              },
              "images[]": {
                  extension: "jpg|jpeg|png|gif",
                  filesize:    "2048"
              },

            }
          });

});

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>rules</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <form id="myform">

            image annonce*
            <input type="file" name="image" class="form-control @error('image') is-invalid @enderror" required autocomplete="image">

            images annonce*
            <input type="file" name="images[]" class="form-control @error('images') is-invalid @enderror" required autocomplete="images" multiple>

        <button class="btn btn-theme">valider</button>
        </form>

Body:
Add this code to your additional-methods.js file.

$.validator.addMethod('fileSize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
}, 'default message');


问:
Whitch is faster? PHP explode or mysql join two tables on 2 ids where condition?
Let's say:

first case scenario: one table

products(product_id, title, description, ..., images);

but in field images we have images separated by '; '

Ex:
/23/25/3/flower1.jpg; /23/25/3/flower5.jpg; /23/25/3/flower7.jpg

if I make a simple mysql query,and then use php to explode, then I will have all images in one array and then to echo all images,

```<code>$images=explode('; ',$row['images']);
</code>```

second case 3tables necessary

products(product_id, title, descr, ...,);

images(image_id, imageurl);

products_images(products_images_id, product_id, image_id);

So, to get images for a specified product I need to do a mysql query with a join.

Can you prove witch case is faster to echo link images?

答:
If you always want to fetch the whole list of images, and never want to use SQL to do anything else with that list, then storing them in a semicolon-separated list is fine.

There are legitimate uses for denormalization. But be aware that you are optimizing for one task by making other tasks harder.

Think about how you would do tasks such as the following if the images are stored in a semicolon-separated list:

Search for a specific image

Add a new image to the list

Delete an image from the list

Fetch the list in sorted order

Count how many images in the list for a given product

Support a longer list of images than fits in one string column

Search for products that share a given image

Many other things you might think of doing

Then you should use the normalized table design and store one image per row.

Body:
Let's say:

first case scenario: one table

products(product_id, title, description, ..., images);

but in field images we have images separated by '; '

Ex:
/23/25/3/flower1.jpg; /23/25/3/flower5.jpg; /23/25/3/flower7.jpg

if I make a simple mysql query,and then use php to explode, then I will have all images in one array and then to echo all images,

$images=explode('; ',$row['images']);

second case 3tables necessary

products(product_id, title, descr, ...,);

images(image_id, imageurl);

products_images(products_images_id, product_id, image_id);

So, to get images for a specified product I need to do a mysql query with a join.

Can you prove witch case is faster to echo link images?


问:
How to add dropdown field and editable field inside a box?
I want to  add different controls(dropdown field and editable text field)inside a box as shown in image. How can I achieve this?

答:
Here you go. Working jsFiddle Example https://jsfiddle.net/utnw34d7/</p>
```<code>.wrapper {
  background-color: #eaeaea;
  box-shadow: 1px 2px 3px 0px;
}

.customBox {
  background-color: white;
  box-shadow: -1px 2px 3px -2px;
}

<div class="row m-4">
    <div class="col-12 border p-4 wrapper">
        <div class="row customBox">
            <label class="fw-bold col-form-label col-auto" for="select1">Dropdown 1:</label>
            <div class="col">
                <select id="select1" class="border-0 form-select">
                    <option>Select</option>
                    <option>...</option>
                </select>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="select2">Dropdown 2:</label>
            <div class="col">
                <select id="select2" class="border-0 form-select">
                    <option>Select</option>
                    <option>...</option>
                </select>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="text1">Label 1:</label>
            <div class="col">
                <input id="text1" class="border-0 form-control" type="text" value="label1">
            </div>
        </div>
        <div class="row">
            <div class="col-auto ms-auto">
                <a href="#" class="fw-bold text-dark text-decoration-none">+ Add New</a>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="text2">Label 2:</label>
            <div class="col">
                <input id="text2" class="border-0 form-control" type="text" value="label2">
            </div>
        </div>
        <div class="row">
            <div class="col-auto ms-auto">
                <a href="#" class="fw-bold text-dark text-decoration-none">+ Add New</a>
            </div>
        </div>
    </div>
</div>
<div class="row mt-4">
    <div class="col-auto mx-auto">
        <button class="btn btn-primary me-2">Button 1</button>
        <button class="btn btn-primary ms-2">Button 2</button>
    </div>
</div>
</code>```

Body:
Here you go. Working jsFiddle Example https://jsfiddle.net/utnw34d7/

.wrapper {
  background-color: #eaeaea;
  box-shadow: 1px 2px 3px 0px;
}

.customBox {
  background-color: white;
  box-shadow: -1px 2px 3px -2px;
}

<div class="row m-4">
    <div class="col-12 border p-4 wrapper">
        <div class="row customBox">
            <label class="fw-bold col-form-label col-auto" for="select1">Dropdown 1:</label>
            <div class="col">
                <select id="select1" class="border-0 form-select">
                    <option>Select</option>
                    <option>...</option>
                </select>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="select2">Dropdown 2:</label>
            <div class="col">
                <select id="select2" class="border-0 form-select">
                    <option>Select</option>
                    <option>...</option>
                </select>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="text1">Label 1:</label>
            <div class="col">
                <input id="text1" class="border-0 form-control" type="text" value="label1">
            </div>
        </div>
        <div class="row">
            <div class="col-auto ms-auto">
                <a href="#" class="fw-bold text-dark text-decoration-none">+ Add New</a>
            </div>
        </div>
        <div class="row customBox mt-3">
            <label class="fw-bold col-form-label col-auto" for="text2">Label 2:</label>
            <div class="col">
                <input id="text2" class="border-0 form-control" type="text" value="label2">
            </div>
        </div>
        <div class="row">
            <div class="col-auto ms-auto">
                <a href="#" class="fw-bold text-dark text-decoration-none">+ Add New</a>
            </div>
        </div>
    </div>
</div>
<div class="row mt-4">
    <div class="col-auto mx-auto">
        <button class="btn btn-primary me-2">Button 1</button>
        <button class="btn btn-primary ms-2">Button 2</button>
    </div>
</div>


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答:
We need to know what $check contains.. please provide more information.
in general it will work:

```<code>if (!empty($check)) {
    $insert  = "INSERT INTO tab (id,url) VALUES ('$id','$url')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

if $check is a boolean just do like this:

```<code>if ( $check ) {
    $insert  = "INSERT INTO tab (id,url) VALUES ('$id','$url')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

and perheps it works:

```<code>if ( $check == TRUE ) {
</code>```

ContentLicense: CC BY-SA 3.0

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

Body:
We need to know what $check contains.. please provide more information.
in general it will work:

if (!empty($check)) {
    $insert  = "INSERT INTO tab (id,url) VALUES ('$id','$url')";
    mysql_query($insert) or die(mysql_error());
}

if $check is a boolean just do like this:

if ( $check ) {
    $insert  = "INSERT INTO tab (id,url) VALUES ('$id','$url')";
    mysql_query($insert) or die(mysql_error());
}

and perheps it works:

if ( $check == TRUE ) {


问:
using same variable that is created in function into another function
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.</p>
```<code>lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

答:
You have to also tell go_back() to use the global variable:

```<code>def go_back():
   global number #add this
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

global tells the function to use the global number so each function has to be told this separately or it will default to using the local version.

Body:
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.

lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

Body:
You have to also tell go_back() to use the global variable:

def go_back():
   global number #add this
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

global tells the function to use the global number so each function has to be told this separately or it will default to using the local version.


问:
MongoDB Aggregation: How to get total records count?
I have used aggregation for fetching records from mongodb.

```<code>$result = $collection->aggregate(array(
  array('$match' => $document),
  array('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'),  'views' => array('$sum' => 1))),
  array('$sort' => $sort),
  array('$skip' => $skip),
  array('$limit' => $limit),
));
</code>```

If I execute this query without limit then 10 records will be fetched. But I want to keep limit as 2. So I would like to get the total records count. How can I do with aggregation? Please advice me. Thanks

答:
if you need to $match with nested documents then

https://mongoplayground.net/p/DpX6cFhR_mm

```<code>db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])
</code>```

Body:
I have used aggregation for fetching records from mongodb.

$result = $collection->aggregate(array(
  array('$match' => $document),
  array('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'),  'views' => array('$sum' => 1))),
  array('$sort' => $sort),
  array('$skip' => $skip),
  array('$limit' => $limit),
));

If I execute this query without limit then 10 records will be fetched. But I want to keep limit as 2. So I would like to get the total records count. How can I do with aggregation? Please advice me. Thanks

Body:
if you need to $match with nested documents then

https://mongoplayground.net/p/DpX6cFhR_mm

db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Canada"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])


问:
Problem looping through web controls
I've got a web page where I am dynamically creating controls during Page_Load event (this is done so because I do not know how many controls I will need until session is active and certain variables are accessible)

I need to be able to loop through these controls to find Checkbox when a button click is processed. Looping through the Form.Controls does not appear to be sufficient. I would think that Request.Form might work but it does not appear to be accessible in my C# block?

What should code for Request.Form look like? OR

Has anyone done this before with dynamically created controls?

Any insight is appreciated.

答:
Your controls will be accessible trough the Controls collection of their immediate parent. Unless you add them like Page.Form.Controls.Add (myControl);, you won't find it in Page.Form.Conttrols. If you add them to a place holder, you must find them in thePlaceHolder.Controls.

```<code>LinkButton myDynamicLinkButton = new myDynamicLinkButton ();
myDynamicLinkButton.ID = "lnkButton";

myPlaceHolder.Controls.Add (myDynamicLinkButton);

//........

LinkButton otherReferenceToMyLinkButton = myPlaceHolder.FindControl ("lnkButton");
</code>```

As @David said in his comment, you should probably think about using a Repeater instead. It would probably simplify your case a lot.

Title: Problem looping through web controls

Body:
Your controls will be accessible trough the Controls collection of their immediate parent. Unless you add them like Page.Form.Controls.Add (myControl);, you won't find it in Page.Form.Conttrols. If you add them to a place holder, you must find them in thePlaceHolder.Controls.

LinkButton myDynamicLinkButton = new myDynamicLinkButton ();
myDynamicLinkButton.ID = "lnkButton";

myPlaceHolder.Controls.Add (myDynamicLinkButton);

//........

LinkButton otherReferenceToMyLinkButton = myPlaceHolder.FindControl ("lnkButton");

As @David said in his comment, you should probably think about using a Repeater instead. It would probably simplify your case a lot.


答:
Use global number in both of your functions:

```<code>lst_img=[img0,img1,img2,img3,img4]

number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   global number
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1
</code>```

Title: using same variable that is created in function into another function

Body:
Use global number in both of your functions:

lst_img=[img0,img1,img2,img3,img4]

number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   global number
   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1


问:
Need a regex to modify a second match and ignore the first and last
Library context, using MarcEdit which can also use regex.

I need this:

```<code>=773 \\$tEtudes inuit$x0701-1008$1Vol. 44 1-2, $2p. 53-84
</code>```

to be changed to this:

```<code>=773  \\$tEtudes inuit$x0701-1008$1Vol. 44, no. 1-2, $2p. 53-84
</code>```

Problem is, the 44 in this case and the 1-2 are numbers that will change from one book to the other and I am building commands to automate it.

I tried focusing on changing the space between the 44 and the 1-2 into a ', no. ' with \s but it obiviously changes all spaces characters.

The adding ', no. ' is easy because there is a different box for it but I can't focus on the 2nd space while ignoring the first and last and also keeping every characters before and after.

Thank you for helping, I've been looking/trying all day!

MarcEdit exemple

答:
If the regular expression implementation supports look ahead, you can require that this space is followed by a range and a comma:

Find: \s(?=\d+-\d+,)

Replace: , no.

Body:
Library context, using MarcEdit which can also use regex.

I need this:

=773 \\$tEtudes inuit$x0701-1008$1Vol. 44 1-2, $2p. 53-84

to be changed to this:

=773  \\$tEtudes inuit$x0701-1008$1Vol. 44, no. 1-2, $2p. 53-84

Problem is, the 44 in this case and the 1-2 are numbers that will change from one book to the other and I am building commands to automate it.

I tried focusing on changing the space between the 44 and the 1-2 into a ', no. ' with \s but it obiviously changes all spaces characters.

The adding ', no. ' is easy because there is a different box for it but I can't focus on the 2nd space while ignoring the first and last and also keeping every characters before and after.

Thank you for helping, I've been looking/trying all day!

MarcEdit exemple


问:
I'm a beginner in Java so have struck in problem. What does (i +1) mean in the statement of a for loop for creating matrix program?
Like I have some example about my question, it goes somthing like this:

```<code>for (int i = 0; i < m; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");
</code>```

In above last line => + (i+1) +

答:
It is appending the value of i + 1 to a string then appending  : to that result. So it would end up printing

```<code>Enter Row 1 :
Enter Row 2 :
Enter Row 3 :
</code>```

The reason for the parentheses is because of precedence. Without them you would append i, then append 1 resulting in

```<code>Enter Row 01 :
Enter Row 11 :
Enter Row 21 :
</code>```

Body:
Like I have some example about my question, it goes somthing like this:

for (int i = 0; i < m; i++) {
            System.out.println("Enter Row "+ (i+1) + " :");

In above last line => + (i+1) +

Body:
It is appending the value of i + 1 to a string then appending  : to that result. So it would end up printing

Enter Row 1 :
Enter Row 2 :
Enter Row 3 :

The reason for the parentheses is because of precedence. Without them you would append i, then append 1 resulting in

Enter Row 01 :
Enter Row 11 :
Enter Row 21 :


问:
Return asynchronous data from an angular method
I am fairly new to angular and am still trying to wrap my head around doing things the angular + httpClient + rxjs way. I am trying to write the rxjs equivalent of the following:

```<code>
async onButtonClick = () => {
    const processedBooks = await this.getAndProcessBooks();
    await myGenericHttpClient.post('/api/something', processedBooks);
}

async getAndProcessBooks = () => {
    const books = await myGenericHttpClient.get('/api/books');

    const processedBooks = books.map(book => {
        return book.read = true;
    });

    return books;
};

</code>```

My understanding of rxjs is i need to use angular's httpClient to make the request then subscribe to the response:

```<code>getAndProcessBooks = () => {
    return httpClient.get('/api/books').subscribe(books => {
        return books;
    });
};

</code>```

However, the problem is getAndProcessBooks returns a subscription, not an array of books so I'm not sure how this method can return the data that I need. Any help or direction to resources would be appreciated!

答:
You can take the result from one API call and send it to another API call using the different map operators such as mergeMap, concatMap, etc of RxJs, which ever suits your use case.

I separated your HTTP calls and created functions for them just for easy readability.

//Returns Books
getAndProcessBooks(): Observable<any> {
    return this.myGenericHttpClient.get('/api/books');
}

//API something that requires books to send call
apiSomethingFunction(processedBooks: any): Observable<any> {
   return this.myGenericHttpClient.post('/api/something', processedBooks);
}

//On the button click
 onButtonClick(): void {
    this.getAndProcessBooks()
      .pipe(
        switchMap((books) => {
          //Response of books comes here, you can map them before sending it to the something API
          return this.apiSomethingFunction(books);
        })
      )
      .subscribe((resp) => {
        console.log(resp);
        console.log('I got Response of API Something');
      });
  }
```

The reason I used switchMap operator was to cancel the previous HTTP call if the user clicks on the button again. You can use different map if your use-case is different.

Body:
I am fairly new to angular and am still trying to wrap my head around doing things the angular + httpClient + rxjs way. I am trying to write the rxjs equivalent of the following:

async onButtonClick = () => {
    const processedBooks = await this.getAndProcessBooks();
    await myGenericHttpClient.post('/api/something', processedBooks);
}

async getAndProcessBooks = () => {
    const books = await myGenericHttpClient.get('/api/books');

    const processedBooks = books.map(book => {
        return book.read = true;
    });

    return books;
};

My understanding of rxjs is i need to use angular's httpClient to make the request then subscribe to the response:

getAndProcessBooks = () => {
    return httpClient.get('/api/books').subscribe(books => {
        return books;
    });
};

However, the problem is getAndProcessBooks returns a subscription, not an array of books so I'm not sure how this method can return the data that I need. Any help or direction to resources would be appreciated!

Body:
You can take the result from one API call and send it to another API call using the different map operators such as mergeMap, concatMap, etc of RxJs, which ever suits your use case.

I separated your HTTP calls and created functions for them just for easy readability.

//Returns Books
getAndProcessBooks(): Observable<any> {
    return this.myGenericHttpClient.get('/api/books');
}

//API something that requires books to send call
apiSomethingFunction(processedBooks: any): Observable<any> {
   return this.myGenericHttpClient.post('/api/something', processedBooks);
}

//On the button click
 onButtonClick(): void {
    this.getAndProcessBooks()
      .pipe(
        switchMap((books) => {
          //Response of books comes here, you can map them before sending it to the something API
          return this.apiSomethingFunction(books);
        })
      )
      .subscribe((resp) => {
        console.log(resp);
        console.log('I got Response of API Something');
      });
  }

The reason I used switchMap operator was to cancel the previous HTTP call if the user clicks on the button again. You can use different map if your use-case is different.


问:
Load 600+ million records in Synapse Dedicated Pool with Oracle as Source
I am trying to do a full load a very huge table (600+ million records) which resides in an Oracle On-Prem database. My destination is Azure Synapse Dedicated Pool.

I have already tried following:

Using ADF Copy activity with Source Partitioning, as source table is having 22 partitions

I increased the Copy Parallelism and DIU to a very high level

Still, I am able to fetch only 150 million records in 3 hrs whereas the ask is to complete the full load in around 2 hrs as the source would be freezed to users during that time frame so that Synapse can copy the data

How a full copy of data can be done from Oracle to Synapse in that time frame?

For a change, I tried loading data from Oracle to ADLS Gen 2, but its slow as well

答:
There are a number of factors to consider here.  Some ideas:

how fast can the table be read?  What indexing / materialized views are in place?  Is there any contention at the database level to rule out?

Recommendation: ensure database is set up for fast read on the table you are exporting

as you are on-premises, what is the local network card setup and throughput?

Recommendation: ensure local network setup is as fast as possible

as you are on-premises, you must be using a Self-hosted Integration Runtime (SHIR).  What is the spec of this machine?  eg 8GB RAM, SSD for spooling etc as per the minimum specification.  Where is this located?  eg 'near' the datasource (in the same on-premises network) or in the cloud.  It is possible to scale out SHIRs by having up to four nodes but you should ensure via the metrics available to you that this is a bottleneck before scaling out.

Recommendation: consider locating the SHIR 'close' to the datasource (ie in the same network)

is the SHIR software version up-to-date?  This gets updated occasionally so it's good practice to keep it updated.

Recommendation: keep the SHIR software up-to-date

do you have Express Route or going across the internet?  ER would probably be faster

Recommendation: consider Express Route.  Alternately consider Data Box for a large one-off export.

you should almost certainly land directly to ADLS  Gen 2 or blob storage.  Going straight into the database could result in contention there and you are dealing with Synapse concepts such as transaction logging, DWU, resource class and queuing contention among others.  View the metrics for the storage in the Azure portal to determine it is under stress.  If it is under stress (which I think unlikely), consider multiple storage accounts

Recommendation: load data to ADLS2.  Although this might seem like an extra step, it provides a recovery point and avoids contention issues by attempting to do the extract and load all at the same time.  I would only load directly to the database if you can prove it goes faster and you definitely don't need the recovery point

what format are you landing in the lake?  Converting to parquet is quite compute intensive for example.  Landing to the lake does leave an audit trail and give you a position to recover from if things go wrong

Recommendation: use parquet for a compressed format.  You may need to optimise the file size.

ultimately the best thing to do would be one big bulk load (say taking the weekend) and then do incremental upserts using a CDC mechanism.  This would allow you to meet your 2 hour window.

Recommendation: consider a one-off big bulk load and CDC / incremental loads to stay within the timeline

In summary, it's probably your network but you have a lot of investigation to do first, and then a number of options I've listed above to work through.


问:
How to workaround the 100 active connections limit between each Cloud Run container and Cloud SQL instance
I use Cloud Run and connect to Cloud SQL via the native connector, where I just specify the instance connection name and Cloud Run exposes it inside as a UNIX socket. The problem is that there is a limit of 100 active SQL connections imposed on each Cloud Run container instance.

My only question is: If I, instead, use a VPC serverless access connector and through that connect Cloud Run to the Cloud SQL instance via internal IP, would the limit continue to be imposed? Wouldn't this limit just be imposed on the Cloud Run native SQL connector?

答:
That limit is only due to the Cloud Run Cloud SQL connector. You can use a serverless VPC connector and go beyond that limit.

But Cloud SQL has a also a limit in number of connections and I'm not sure that opening so much connection on only one Cloud Run instance is a good choice.

In addition, if you use connection pool, you can reuse your connections easily and it could be better to scale horizontally with Cloud Run, instead of having only 1 big CLoud Run instance with thousands of connections to a database.