问:
Replace items in a list ansible playbook
I have the following dictionary:

{
  "test1": ["300m","","0","4","1050m"],
  "test2": ["600m","","","0","2"]
}
```
<p>I would execute a replacement over the items of the above lists and tried this:</p>
<pre class="lang-yaml prettyprint-override"><code>- set_fact:
    result: "{{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}"
  with_items: "{{dict_ns_cpu | dict2items}}"
  ignore_errors: true
</code>```

With the values of the list:

If the value ends with m, I want to remove it and divide the value per 1000.

If the value is only a number, multiply per 1000

I get the following error:

"msg": "Unexpected templating type error occurred on ({{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}): unhashable type: 'slice'"

Could anyone help me?

答:
If you literally want to replace an 'm' with '000' when the 'm' is preceded by a digit and succeeded by a " you could do:

\d(m)"

Body:
I have the following dictionary:

{
  "test1": ["300m","","0","4","1050m"],
  "test2": ["600m","","","0","2"]
}

I would execute a replacement over the items of the above lists and tried this:

- set_fact:
    result: "{{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}"
  with_items: "{{dict_ns_cpu | dict2items}}"
  ignore_errors: true

With the values of the list:

If the value ends with m, I want to remove it and divide the value per 1000.

If the value is only a number, multiply per 1000

I get the following error:

"msg": "Unexpected templating type error occurred on ({{result | default({}) | combine( { item.key: item.value | map((item is match('.*m'))|ternary(item[:-1]|int / 1000, item|int * 1000)) | list} ) }}): unhashable type: 'slice'"

Could anyone help me?


来源: stackexchange

问:
Nested Json Object Into Array
I'm trying to access a nested json array

```<code>        var jsonResponse:Object = JSON.decode(response);
        var foo:Object = JSON.decode(jsonResponse.nested);
        var bar:Array = foo as Array;
</code>```

When i inspect foo - its an object with about 50 children objects.

I can read the properties of the children objects.

However, when i cast foo as an Array it comes back null.

I'd prefer to not iterate over each object and push it into an array.

Any advice?

答:
You could decode the JSON right into an Array instead of Object, like this:

```<code>var jsonResponse:Array = JSON.decode(response);
var foo:Array = JSON.decode(jsonResponse.nested);
</code>```

Have a look at this question:
AS3 JSON parsing

ContentLicense: CC BY-SA 3.0

Title: Nested Json Object Into Array

Body:
I'm trying to access a nested json array

        var jsonResponse:Object = JSON.decode(response);
        var foo:Object = JSON.decode(jsonResponse.nested);
        var bar:Array = foo as Array;

When i inspect foo - its an object with about 50 children objects.

I can read the properties of the children objects.

However, when i cast foo as an Array it comes back null.

I'd prefer to not iterate over each object and push it into an array.

Any advice?

Body:
You could decode the JSON right into an Array instead of Object, like this:

var jsonResponse:Array = JSON.decode(response);
var foo:Array = JSON.decode(jsonResponse.nested);

Have a look at this question:
AS3 JSON parsing


问:
Evenly space StackPanel children to fill remaining space
I have a StackPanel in WPF that contains Labels and TextBoxes, the StackPanel's orientation is Vertical. I'm looking to have the children spaced evenly amongst the remaining height of the StackPanel, or maybe some dynamic padding or something between each UI element and I'm not sure how to do this.

This is what it currently looks like:

```<code><StackPanel Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
    <Label>Template Name:</Label>
    <TextBox x:Name="templateNameTextBox"></TextBox>
    <Label>Object Name:</Label>
    <TextBox x:Name="objectNameTextBox"></TextBox>
    <Label>Custom Name:</Label>
    <TextBox x:Name="customNameTextBox"></TextBox>
</StackPanel>
</code>```

There is just a ton of empty space below the last TextBox. I know I'll probably have to put each Label and corresponding TextBox in their own panel at some point so that they're grouped, but I haven't bothered with that until I figure out the spacing. I just don't want to have to put static values for each one to get them spaced properly, if possible.

Solved:

Thank you, I wasn’t thinking about them being in their own row when you mentioned a grid, that makes sense and is clear now that you mentioned it. The uniform grid should work as they all do need to be evenly spaced. I haven’t yet used a uniformgrid and didn’t know that’s what they were for, so thank you for leading me to them, I think that’s what I will opt for.

答:
In order to distribute the space evenly, you could use a Grid with the default star-sizing (* for each row).

Columns and rows that are defined within a Grid can take advantage of Star sizing to distribute remaining space proportionally. When Star is selected as the height or width of a row or column, that column or row receives a weighted proportion of the remaining available space.

It could look like this (I added StackPanels to group labels and text boxes).

```<code><Grid Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
   <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
      <RowDefinition/>
   </Grid.RowDefinitions>
   <StackPanel Grid.Row="0"
               VerticalAlignment="Center">
      <Label>Template Name:</Label>
      <TextBox x:Name="templateNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel Grid.Row="1"
               VerticalAlignment="Center">
      <Label>Object Name:</Label>
      <TextBox x:Name="objectNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel Grid.Row="2"
               VerticalAlignment="Center">
      <Label>Custom Name:</Label>
      <TextBox x:Name="customNameTextBox"></TextBox>
   </StackPanel>
</Grid>
</code>```

Since the distribution should be equal for all elements, you could alternatively use a UniformGrid.

```<code><UniformGrid Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
   <StackPanel VerticalAlignment="Center">
      <Label>Template Name:</Label>
      <TextBox x:Name="templateNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel VerticalAlignment="Center">
      <Label>Object Name:</Label>
      <TextBox x:Name="objectNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel VerticalAlignment="Center">
      <Label>Custom Name:</Label>
      <TextBox x:Name="customNameTextBox"></TextBox>
   </StackPanel>
</UniformGrid>-->
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a StackPanel in WPF that contains Labels and TextBoxes, the StackPanel's orientation is Vertical. I'm looking to have the children spaced evenly amongst the remaining height of the StackPanel, or maybe some dynamic padding or something between each UI element and I'm not sure how to do this.

This is what it currently looks like:

<StackPanel Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
    Template Name:
    <TextBox x:Name="templateNameTextBox"></TextBox>
    Object Name:
    <TextBox x:Name="objectNameTextBox"></TextBox>
    Custom Name:
    <TextBox x:Name="customNameTextBox"></TextBox>
</StackPanel>

There is just a ton of empty space below the last TextBox. I know I'll probably have to put each Label and corresponding TextBox in their own panel at some point so that they're grouped, but I haven't bothered with that until I figure out the spacing. I just don't want to have to put static values for each one to get them spaced properly, if possible.

Solved:

Thank you, I wasn’t thinking about them being in their own row when you mentioned a grid, that makes sense and is clear now that you mentioned it. The uniform grid should work as they all do need to be evenly spaced. I haven’t yet used a uniformgrid and didn’t know that’s what they were for, so thank you for leading me to them, I think that’s what I will opt for.

Body:
In order to distribute the space evenly, you could use a Grid with the default star-sizing (* for each row).

Columns and rows that are defined within a Grid can take advantage of Star sizing to distribute remaining space proportionally. When Star is selected as the height or width of a row or column, that column or row receives a weighted proportion of the remaining available space.

It could look like this (I added StackPanels to group labels and text boxes).

<Grid Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
   <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
      <RowDefinition/>
   </Grid.RowDefinitions>
   <StackPanel Grid.Row="0"
               VerticalAlignment="Center">
      <Label>Template Name:</Label>
      <TextBox x:Name="templateNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel Grid.Row="1"
               VerticalAlignment="Center">
      <Label>Object Name:</Label>
      <TextBox x:Name="objectNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel Grid.Row="2"
               VerticalAlignment="Center">
      <Label>Custom Name:</Label>
      <TextBox x:Name="customNameTextBox"></TextBox>
   </StackPanel>
</Grid>

Since the distribution should be equal for all elements, you could alternatively use a UniformGrid.

<UniformGrid Margin="10 0" Grid.Row="1" Grid.RowSpan="3" Grid.Column="1">
   <StackPanel VerticalAlignment="Center">
      <Label>Template Name:</Label>
      <TextBox x:Name="templateNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel VerticalAlignment="Center">
      <Label>Object Name:</Label>
      <TextBox x:Name="objectNameTextBox"></TextBox>
   </StackPanel>
   <StackPanel VerticalAlignment="Center">
      <Label>Custom Name:</Label>
      <TextBox x:Name="customNameTextBox"></TextBox>
   </StackPanel>
</UniformGrid>-->


问:
LINQ Group By and merge properties
```<code>private static void Main()
{
    var accounts = new List<Account>()
    {
    new Account { PrimaryId = 1, SecondaryId = 10 },
    new Account { PrimaryId = 1, SecondaryId = 12 }
    };
}

public class Account
{
    public int PrimaryId { get; set; }
    public IList<int> SecondaryIds { get; set; }
    public int SecondaryId { get; set; }
}
</code>```

Suppose I have the above code, I would like to group by PrimaryId and merge SecondaryId into SecondaryIds.

For example:

```<code>// PrimaryId = 1
// SecondaryIds = 10, 12
</code>```

How can achieve it?

I did this so far

```<code>var rs = accounts.GroupBy(g => g.PrimaryId == 1)
.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });
</code>```

答:
When using .GroupBy() followed by .Select(), you need to drill down one level inside your grouped items:

```<code>var rs = accounts
    .GroupBy(a => a.PrimaryId)
    .Select(gr => new Account {
        PrimaryId = gr.Key,
        SecondaryIds = gr.Select(account => account.SecondaryId).ToList()
    });
</code>```

Title: LINQ Group By and merge properties

Body:
private static void Main()
{
    var accounts = new List<Account>()
    {
    new Account { PrimaryId = 1, SecondaryId = 10 },
    new Account { PrimaryId = 1, SecondaryId = 12 }
    };
}

public class Account
{
    public int PrimaryId { get; set; }
    public IList<int> SecondaryIds { get; set; }
    public int SecondaryId { get; set; }
}

Suppose I have the above code, I would like to group by PrimaryId and merge SecondaryId into SecondaryIds.

For example:

// PrimaryId = 1
// SecondaryIds = 10, 12

How can achieve it?

I did this so far

var rs = accounts.GroupBy(g => g.PrimaryId == 1)
.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });

Body:
When using .GroupBy() followed by .Select(), you need to drill down one level inside your grouped items:

var rs = accounts
    .GroupBy(a => a.PrimaryId)
    .Select(gr => new Account {
        PrimaryId = gr.Key,
        SecondaryIds = gr.Select(account => account.SecondaryId).ToList()
    });


答:
What I'd do, perhaps

LINQ GroupBy in its simplest form, takes a lambda that returns the Key that shall be grouped by. .GroupBy(a => a.PrimaryId). It produces something like a "list of lists", where everything in the inner list has the same key.

If you did that grouping you could explore it like this:

```<code>var listOfLists = accounts.GroupBy(a => a.PrimaryId);

foreach(var innerList in listOfLists){
  Console.WriteLine("Key is: " + innerList.Key);

  foreach(Account account in innerList)
    Console.WriteLine("Sid is: " + account.SecondaryId);
}
</code>```

So it's effectively put your Account objects into something like a List<List<Account>>, except the inner list has a Key property that tells you what common value (the PrimaryId) the accounts in the inner list all share

There's an extended form of GroupBy that takes a second argument of "what item, possibly from the original objects, do you want to put into the inner list?", and we could use that like this:

```<code>.GroupBy(a => a.PrimaryId, a => a.SecondaryId)
</code>```

This would create something like a List<List<int>> because instead of the whole account object, it's just pulling the SecondaryId out and putting that in the inner list. This is fine because you can still get the PrimaryId from the Key and there isn't anything else in an Account

There's actually even another form of GroupBy with a third argument that will take each item in the resulting "list of lists" and allow you to do something with that..

```<code>.GroupBy(
  a => a.PrimaryId,     //derive the key
  a => a.SecondaryId,   //derive the innerList
  (key, innerList) => new Account { PrimaryId = key, SecondaryIds = innerList.ToList() }
)
</code>```

You can think of this third argument as being like the .Select() you've put on the end of the groupby. It's slightly different, and perhaps a bit easier to use because of that clear separation between "the key" and "the list of things with that key"

So, the first argument (key, is the grouping key (the PrimaryID), and the second argument innerList) is the list of all the SecondaryIds with that grouping key. We can use these two bits of info to make a new Account object with the Primary and SecondaryIds set

I mentioned in the comments that it's weird to have a single SecondaryId and also a list of them in one object.. I know why you've done it, but if you wanted to drop the SecondaryId singular and just keep the list, the groupby would change slighty:

```<code>.GroupBy(
  a => a.PrimaryId,
  a => a.SecondaryId.First(),   //take the only item
  (key, innerList) => new Account { PrimaryId = key, SecondaryIds = innerList.ToList() }
)
</code>```

This would be capable of processing a single item list of secondary IDs, for example something like this:

```<code>var accounts = new List<Account>()
{
  new Account { PrimaryId = 1, SecondaryIds = new(){10} },
  new Account { PrimaryId = 1, SecondaryIds = new(){12} }
};
</code>```

Taking a look at your attempt:

```<code>var rs = accounts.GroupBy(g => g.PrimaryId == 1)
.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });
</code>```

Doing .GroupBy(g => g.PrimaryId == 1) will group by an assessment of whether the PrimaryId is 1 or not. It won't filter anything to "just ID 1" - essentially anything that was PrimaryId 1 would go in one inner list, and everything else would go in another. The Key of the inner list would be a bool. If your accounts list only contained Account objects with Primary ID 1 then all would be fine. It'd go a bit haywire if it didn't

```<code>.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });
</code>```

Your GroupBy() with one argument has produced something like a List<List<Account>>, so it means s is the inner list. It's actually an IGrouping<Account> which is like a list of Account objects but with that extra Key property that tells you what all the items in the grouping have in common.

This means that, because this .Select is giving you s and s is a list of Account, and you want just the SecondaryId out of each account in that list, you need another Select, this time on s to pull just the SecondaryId out of each account within it:

```<code>.Select(s => new Accounts
{
  PrimaryId = 1,
  SecondaryIds = s.Select(acc => acc.SecondaryId)
});
</code>```

and then you want to call ToList() on that Select

```<code>.Select(s => new Accounts
{
  PrimaryId = 1,
  SecondaryIds = s.Select(acc => acc.SecondaryId).ToList()
});
</code>```

If I was doing that way I'd do:

```<code>.GroupBy(a => a.PrimaryId)
.Select(g => new Accounts
{
  PrimaryId = g.Key,
  SecondaryIds = g.Select(acc => acc.SecondaryId).ToList()
});
</code>```

But the 3 argument GroupBy is a bit cleaner..

Title: LINQ Group By and merge properties

Body:
What I'd do, perhaps

LINQ GroupBy in its simplest form, takes a lambda that returns the Key that shall be grouped by. .GroupBy(a => a.PrimaryId). It produces something like a "list of lists", where everything in the inner list has the same key.

If you did that grouping you could explore it like this:

var listOfLists = accounts.GroupBy(a => a.PrimaryId);

foreach(var innerList in listOfLists){
  Console.WriteLine("Key is: " + innerList.Key);

  foreach(Account account in innerList)
    Console.WriteLine("Sid is: " + account.SecondaryId);
}

So it's effectively put your Account objects into something like a List<List<Account>>, except the inner list has a Key property that tells you what common value (the PrimaryId) the accounts in the inner list all share

There's an extended form of GroupBy that takes a second argument of "what item, possibly from the original objects, do you want to put into the inner list?", and we could use that like this:

.GroupBy(a => a.PrimaryId, a => a.SecondaryId)

This would create something like a List<List<int>> because instead of the whole account object, it's just pulling the SecondaryId out and putting that in the inner list. This is fine because you can still get the PrimaryId from the Key and there isn't anything else in an Account

There's actually even another form of GroupBy with a third argument that will take each item in the resulting "list of lists" and allow you to do something with that..

.GroupBy(
  a => a.PrimaryId,     //derive the key
  a => a.SecondaryId,   //derive the innerList
  (key, innerList) => new Account { PrimaryId = key, SecondaryIds = innerList.ToList() }
)

You can think of this third argument as being like the .Select() you've put on the end of the groupby. It's slightly different, and perhaps a bit easier to use because of that clear separation between "the key" and "the list of things with that key"

So, the first argument (key, is the grouping key (the PrimaryID), and the second argument innerList) is the list of all the SecondaryIds with that grouping key. We can use these two bits of info to make a new Account object with the Primary and SecondaryIds set

I mentioned in the comments that it's weird to have a single SecondaryId and also a list of them in one object.. I know why you've done it, but if you wanted to drop the SecondaryId singular and just keep the list, the groupby would change slighty:

.GroupBy(
  a => a.PrimaryId,
  a => a.SecondaryId.First(),   //take the only item
  (key, innerList) => new Account { PrimaryId = key, SecondaryIds = innerList.ToList() }
)

This would be capable of processing a single item list of secondary IDs, for example something like this:

var accounts = new List<Account>()
{
  new Account { PrimaryId = 1, SecondaryIds = new(){10} },
  new Account { PrimaryId = 1, SecondaryIds = new(){12} }
};

Taking a look at your attempt:

var rs = accounts.GroupBy(g => g.PrimaryId == 1)
.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });

Doing .GroupBy(g => g.PrimaryId == 1) will group by an assessment of whether the PrimaryId is 1 or not. It won't filter anything to "just ID 1" - essentially anything that was PrimaryId 1 would go in one inner list, and everything else would go in another. The Key of the inner list would be a bool. If your accounts list only contained Account objects with Primary ID 1 then all would be fine. It'd go a bit haywire if it didn't

.Select(s => new Accounts
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });

Your GroupBy() with one argument has produced something like a List<List<Account>>, so it means s is the inner list. It's actually an IGrouping<Account> which is like a list of Account objects but with that extra Key property that tells you what all the items in the grouping have in common.

This means that, because this .Select is giving you s and s is a list of Account, and you want just the SecondaryId out of each account in that list, you need another Select, this time on s to pull just the SecondaryId out of each account within it:

.Select(s => new Accounts
{
  PrimaryId = 1,
  SecondaryIds = s.Select(acc => acc.SecondaryId)
});

and then you want to call ToList() on that Select

.Select(s => new Accounts
{
  PrimaryId = 1,
  SecondaryIds = s.Select(acc => acc.SecondaryId).ToList()
});

If I was doing that way I'd do:

.GroupBy(a => a.PrimaryId)
.Select(g => new Accounts
{
  PrimaryId = g.Key,
  SecondaryIds = g.Select(acc => acc.SecondaryId).ToList()
});

But the 3 argument GroupBy is a bit cleaner..


问:
Bootstrap modal not displaying
I've copied and pasted the example code from twitter bootstrap to create a basic modal window in my Rails 3.2 app:

```<code><!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <p>One fine body…</p>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

<a href= "#myModal"  role="button" class="btn" data-toggle="modal">Launch demo modal</a>
</code>```

It's not working.  It's not because of jQuery or scripts not loading because a) it doesn't need to load any js because its using data targeting and b) I've checked the console and everything is firing perfectly.

It's also not because I'm including both boostrap.js and bootstrap-modal.js...I've checked and I'm not.

I'm at a loss.  It should just work.  Other bootstrap js is working fine on the site.

The only thing I can think of is it's something to do with the definition of the classes .hide and .fade - when I take them out, the modal shows up fine.  When I include them, it won't show up at all.

Could jQuery UI be interfering with it?

Please ask me for any further info you might need to help me...

UPDATE:

So I think I see the problem, but I don't know how to fix it.  When I check the console, right at the top I see that

```<code>element.style {
display: none;
}
</code>```

is somehow now part of the div, so in the console it looks like this:

```<code><div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;" >
</code>```

But I don't know why it is adding it in, or where from.  How can I track this down?

Thanks

答:
I had the same problem. For me the cause was the use of Bootstrap 5 with outdated data-toogle and data-target attributes in the launch button:

After the correction of

```<code><button type="button" class="btn" data-toggle="modal" data-target="#myModal" >
</code>```

to

```<code><button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#myModal">
</code>```

it ran correctly.

Title: Bootstrap modal not displaying

Body:
I've copied and pasted the example code from twitter bootstrap to create a basic modal window in my Rails 3.2 app:

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal header

One fine body…

    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>

Launch demo modal

It's not working.  It's not because of jQuery or scripts not loading because a) it doesn't need to load any js because its using data targeting and b) I've checked the console and everything is firing perfectly.

It's also not because I'm including both boostrap.js and bootstrap-modal.js...I've checked and I'm not.

I'm at a loss.  It should just work.  Other bootstrap js is working fine on the site.

The only thing I can think of is it's something to do with the definition of the classes .hide and .fade - when I take them out, the modal shows up fine.  When I include them, it won't show up at all.

Could jQuery UI be interfering with it?

Please ask me for any further info you might need to help me...

UPDATE:

So I think I see the problem, but I don't know how to fix it.  When I check the console, right at the top I see that

element.style {
display: none;
}

is somehow now part of the div, so in the console it looks like this:

But I don't know why it is adding it in, or where from.  How can I track this down?

Thanks

Body:
I had the same problem. For me the cause was the use of Bootstrap 5 with outdated data-toogle and data-target attributes in the launch button:

After the correction of

<button type="button" class="btn" data-toggle="modal" data-target="#myModal" >

to

<button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#myModal">

it ran correctly.


问:
Debugging strapi in Visual Studio Code
I'm trying to debug my strapi project (3.0.0 beta 16.6) in VS Code.
My launch.json:

```<code>{
  "type": "node",
  "request": "attach",
  "name": "Attach to strapi",
  "port": 9229
}
</code>```

My package.json:

```<code>"scripts": {
    "debug": "node --inspect=127.0.0.1:9229 ./node_modules/strapi/bin/strapi.js develop"
}
</code>```

Debugger attaches to the process, but all my breakpoints become unverified (appear black, not red). What's wrong with my configs?

答:
This worked for me using Strapi v4</p>
```<code>{
    "version": "0.2.0",
    "configurations": [
     {
      "name": "STRAPI Debug",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceRoot}",
      "runtimeExecutable": "node",
      "runtimeVersion":"14.19.0",
      "runtimeArgs": ["--lazy"],
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceRoot}/node_modules/@strapi/strapi/bin/strapi.js",
      "args": [
        "develop"
      ],
      "protocol": "inspector",
      "env": {
        "NODE_ENV": "development"
      },
      "autoAttachChildProcesses": true,
      "console": "integratedTerminal"
     },
    ]
}
</code>```

Title: Debugging strapi in Visual Studio Code

Body:
I'm trying to debug my strapi project (3.0.0 beta 16.6) in VS Code.
My launch.json:

{
  "type": "node",
  "request": "attach",
  "name": "Attach to strapi",
  "port": 9229
}

My package.json:

"scripts": {
    "debug": "node --inspect=127.0.0.1:9229 ./node_modules/strapi/bin/strapi.js develop"
}

Debugger attaches to the process, but all my breakpoints become unverified (appear black, not red). What's wrong with my configs?

Body:
This worked for me using Strapi v4

{
    "version": "0.2.0",
    "configurations": [
     {
      "name": "STRAPI Debug",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceRoot}",
      "runtimeExecutable": "node",
      "runtimeVersion":"14.19.0",
      "runtimeArgs": ["--lazy"],
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceRoot}/node_modules/@strapi/strapi/bin/strapi.js",
      "args": [
        "develop"
      ],
      "protocol": "inspector",
      "env": {
        "NODE_ENV": "development"
      },
      "autoAttachChildProcesses": true,
      "console": "integratedTerminal"
     },
    ]
}


问:
find substring with special characters
I have pattern 'šalotka 29%'
and i need to know if string 'something something šalotka 29% something' contains the pattern
but not if the pattern is part of a longer word 'something something šalotka 29%something'

I have this mb_eregi('\b' . $pattern . '\b', $string)
but its not working because regex boundaries not working with special character.
Any suggestion?

答:
A word boundary matches only between a word character (a character from the \w character class) and a non-word character or the limit of the string.

If your searched string starts or ends with a non-word character, you can't use a word-boundary.

The difficulty is to define yourself precisely what separates the desired chain from the rest. In other words, it is your choice.
Whatever your choice is, you can use the same technique: using lookarounds before and after your string to define what you don't want around your string: a negative lookbehind (?<!...) and a negative lookahead (?!...).

Example:

to forbid all that isn't a whitespace around the string:

```<code>mb_eregi('(?<!\S)' . $item . '(?!\S)', $string, $match);
</code>```

to forbid all that isn't a word character:

```<code>mb_eregi('(?<!\w)' . $item . '(?!\w)', $string, $match);
</code>```

full example:

```<code>$item = 'šalotka 29%';
$string = 'something something šalotk 29% something';

mb_regex_encoding('UTF-8'); // be sure to use the correct encoding

// if needed escape regex special characters
$item = mb_eregi_replace('[\[\](){}.\\\\|$^?+*#-]', '\\\0', $item);

mb_eregi('(?<!\S)' . $item . '(?!\S)', $string, $matches);

print_r($matches);
</code>```

Notices:

If ereg functions are now obsolete and have been removed from recent PHP versions, mb_ereg functions, based on the oniguruma regex engine, still exist and offer features not available in preg_ functions (PCRE).

Obviously for this current question, you can do the same with preg_match:

```<code>preg_match('~(?<!\S)' . $item . '(?!\S)~ui', $string, $match);
</code>```

If don't have the control of the searched string (a user input for example), take care that this one doesn't contain special regex characters.
With preg_ functions you can use preg_quote to escape them, but it's also possible to "do it yourself" with $item = mb_ereg_replace('[\[\](){}.\\\\|$^?+*#-]', '\\\0', $item); that suffices for most of the syntaxes available in mb_ereg functions (Note that escaping all non-word characters does the job too). Feel free to write your own if you want to deal with Emacs or BRE syntaxes.

Title: find substring with special characters

Body:
A word boundary matches only between a word character (a character from the \w character class) and a non-word character or the limit of the string.

If your searched string starts or ends with a non-word character, you can't use a word-boundary.

The difficulty is to define yourself precisely what separates the desired chain from the rest. In other words, it is your choice.
Whatever your choice is, you can use the same technique: using lookarounds before and after your string to define what you don't want around your string: a negative lookbehind (?<!...) and a negative lookahead (?!...).

Example:

to forbid all that isn't a whitespace around the string:

mb_eregi('(?<!\S)' . $item . '(?!\S)', $string, $match);

to forbid all that isn't a word character:

mb_eregi('(?<!\w)' . $item . '(?!\w)', $string, $match);

full example:

$item = 'šalotka 29%';
$string = 'something something šalotk 29% something';

mb_regex_encoding('UTF-8'); // be sure to use the correct encoding

// if needed escape regex special characters
$item = mb_eregi_replace('[\[\](){}.\\\\|$^?+*#-]', '\\\0', $item);

mb_eregi('(?<!\S)' . $item . '(?!\S)', $string, $matches);

print_r($matches);

Notices:

If ereg functions are now obsolete and have been removed from recent PHP versions, mb_ereg functions, based on the oniguruma regex engine, still exist and offer features not available in preg_ functions (PCRE).

Obviously for this current question, you can do the same with preg_match:

preg_match('~(?<!\S)' . $item . '(?!\S)~ui', $string, $match);

If don't have the control of the searched string (a user input for example), take care that this one doesn't contain special regex characters.
With preg_ functions you can use preg_quote to escape them, but it's also possible to "do it yourself" with $item = mb_ereg_replace('[\[\](){}.\\\\|$^?+*#-]', '\\\0', $item); that suffices for most of the syntaxes available in mb_ereg functions (Note that escaping all non-word characters does the job too). Feel free to write your own if you want to deal with Emacs or BRE syntaxes.


问:
Creating pubsub subscription to topic failed with error: User not authorized to perform this action
When I try to deploy a dataflow job with a service account, it fails with the following error:

Workflow failed. Causes: Step
  "setup_resource_XXXXXX.subscription-1210256155950706891639" failed.,
  Step setup_resource_XXXXXX.subscription-1210256155950706891639: Set up
  of resource XXXXXX.subscription-12102561559507068916 failed, Creating
  pubsub subscription
  projects/XXXXXX/subscriptions/XXXXXX.subscription-12102561559507068916
  to topic projects/XXXXXX/topics/XXXXXX failed with error: User not
  authorized to perform this action.

I have given the service account "Pub/Sub Subscriber" permission for that topic.

答:
Following the suggestion of norbjb(Jun 3 '19 at 12:56), I have found that your Service Account need be granted:

Cloud Dataflow Service Agent

That solved the issue for me.


问:
How to get the current shop in shopify when using NodeJS (Public App)?
I am new to Shopify App Devlopment, especially the Shopify API.

I create a working app with the Shopify CLI and now want to communicate with the API.

I try to access following endpoint: https://{my_shop]/admin/api/2021-07/shop.json

I learned that I need some access token and the shop name to access this endpoint.

I created an access token under my private apps section.

But I dont know how to get the currently logged in store.

For example, when clicking a button in my frontend, I would like to call my endpoint, which in turn calls the Shopify API endpoint and retrieves the information. How do I do this the right way? And how do I get the currently logged in shop?

This is my code so far:

```<code>import "@babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "@shopify/shopify-api";
import Koa from "koa";
import next from "next";
import Router from "koa-router";
import axios from 'axios';

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8081;
const dev = process.env.NODE_ENV !== "production";
const app = next({
  dev,
});
const handle = app.getRequestHandler();

Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SCOPES.split(","),
  HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  // This should be replaced with your preferred storage strategy
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

// Storing the currently active shops in memory will force them to re-login when your server
restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(async () => {
  const server = new Koa();
  const router = new Router();
  server.keys = [Shopify.Context.API_SECRET_KEY];
  server.use(
    createShopifyAuth({
      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop, accessToken, scope } = ctx.state.shopify;
        const host = ctx.query.host;
        ACTIVE_SHOPIFY_SHOPS[shop] = scope;

        const response = await Shopify.Webhooks.Registry.register({
          shop,
          accessToken,
          path: "/webhooks",
          topic: "APP_UNINSTALLED",
          webhookHandler: async (topic, shop, body) =>
            delete ACTIVE_SHOPIFY_SHOPS[shop],
        });

        if (!response.success) {
          console.log(
            `Failed to register APP_UNINSTALLED webhook: ${response.result}`
          );
        }

        // Redirect to app with shop parameter upon auth
        ctx.redirect(`/?shop=${shop}&host=${host}`);
      },
    })
  );

  router.get("/test2", verifyRequest(), async(ctx, res) => {
    const {shop, accessToken } = ctx.session;
    console.log(shop);
    console.log(accessToken);
  })

  router.get("/test", async (ctx) => {

    const config = {
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': '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'
      }
    }

    await axios.get('${the_store_name_belongs_here}/admin/api/2021-07/shop.json', config).then(res => {
      ctx.body = res.data;
    });
  });

  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });

  router.post(
    "/graphql",
    verifyRequest({ returnHeader: true }),
    async (ctx, next) => {
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );

  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", async (ctx) => {
    const shop = ctx.query.shop;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});
</code>```

Please have a look at my attempts - endpoint /test and endpoint /test2.
test2 is not working. ctx.session is null. ctx itself is null. Why?

test1 is working when I hard code my shops name into the url, then I get the desired data. But how do I put a shop variable inside? That's my struggle.

答:
First of all, it is not good practice to use MemorySessionStorage in production environment due to its limitations, you can find a good explanation here

MemorySessionStorage exists as an option to help you get started
developing your apps as quickly as possible...

So, implement a CustomSessionStorage (refer to the doc above), you will have access to the session that stores data such as shop, accessToken, scope among others. As long as authenticated requests are made, providing the JWT in the header, you can get the context properly working.

e.g. (react-koa):

```<code>//client.js
import { useAppBridge } from "@shopify/app-bridge-react";
import { getSessionToken } from "@shopify/app-bridge-utils";

function Index() {
   const app = useAppBridge();

   async function getProducts() {
       const token = await getSessionToken(app);

       const response = await fetch("/api/products", {
           headers: { "Authorization": `Bearer ${token}` }
       });

       const result = await response.json();
       console.log(result);
   }

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

and then...

```<code>// server.js

router.get("/api/products", verifyRequest({ returnHeader: true }), async (ctx) => {
    // Load the current session to get the `accessToken`.
    // pass a third parameter clarifying the accessMode (isOnline = true by default)
    const session = await Shopify.Utils.loadCurrentSession(ctx.req, ctx.res);

    // Create a new client for the specified shop.
    const client = new Shopify.Clients.Rest(session.shop, session.accessToken);

    // Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`.
    const products = await client.get({
      path: 'products',
    });

    ctx.body = results.body;
    ctx.res.status = 200;
  });
</code>```

more details here.

Using axios, you can define it as a hook (working example using TypeScript):

```<code>import axios from 'axios';
import { useAppBridge } from '@shopify/app-bridge-react';
import { getSessionToken } from '@shopify/app-bridge-utils';

function useAxios() {
  const app = useAppBridge();
  const instance = axios.create();
  instance.interceptors.request.use(async function (config) {
    const token = await getSessionToken(app);
    config.headers['Authorization'] = `Bearer ${token}`;
    return config;
  });
  return [instance];
}

export default useAxios;

// index.js

// ...
const [axios] = useAxios();

// ...
const result = await axios.get('/api/products');
console.log(result.data);
// ...
</code>```

Hope this helps anyone who is still looking for help.

Body:
I am new to Shopify App Devlopment, especially the Shopify API.

I create a working app with the Shopify CLI and now want to communicate with the API.

I try to access following endpoint: https://{my_shop]/admin/api/2021-07/shop.json

I learned that I need some access token and the shop name to access this endpoint.

I created an access token under my private apps section.

But I dont know how to get the currently logged in store.

For example, when clicking a button in my frontend, I would like to call my endpoint, which in turn calls the Shopify API endpoint and retrieves the information. How do I do this the right way? And how do I get the currently logged in shop?

This is my code so far:

import "@babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "@shopify/shopify-api";
import Koa from "koa";
import next from "next";
import Router from "koa-router";
import axios from 'axios';

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8081;
const dev = process.env.NODE_ENV !== "production";
const app = next({
  dev,
});
const handle = app.getRequestHandler();

Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SCOPES.split(","),
  HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  // This should be replaced with your preferred storage strategy
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

// Storing the currently active shops in memory will force them to re-login when your server
restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(async () => {
  const server = new Koa();
  const router = new Router();
  server.keys = [Shopify.Context.API_SECRET_KEY];
  server.use(
    createShopifyAuth({
      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop, accessToken, scope } = ctx.state.shopify;
        const host = ctx.query.host;
        ACTIVE_SHOPIFY_SHOPS[shop] = scope;

        const response = await Shopify.Webhooks.Registry.register({
          shop,
          accessToken,
          path: "/webhooks",
          topic: "APP_UNINSTALLED",
          webhookHandler: async (topic, shop, body) =>
            delete ACTIVE_SHOPIFY_SHOPS[shop],
        });

        if (!response.success) {
          console.log(
            `Failed to register APP_UNINSTALLED webhook: ${response.result}`
          );
        }

        // Redirect to app with shop parameter upon auth
        ctx.redirect(`/?shop=${shop}&host=${host}`);
      },
    })
  );

  router.get("/test2", verifyRequest(), async(ctx, res) => {
    const {shop, accessToken } = ctx.session;
    console.log(shop);
    console.log(accessToken);
  })

  router.get("/test", async (ctx) => {

    const config = {
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': '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'
      }
    }

    await axios.get('${the_store_name_belongs_here}/admin/api/2021-07/shop.json', config).then(res => {
      ctx.body = res.data;
    });
  });

  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });

  router.post(
    "/graphql",
    verifyRequest({ returnHeader: true }),
    async (ctx, next) => {
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );

  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", async (ctx) => {
    const shop = ctx.query.shop;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

Please have a look at my attempts - endpoint /test and endpoint /test2.
test2 is not working. ctx.session is null. ctx itself is null. Why?

test1 is working when I hard code my shops name into the url, then I get the desired data. But how do I put a shop variable inside? That's my struggle.

Body:
First of all, it is not good practice to use MemorySessionStorage in production environment due to its limitations, you can find a good explanation here

MemorySessionStorage exists as an option to help you get started
developing your apps as quickly as possible...

So, implement a CustomSessionStorage (refer to the doc above), you will have access to the session that stores data such as shop, accessToken, scope among others. As long as authenticated requests are made, providing the JWT in the header, you can get the context properly working.

e.g. (react-koa):

//client.js
import { useAppBridge } from "@shopify/app-bridge-react";
import { getSessionToken } from "@shopify/app-bridge-utils";

function Index() {
   const app = useAppBridge();

   async function getProducts() {
       const token = await getSessionToken(app);

       const response = await fetch("/api/products", {
           headers: { "Authorization": `Bearer ${token}` }
       });

       const result = await response.json();
       console.log(result);
   }

   return (<></>);
}

and then...

// server.js

router.get("/api/products", verifyRequest({ returnHeader: true }), async (ctx) => {
    // Load the current session to get the `accessToken`.
    // pass a third parameter clarifying the accessMode (isOnline = true by default)
    const session = await Shopify.Utils.loadCurrentSession(ctx.req, ctx.res);

    // Create a new client for the specified shop.
    const client = new Shopify.Clients.Rest(session.shop, session.accessToken);

    // Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`.
    const products = await client.get({
      path: 'products',
    });

    ctx.body = results.body;
    ctx.res.status = 200;
  });

more details here.

Using axios, you can define it as a hook (working example using TypeScript):

import axios from 'axios';
import { useAppBridge } from '@shopify/app-bridge-react';
import { getSessionToken } from '@shopify/app-bridge-utils';

function useAxios() {
  const app = useAppBridge();
  const instance = axios.create();
  instance.interceptors.request.use(async function (config) {
    const token = await getSessionToken(app);
    config.headers['Authorization'] = `Bearer ${token}`;
    return config;
  });
  return [instance];
}

export default useAxios;

// index.js

// ...
const [axios] = useAxios();

// ...
const result = await axios.get('/api/products');
console.log(result.data);
// ...

Hope this helps anyone who is still looking for help.


问:
Do records generate overrides for inherited positional properties?
Consider the following record definitions:

```<code>public record BaseRecord(string Text)
{
    public string Text { get; init; } = Normalize(Text);

    // ...
}

public record DerivedRecord(string Text) : BaseRecord(Text)
{
    // ...
}
</code>```

BaseRecord will have the normalized value for Text. But does DerivedRecord reuse the Test property from BaseRecord, or does it generate a new one that ignores the normalized base value?

Further: What if BaseRecord did not have Text as a positional parameter, but only as a regular property?

答:
The purpose of inheritance for record types is to add additional properties to existing record types.

Consider this more simplified example:

```<code>public record BaseRecord(string Text);

public record DerivedRecord(string Text, string Other) : BaseRecord(Text);
</code>```

The user expects now from DerivedRecord a record type with 2 properties: Text and Other.
The compiler sees that BaseRecord already has the property Text and only adds Other as another property.

If the compiler would not do this, there would be 2 properties named Text where the derived property would hide the base property (known as shadowing) which is definitely not a behavior you want.

Body:
Consider the following record definitions:

public record BaseRecord(string Text)
{
    public string Text { get; init; } = Normalize(Text);

    // ...
}

public record DerivedRecord(string Text) : BaseRecord(Text)
{
    // ...
}

BaseRecord will have the normalized value for Text. But does DerivedRecord reuse the Test property from BaseRecord, or does it generate a new one that ignores the normalized base value?

Further: What if BaseRecord did not have Text as a positional parameter, but only as a regular property?

Body:
The purpose of inheritance for record types is to add additional properties to existing record types.

Consider this more simplified example:

public record BaseRecord(string Text);

public record DerivedRecord(string Text, string Other) : BaseRecord(Text);

The user expects now from DerivedRecord a record type with 2 properties: Text and Other.
The compiler sees that BaseRecord already has the property Text and only adds Other as another property.

If the compiler would not do this, there would be 2 properties named Text where the derived property would hide the base property (known as shadowing) which is definitely not a behavior you want.


问:
Crtical section not working in OpenMP program
Q. Fill an array of size 100 with 1. Find sum of the array.

So i ran the below program on linux compiled with the flag -fopenmp and the answer i am getting is Sum : 400 (As 4 cores ) but it should be 100 as its in critical section
Note: Dont mind intialiazing of 1 , I was told to do this for this question

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

#include <omp.h>

int main()

{

    int size=100;

    int a[size];

    double sum=0.0;

    for (int i =0;i<size/4;i++)

        a[i]=1;

    for (int i =size/4;i<size/2;i++)

        a[i]=1;

    for (int i =size/2;i<3*size/4;i++)

        a[i]=1;

    for (int i =3*size/4;i<size;i++)

        a[i]=1;

    #pragma omp parallel shared(sum)

    {

        for(int i =0;i<size;i++){

    #pragma omp critical

         {

                sum+=a[i];

         }

        }

    }

    printf("Sum : %f",sum);

    return 0;

}
</code>```

答:
Your big mistake is using omp parallel without for: now every thread executes the whole for loop (because omp parallel only creates the threads) and your result is 4x too large. You need to use: omp parallel for, which contains the omp for "worksharing" construct.

Conceptual mistake: critical sections are really bad for performance in simple cases like this. You will get the right result, but no speedup. Use a reduction clause on your parallel for. Try to avoid critical and atomic as much as possible.

Btw, why all the blank lines? That just makes it harder for us to read.

Body:
Q. Fill an array of size 100 with 1. Find sum of the array.

So i ran the below program on linux compiled with the flag -fopenmp and the answer i am getting is Sum : 400 (As 4 cores ) but it should be 100 as its in critical section
Note: Dont mind intialiazing of 1 , I was told to do this for this question

#include <stdio.h>

#include <omp.h>

int main()

{

    int size=100;

    int a[size];

    double sum=0.0;

    for (int i =0;i<size/4;i++)

        a[i]=1;

    for (int i =size/4;i<size/2;i++)

        a[i]=1;

    for (int i =size/2;i<3*size/4;i++)

        a[i]=1;

    for (int i =3*size/4;i<size;i++)

        a[i]=1;

    #pragma omp parallel shared(sum)

    {

        for(int i =0;i<size;i++){

    #pragma omp critical

         {

                sum+=a[i];

         }

        }

    }

    printf("Sum : %f",sum);

    return 0;

}


问:
How to check if my type t is surrounded by typing.List or not? For example check the difference between int and List[int]
I want to execute different code depending on the type of my t.

I've got the follwing types:

```<code>from pydantic import BaseModel
from typing import List

class Person(BaseModel):
    name: str
    id: int
</code>```

and

```<code>t1 = Person
t2 = List[Person]
</code>```

now I want to check if my variable tX is if of a list type or a normal type. How can I do that?

```<code>def check_if_list(t):
    if type(t) == List:  # <- this doesn't work how can i do this check
        print('LIST') # some code
    else:
        print('NO LIST') # some code
</code>```

t1 and t2 would give me:

```<code>check_if_list(t1)  # prints NO LIST
check_if_list(t2)  # prints LIST
</code>```

答: You don't to import the typing library. Just evaluate this type(t) == list.</p>

Body:
I want to execute different code depending on the type of my t.

I've got the follwing types:

from pydantic import BaseModel
from typing import List

class Person(BaseModel):
    name: str
    id: int

and

t1 = Person
t2 = List[Person]

now I want to check if my variable tX is if of a list type or a normal type. How can I do that?

def check_if_list(t):
    if type(t) == List:  # <- this doesn't work how can i do this check
        print('LIST') # some code
    else:
        print('NO LIST') # some code

t1 and t2 would give me:

check_if_list(t1)  # prints NO LIST
check_if_list(t2)  # prints LIST


问:
Eclipse editor that unpackages/repackages files on open/save?
I'd like to create an Eclipse editor plugin that will show a decoded portion of a file rather than the raw original, and then re-encode the file upon saving.  For example, an editor for a docx file that would unzip the archive, display the various xml component files in different tabs, and upon saving, would write them all out and rezip the archive.  Can anyone point me to an existing project that does something like this?  So far the examples I've seen based on ISourceViewer and ITextViewer only read the file as it exists on disk.

Thanks!
--Andy

答: Have a look at org.eclipse.pde.internal.ui.editor.plugin.ManifestEditor from PDE. This editor does not unzip the input, but it does decode the different parts of the input files...


问:
B2C- Customization of signing up page (custom policy)
UPDATE

I used split email verification and sign up for my sign up process.
On the 4th page I added a button to allow changing the email address.

How to allow user to reset email validation (picture 1) when he clicks on the change email button, knowing that at this step of process, the input "email" and the button for sending code "email_ver_but_send" are not hidden but not exist when inspecting the page?

Those are my pages for signing up  :

1-Validation email

2- Validate code

3- Change email

4- Create account

My questions are :

1- How to hide continue and cancel buttons in steps 1-2-3 and only display them in the 4th step of the process?

2- After checking the code (step 2), how to go directly to step 4?

Thanks for help

答:
There is a metadata setting called setting.showCancelButton that can be added to the self asserted technical profile. This has the possible value of true for showing the button and false for not showing the button.

Here is an example

```<code>    <TechnicalProfile Id="SelfAsserted-Page">
      <DisplayName>Self Asserted Page</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="setting.showCancelButton">false</Item>
      </Metadata>
      <InputClaims>
      </InputClaims>
      <OutputClaims>
      </OutputClaims>
    </TechnicalProfile>
</code>```

More information about the metadata keys for self-asserted technical profiles can be found on the Microsoft documentation website.

Body:
There is a metadata setting called setting.showCancelButton that can be added to the self asserted technical profile. This has the possible value of true for showing the button and false for not showing the button.

Here is an example

    <TechnicalProfile Id="SelfAsserted-Page">
      <DisplayName>Self Asserted Page</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="setting.showCancelButton">false</Item>
      </Metadata>
      <InputClaims>
      </InputClaims>
      <OutputClaims>
      </OutputClaims>
    </TechnicalProfile>

More information about the metadata keys for self-asserted technical profiles can be found on the Microsoft documentation website.


问:
CSS component is moving up the screen to the header
I have used these CSS properties for my card, however whenever I move the page to test the responsiveness the component moves upwards towards the header.

(I would post a photo but I don't have the rep yet)

```<code>.card {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}
</code>```
```<code><div className="card">
        <div className="p-4  bg-white rounded-lg border border-gray-200 shadow-md sm:p-6 lg:p-8 dark:bg-gray-800 dark:border-gray-700 w-96 min-w-full">

        </div>
      </div>
</code>```

答: I think you can solve this with a parent div unsure</p>

Body:
I have used these CSS properties for my card, however whenever I move the page to test the responsiveness the component moves upwards towards the header.

(I would post a photo but I don't have the rep yet)

.card {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}


问:
Append a txt file in .Net
I am Creating a txt file in.Net with the help of below code.

```<code>StreamWriter writerVer = new StreamWriter(@"c:\Version.txt");
writerVer.WriteLine("Version : " + Context.Parameters["ver"]);
File.SetAttributes(@"C:\Version.txt", FileAttributes.Hidden);
</code>```

Then I need to Update the file on the next line by keeping the above code as it is.

This code overrites the entire file.

```<code>StreamWriter writer = new StreamWriter(@"c:\Version.txt");
writer.WriteLine("Connection string : "+con);
</code>```

Regrads,

Sachin K

答:
try this

```<code> StreamWriter writerVer = new StreamWriter(@"c:\Version.txt", true);
</code>```

There is an overload of the StreamWriter constructor that takes an additional bool parameter to indicate if you want to append or not.

Title: Append a txt file in .Net

Body:
I am Creating a txt file in.Net with the help of below code.

StreamWriter writerVer = new StreamWriter(@"c:\Version.txt");
writerVer.WriteLine("Version : " + Context.Parameters["ver"]);
File.SetAttributes(@"C:\Version.txt", FileAttributes.Hidden);

Then I need to Update the file on the next line by keeping the above code as it is.

This code overrites the entire file.

StreamWriter writer = new StreamWriter(@"c:\Version.txt");
writer.WriteLine("Connection string : "+con);

Regrads,

Sachin K

Body:
try this

 StreamWriter writerVer = new StreamWriter(@"c:\Version.txt", true);

There is an overload of the StreamWriter constructor that takes an additional bool parameter to indicate if you want to append or not.


问:
Any suggestion how to remove error "SyntaxError: Cannot use import statement outside a module" while running Appium.js from Java code?
Any suggestion how to remove error "SyntaxError: Cannot use import statement outside a module" while running Appium.js from Java code?
Trying adding type: "type": "module" in your package.json or the .mjs extension.
when "type": "module" added the new exception came.
node:internal/errors:464
ErrorCaptureStackTrace(err);
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Ritesh Mittal\AppData\Roaming\npm\node_modules\appium\lib\logger' imported from C:\Users\Ritesh Mittal\AppData\Roaming\npm\node_modules\appium\lib\appium.js
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:416:11)
at moduleResolve (node:internal/modules/esm/resolve:932:10)
at defaultResolve (node:internal/modules/esm/resolve:1044:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ModuleWrap. (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

Used cjs-to-es6 utility to convert appium.js in appium.mjs. But, js not converted mjs.

//Code

```<code>AppiumDriverLocalService service;
AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(Integer.parseInt("4723"));
builder.withAppiumJS(new File("C:\\Users\\Ritesh Mittal\\AppData\\Roaming\\npm\\node_modules\\appium\\lib\\appium.js"));

service = AppiumDriverLocalService.buildService(builder);
service.start();
System.out.println("APpium Service Started on: ");
</code>```

Any help?

答: It is solved correcting Appium path. It was needed till node_modules\appium</p>

Body:
Any suggestion how to remove error "SyntaxError: Cannot use import statement outside a module" while running Appium.js from Java code?
Trying adding type: "type": "module" in your package.json or the .mjs extension.
when "type": "module" added the new exception came.
node:internal/errors:464
ErrorCaptureStackTrace(err);
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Ritesh Mittal\AppData\Roaming\npm\node_modules\appium\lib\logger' imported from C:\Users\Ritesh Mittal\AppData\Roaming\npm\node_modules\appium\lib\appium.js
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:416:11)
at moduleResolve (node:internal/modules/esm/resolve:932:10)
at defaultResolve (node:internal/modules/esm/resolve:1044:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ModuleWrap. (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

Used cjs-to-es6 utility to convert appium.js in appium.mjs. But, js not converted mjs.

//Code

AppiumDriverLocalService service;
AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(Integer.parseInt("4723"));
builder.withAppiumJS(new File("C:\\Users\\Ritesh Mittal\\AppData\\Roaming\\npm\\node_modules\\appium\\lib\\appium.js"));

service = AppiumDriverLocalService.buildService(builder);
service.start();
System.out.println("APpium Service Started on: ");

Any help?


答:
The most pythonic way of doing it is using the built-in function isinstance:

```<code>if isinstance(t, list)
</code>```

At least according to PEP-8:

Object type comparisons should always use isinstance() instead of comparing types directly

If you want to check an inheritance from typing.List you should be aware that a list doesn't come from typing.List, that's only a way of representing it in type hints.

Title: How to check if my type t is surrounded by typing.List or not? For example check the difference between int and List[int]

Body:
The most pythonic way of doing it is using the built-in function isinstance:

if isinstance(t, list)

At least according to PEP-8:

Object type comparisons should always use isinstance() instead of comparing types directly

If you want to check an inheritance from typing.List you should be aware that a list doesn't come from typing.List, that's only a way of representing it in type hints.


问:
What is DDD's Aggregate in SpringBoot MVC?
Suppose I've a bunch of microservices, each written on SpringBoot MVC (REST, Controller, Service, etc..)

Can anybody explain what is DDD's Aggregate in SpringBoot MVC? is it a controller? Or is it a specific microservice which is a root for some other microservices?

In other words, is aggregate something within a service with a controller's endpoint as a root? or is aggregate a sub-set of microservices with a particular SpringBoot application/service as an entry point to them?

答:
It is neither a controller nor specific microservice.

It is a cluster of the domain objects that can be treated as a single unit (e.g. Order and its order line) (see this) which is retrieved , saved and searched by the repository.

The spring framework also provides an more specialised @Component called @Repository to represent the repository concepts (quoted from its javadoc) :

Indicates that an annotated class is a "Repository", originally
defined by Domain-Driven Design (Evans, 2003) as "a mechanism for
encapsulating storage, retrieval, and search behavior which emulates a
collection of objects".

Teams implementing traditional Java EE
patterns such as "Data Access Object"  may also apply this stereotype
to DAO classes, though care should be taken to understand the
distinction between Data Access Object and DDD-style repositories
before doing so. This annotation is a general-purpose stereotype and
individual teams may narrow their semantics and use as appropriate.

As we use repository to save JPA @Entity or MongoDB @Document to the underlying datastore , so DDD aggregate is more align to them


问:
Strange behavior with ggplots geom_point in for loop
I am using ggplot and gridExtra to make two plots side by side with different data, and I'm observing an unexpected behavior when using vector to make the plot instead of a dataframe.

Here is MWE with my problem:

```<code>library(ggplot2)
library(dplyr)
library(gridExtra)

cases <- c(1, 2)

df <- data.frame(
  case=cases,
  y1=c(1, 2),
  y2=c(2, 4),
  y3=c(3, 8),
  y4=c(4, 16),
  y5=c(5, 32)
)

x <- c(1, 2, 3, 4, 5)

plot_list <- list()
for(caso in cases){
  data <- df %>% filter(case == caso)
  y <- data %>% dplyr::select(starts_with('y')) %>% unlist(use.name=FALSE)
  dd <- data.frame(xdf=x, ydf=y)
  graph <- (
    ggplot()
    + geom_line(data=dd, aes(x=xdf, y=ydf))
    ## + geom_point(data=dd, aes(x=xdf, y=ydf)) # this line works
    + geom_point(aes(x=x, y=y)) # this line doesn't
  )
  plot_list[[length(plot_list)+1]] <- graph
}

grid.arrange(grobs=plot_list, ncol=2)
</code>```

This code makes a plot with a line on the left and a parabola on the right. I marked two lines that call geom_point. If I use the line with the dataframe, everything works as expected. However, if I use the line with the vectors (that were actually used to create the dataframe), than the points of the parabola are plotted in all the graphs.

Here is the resulting figure:

Clearly, the problem is solved by using dataframes instead of vectors, but I wanted to understand why this behavior is happening in the first place. So I'd appreciate any insight of why R is behaving in such seemingly counter-intuitive (at least for me) way.

答:
Interesting finding. This is because you're using a for loop and they have also to me often enough difficult to understand behaviour regarding object creation and evaluation. In your case, ggplot doesn't draw the plots until the last end, and then the last vector 'y' is used for the plot. I find the easiest way to avoid this problem is using another way to loop instead. I prefer the apply family.

That said - my advice is to avoid using vectors in aes() - this only causes headaches.

I just found this thread which explains the problem much better. Suggest closing this question as a duplicate. "for" loop only adds the final ggplot layer

library(ggplot2)
library(dplyr)

df <- data.frame( case=1:2, y1=c(1, 2), y2=c(2, 4), y3=c(3, 8), y4=c(4, 16), y5=c(5, 32))

x <- 1:5

plot_list <- lapply(1:2, function(i){
  data <- df %>% dplyr::filter(case == i)
  y <- data %>% dplyr::select(starts_with('y')) %>% unlist(use.name=FALSE)
  graph <- ggplot() +
    geom_point(aes(x=x, y=y))
  graph
})

gridExtra::grid.arrange(grobs=plot_list, ncol=2)
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
I am using ggplot and gridExtra to make two plots side by side with different data, and I'm observing an unexpected behavior when using vector to make the plot instead of a dataframe.

Here is MWE with my problem:

library(ggplot2)
library(dplyr)
library(gridExtra)

cases <- c(1, 2)

df <- data.frame(
  case=cases,
  y1=c(1, 2),
  y2=c(2, 4),
  y3=c(3, 8),
  y4=c(4, 16),
  y5=c(5, 32)
)

x <- c(1, 2, 3, 4, 5)

plot_list <- list()
for(caso in cases){
  data <- df %>% filter(case == caso)
  y <- data %>% dplyr::select(starts_with('y')) %>% unlist(use.name=FALSE)
  dd <- data.frame(xdf=x, ydf=y)
  graph <- (
    ggplot()
    + geom_line(data=dd, aes(x=xdf, y=ydf))
    ## + geom_point(data=dd, aes(x=xdf, y=ydf)) # this line works
    + geom_point(aes(x=x, y=y)) # this line doesn't
  )
  plot_list[[length(plot_list)+1]] <- graph
}

grid.arrange(grobs=plot_list, ncol=2)

This code makes a plot with a line on the left and a parabola on the right. I marked two lines that call geom_point. If I use the line with the dataframe, everything works as expected. However, if I use the line with the vectors (that were actually used to create the dataframe), than the points of the parabola are plotted in all the graphs.

Here is the resulting figure:

Clearly, the problem is solved by using dataframes instead of vectors, but I wanted to understand why this behavior is happening in the first place. So I'd appreciate any insight of why R is behaving in such seemingly counter-intuitive (at least for me) way.

Body:
Interesting finding. This is because you're using a for loop and they have also to me often enough difficult to understand behaviour regarding object creation and evaluation. In your case, ggplot doesn't draw the plots until the last end, and then the last vector 'y' is used for the plot. I find the easiest way to avoid this problem is using another way to loop instead. I prefer the apply family.

That said - my advice is to avoid using vectors in aes() - this only causes headaches.

I just found this thread which explains the problem much better. Suggest closing this question as a duplicate. "for" loop only adds the final ggplot layer

library(ggplot2)
library(dplyr)

df <- data.frame( case=1:2, y1=c(1, 2), y2=c(2, 4), y3=c(3, 8), y4=c(4, 16), y5=c(5, 32))

x <- 1:5

plot_list <- lapply(1:2, function(i){
  data <- df %>% dplyr::filter(case == i)
  y <- data %>% dplyr::select(starts_with('y')) %>% unlist(use.name=FALSE)
  graph <- ggplot() +
    geom_point(aes(x=x, y=y))
  graph
})

gridExtra::grid.arrange(grobs=plot_list, ncol=2)

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Uncaught TypeError: Vue.component is not a function
In OS X with Laravel/Homestead, I'm getting an error using Vue (v2.2.1).  The component won't load and the console error is "Uncaught TypeError: Vue.component is not a function".

Full console error

```<code>    Uncaught TypeError: Vue.component is not a function
        at eval (eval at <anonymous> (app.js:321), <anonymous>:17:5)
        at Object.<anonymous> (app.js:321)
        at __webpack_require__ (app.js:20)
        at app.js:64
        at app.js:67
</code>```

What is throwing me off is that if I make a change to app.js, the webpack does not update to reflect any changes.  So I need to A) fix the issue above, and B) figure out how to get the webpack to show updates in the console.

Any help would be greatly appreciated!  I'm a noob.  Here is my code...

app.js file

```<code>    Vue.component('video-upload', require('./components/VideoUpload.vue'));

    const app = new Vue({
        el: 'body'
    });
</code>```

VideoUpload.vue

```<code>    <template>
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">Example</div>

                        <div class="panel-body">
                            This is an example
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <script>
        export default {
            mounted() {
                console.log('Component mounted.')
            }
        }
    </script>
</code>```

upload.blade.php

```<code>    @extends('layouts.app')

    @section('content')
        <video-upload></video-upload>
    @endsection
</code>```

package.json

```<code>    {
      "private": true,
      "scripts": {
        "prod": "gulp --production",
        "dev": "gulp watch"
      },
        "devDependencies": {
        "bootstrap-sass": "^3.3.7",
        "gulp": "^3.9.1",
        "jquery": "^3.1.0",
        "laravel-elixir": "^6.0.0-9",
        "laravel-elixir-vue": "^0.1.4",
        "laravel-elixir-webpack-official": "^1.0.2",
        "lodash": "^4.14.0",
        "video.js": "^5.11.6",
        "vue": "^2.2.1",
        "vue-resource": "^0.9.3"
      }
    }
</code>```

答:
CHECK YOUR CDN VUE VERSION. THEY CHANGED FROM VUE 2 TO VUE 3.

This scenarion happened here, we were using Vue 2 and our CDN changed the global script to Vue 3.

Vue 3 changed the "Vue.component" to "Vue.directive" which broke our application.

Body:
In OS X with Laravel/Homestead, I'm getting an error using Vue (v2.2.1).  The component won't load and the console error is "Uncaught TypeError: Vue.component is not a function".

Full console error

    Uncaught TypeError: Vue.component is not a function
        at eval (eval at <anonymous> (app.js:321), <anonymous>:17:5)
        at Object.<anonymous> (app.js:321)
        at __webpack_require__ (app.js:20)
        at app.js:64
        at app.js:67

What is throwing me off is that if I make a change to app.js, the webpack does not update to reflect any changes.  So I need to A) fix the issue above, and B) figure out how to get the webpack to show updates in the console.

Any help would be greatly appreciated!  I'm a noob.  Here is my code...

app.js file

    Vue.component('video-upload', require('./components/VideoUpload.vue'));

    const app = new Vue({
        el: 'body'
    });

VideoUpload.vue

    <template>

Example

                            This is an example

    </template>

upload.blade.php

    @extends('layouts.app')

    @section('content')
        <video-upload></video-upload>
    @endsection

package.json

    {
      "private": true,
      "scripts": {
        "prod": "gulp --production",
        "dev": "gulp watch"
      },
        "devDependencies": {
        "bootstrap-sass": "^3.3.7",
        "gulp": "^3.9.1",
        "jquery": "^3.1.0",
        "laravel-elixir": "^6.0.0-9",
        "laravel-elixir-vue": "^0.1.4",
        "laravel-elixir-webpack-official": "^1.0.2",
        "lodash": "^4.14.0",
        "video.js": "^5.11.6",
        "vue": "^2.2.1",
        "vue-resource": "^0.9.3"
      }
    }


问:
How to change font size of title in iphone?
this is the code ,this will show the default size, i want to change the font size of the title becoz this title is too big n not showing the whole only "Cook Great Indian..." is showing...pl let me help out</p>

```<code>- (void)viewDidLoad {

    self.title = @"Cook Great Indian Recipes";
}
</code>```

答:
Try setting custom label for title label:</p>

```<code>    self.title = @"Cook Great Indian Recipes";
    CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:17.0];
    label.textAlignment = UITextAlignmentCenter;
    self.navigationItem.titleView = label;
    label.text = self.title;
    [label release];
</code>```

Body:
this is the code ,this will show the default size, i want to change the font size of the title becoz this title is too big n not showing the whole only "Cook Great Indian..." is showing...pl let me help out

- (void)viewDidLoad {

    self.title = @"Cook Great Indian Recipes";
}

Body:
Try setting custom label for title label:

    self.title = @"Cook Great Indian Recipes";
    CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:17.0];
    label.textAlignment = UITextAlignmentCenter;
    self.navigationItem.titleView = label;
    label.text = self.title;
    [label release];


问:
How to identify if create read replica action is complete and finished
I am trying to create a read replica of the production database and then I want to promote the read replica to a test database.

I have used this awscli command to create a read replica

```<code>aws rds create-db-instance-read-replica --db-instance-identifier test-database --source-db-instance-identifier production-database --region eu-central-1
</code>```

I know I cannot issue a promote read replica command immediately as I would get an error.

```<code>bash-3.2$ aws rds promote-read-replica --db-instance-identifier test-database --region eu-central-1

An error occurred (InvalidDBInstanceState) when calling the PromoteReadReplica operation: DB Instance is not in an available state.
</code>```

How can I check if the read replica is created successfully so I can issue a promote read replica command?

I tried to query the events for the database but it is returning empty.

```<code>bash-3.2$ aws rds describe-events --source-identifier test-database --source-type db-instance
{
    "Events": []
}
</code>```

I am trying to do this in the Jenkins pipeline so it has to be checked programmatically.

Kindly advise.

答:
i m trying to continue the above script by adding parameter group and reboot the read replica .</p>
```<code> db_status=$(aws rds describe-db-instances \
                --db-instance-identifier db-replica \
                --profile xxx \
                --region us-west-2 \
                --query 'DBInstances[0].DBInstanceStatus' \
                --output text)
    [[ $db_status != "available" ]] \
        && (echo $db_status; sleep 15)\
        || break

 echo "Finally ${db_status}"
if [ $db_status == "available" ]
    then
        echo "replica created successfully"
        echo "Rebooting replica"
        aws rds reboot-db-instance --db-instance-identifier db-replica
        sleep 5;
else
   echo "replica rebooted successfully"
fi

exit 1
</code>```

Body:
I am trying to create a read replica of the production database and then I want to promote the read replica to a test database.

I have used this awscli command to create a read replica

aws rds create-db-instance-read-replica --db-instance-identifier test-database --source-db-instance-identifier production-database --region eu-central-1

I know I cannot issue a promote read replica command immediately as I would get an error.

bash-3.2$ aws rds promote-read-replica --db-instance-identifier test-database --region eu-central-1

An error occurred (InvalidDBInstanceState) when calling the PromoteReadReplica operation: DB Instance is not in an available state.

How can I check if the read replica is created successfully so I can issue a promote read replica command?

I tried to query the events for the database but it is returning empty.

bash-3.2$ aws rds describe-events --source-identifier test-database --source-type db-instance
{
    "Events": []
}

I am trying to do this in the Jenkins pipeline so it has to be checked programmatically.

Kindly advise.

Body:
i m trying to continue the above script by adding parameter group and reboot the read replica .

 db_status=$(aws rds describe-db-instances \
                --db-instance-identifier db-replica \
                --profile xxx \
                --region us-west-2 \
                --query 'DBInstances[0].DBInstanceStatus' \
                --output text)
    [[ $db_status != "available" ]] \
        && (echo $db_status; sleep 15)\
        || break

 echo "Finally ${db_status}"
if [ $db_status == "available" ]
    then
        echo "replica created successfully"
        echo "Rebooting replica"
        aws rds reboot-db-instance --db-instance-identifier db-replica
        sleep 5;
else
   echo "replica rebooted successfully"
fi

exit 1


问:
How to assign .editorconfig to a Visual Studio 2019 C++ solution?
I am editing a VS solution that has a different coding style than the one I normally use. I found in the docs that VS 2019 supports EditorConfig: https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2019

I created .editorconfig file in the root of my solution:

I put this in the file:

```<code>root = true

[*.{cpp,hpp,h}]
indent_style = space
indent_size = 4
</code>```

I then went to the solution, right clicked the solution Botcraft in the solution explorer, selected Add an existing item... and added the aforementioned file. I can now see the item in the solution:

However, when I write if(true) and press enter, I still get two spaces as per my VS settings instead of four as per the editorconfig settings.

How to link .editorconfig to visual studio solution and make it respect the settings inside?

答: EditorConfig files are only applied to the directory they are in and its sub-directories you need to put the file in the same folder as your source code (or a folder above it) not in the same folder as your solution/project files.</p>

Body:
I am editing a VS solution that has a different coding style than the one I normally use. I found in the docs that VS 2019 supports EditorConfig: https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2019

I created .editorconfig file in the root of my solution:

I put this in the file:

root = true

[*.{cpp,hpp,h}]
indent_style = space
indent_size = 4

I then went to the solution, right clicked the solution Botcraft in the solution explorer, selected Add an existing item... and added the aforementioned file. I can now see the item in the solution:

However, when I write if(true) and press enter, I still get two spaces as per my VS settings instead of four as per the editorconfig settings.

How to link .editorconfig to visual studio solution and make it respect the settings inside?


问:
Flutter - Firebase callable functions with region not working
we currently facing the problem in our flutter app, that httpsCallable functions which are defined with a region, in our case "europe-west1", is throwing an exception:

```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [firebase_functions/internal] Response is not valid JSON object.

#0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
<asynchronous suspension>
#2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:23:24)
<asynchronous suspension>
#3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:35:37)
<asynchronous suspension>

#0      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:39:7)
<asynchronous suspension>
#1      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:35:37)
<asynchronous suspension>
</code>```

As far, as we tested, it makes no difference, if we define the region in flutter accordingly to docs:

```<code>final result = await FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('myCallableFunction').call();
</code>```

Or directly in the cloud function:

```<code>exports.myCallableFunction = functions.region("europe-west1").https.onCall((data, context) => {
   // ... return result
});
</code>```

If we remove the region on both lines above, the callable function is working and returning the expected result.

Is there something, what I miss or is there currently an issue in flutter itself?

答:
After some testing and the comment from Peter Koltai, the solution is defining the region in both, flutter and cloud functions:

flutter:

```<code>final result = await FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('myCallableFunction').call();
</code>```

cloud functions:

```<code>exports.myCallableFunction = functions.region("europe-west1").https.onCall((data, context) => {
   // ... return result
});
</code>```

Of course, this makes sense, because as the caller, I want to call the callable functions out of the "europe-west1" region. This gives, if required, the flexibility to call different functions for different regions.

Body:
we currently facing the problem in our flutter app, that httpsCallable functions which are defined with a region, in our case "europe-west1", is throwing an exception:

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [firebase_functions/internal] Response is not valid JSON object.

#0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
<asynchronous suspension>
#2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:23:24)
<asynchronous suspension>
#3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:35:37)
<asynchronous suspension>

#0      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:39:7)
<asynchronous suspension>
#1      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:35:37)
<asynchronous suspension>

As far, as we tested, it makes no difference, if we define the region in flutter accordingly to docs:

final result = await FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('myCallableFunction').call();

Or directly in the cloud function:

exports.myCallableFunction = functions.region("europe-west1").https.onCall((data, context) => {
   // ... return result
});

If we remove the region on both lines above, the callable function is working and returning the expected result.

Is there something, what I miss or is there currently an issue in flutter itself?

Body:
After some testing and the comment from Peter Koltai, the solution is defining the region in both, flutter and cloud functions:

flutter:

final result = await FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('myCallableFunction').call();

cloud functions:

exports.myCallableFunction = functions.region("europe-west1").https.onCall((data, context) => {
   // ... return result
});

Of course, this makes sense, because as the caller, I want to call the callable functions out of the "europe-west1" region. This gives, if required, the flexibility to call different functions for different regions.


问:
Is there an accepted "name" for an event that simply reports back a "message"
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

```<code>var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();
</code>```

答:
As Adam already mentioned it would be easier to distinguish between these events for other classes, because every listener will only receive these kinds of events he liked. But if you think that everyone who subscribes to one of these events has to subscribe to all of them then it wouldn't make sense to make such a bunch of different events.

If you like to merge them, you are on your own. But maybe you can get some inspiration from the INotifyPropertyChanged and the ListChanged event, cause they are also some kind of aggregators for different kind of things that could happen. But this leads to the fact that the client has to inspect the incoming data from the event and make has maybe to throw away a lot of incoming events, cause they are out of interest.

Body:
I have a "DataImporter" class [takes data from many sources and processes it] that I want to report back through an event when it "does something".
At the moment I have:
DataImporterStarted
DataImporterCompleted
DataImporterImportedData
DataImporterDeleted

But they all do the same thing...report back a simple string saying "Data Importer started at xx:xx" or "DataImporter Imported xxx Rows" etc.

Should I be keeping the events separate, or is there an accepted pattern/naming convention for this kind of "I'm doing something" event?
Thx

I was trying to avoid code like this:

var importer = new DataImporter();
importer.DataImporterStarted += new DataImporterStartedEventHandler(importer_DataImporterMessage);
importer.DataImported += new DataImportedEventHandler(importer_DataImporterMessage);
importer.DataImporterCompleted += new DataImporterCompletedEventHandler(importer_DataImporterMessage);
importer.RunDataImporter();


问:
Trouble posting to many-to-many field
I am trying to post a combination object, which refers to already existing tag objects. Basically I want the tag_id field of the combination to include 2 ids referring to Tag objects.

This is my code:

models.py

```<code>class Combination(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
    tag_id = models.ManyToManyField(Tag, null=True)
    created = models.DateTimeField(editable=False)
    score = models.PositiveIntegerField(default=0)

    objects = models.Manager()

    def __str__(self):
        return str(self.tag_id) or ''
</code>```

serializers.py

```<code>class CombinationSerializer(serializers.ModelSerializer):
  tag_id = TagWithIdSerializer(many=True, required=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag_id')

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    for tag_object in tag_data:
      combination.set(tag_id=tag_object)
    if len(combination.tag_id) == 2:
      return combination

  def to_representation(self, instance):
    rep = super().to_representation(instance)
    rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
    return rep
</code>```

With this I am currently getting an AttributeError : 'Combination' object has no attribute 'set'

If I update this:

```<code>for tag_object in tag_data:
      combination.set(tag_id=tag_object)
</code>```

Like this:

```<code>    combination.save()
    for tag_object in tag_data:
      combination.tag_id.add(tag_object)
</code>```

I am now getting the error Field 'id' expected a number but got OrderedDict([('name', 'word'), ('language', 'en')]).

If I add:

```<code>    combination.save()
    for tag_object in tag_data[0]:
      combination.tag_id.add(tag_object)
</code>```

I get the ValueError Field 'id' expected a number but got 'name'.

How can I get rid of this?

答:
In order to set objects in a ManyToMany field in Django you have to save the object before. Like so

combination.save()

for tag_object in tag_data:
    combination.tag_id.add(tab_object)
```

Title: Trouble posting to many-to-many field

Body:
I am trying to post a combination object, which refers to already existing tag objects. Basically I want the tag_id field of the combination to include 2 ids referring to Tag objects.

This is my code:

models.py

class Combination(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
    tag_id = models.ManyToManyField(Tag, null=True)
    created = models.DateTimeField(editable=False)
    score = models.PositiveIntegerField(default=0)

    objects = models.Manager()

    def __str__(self):
        return str(self.tag_id) or ''

serializers.py

class CombinationSerializer(serializers.ModelSerializer):
  tag_id = TagWithIdSerializer(many=True, required=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag_id')

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    for tag_object in tag_data:
      combination.set(tag_id=tag_object)
    if len(combination.tag_id) == 2:
      return combination

  def to_representation(self, instance):
    rep = super().to_representation(instance)
    rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
    return rep

With this I am currently getting an AttributeError : 'Combination' object has no attribute 'set'

If I update this:

for tag_object in tag_data:
      combination.set(tag_id=tag_object)

Like this:

    combination.save()
    for tag_object in tag_data:
      combination.tag_id.add(tag_object)

I am now getting the error Field 'id' expected a number but got OrderedDict([('name', 'word'), ('language', 'en')]).

If I add:

    combination.save()
    for tag_object in tag_data[0]:
      combination.tag_id.add(tag_object)

I get the ValueError Field 'id' expected a number but got 'name'.

How can I get rid of this?