问:
Gridview.Databind() not refresh the data
First of all, sorry if I make mistakes in english...

I'm making a web with c#, and I have some problems for refresh the data displayed in the GridView

I'm getting the data throw the SqlDataSource defined at the aspx view:

```<code><asp:SqlDataSource ID="PRODUCTOS_CON_STOCK" runat="server" ConnectionString="<%$ ConnectionStrings:XXXX %>" ProviderName="<%$ ConnectionStrings:XXX.ProviderName %>" DataSourceMode="DataSet" SelectCommand=" select EAN, CODART.....  "> </asp:SqlDataSource>
</code>```

When I click a button, I update some data in the database, and I want refresh de GridView with the new data, without reload the page.
I'm making: gridView.DataBind();, but that doesn't refresh the data in the GridView.

(At the database is updated)

The GridView is inside of an UpdatePanel.

I was trying some things, like:

Reassing the DataSourceID  and make the gridView.DataBind();

Assing the DataSourceID in null, make the gridView.DataBind();, and alter reassing the DataSourceID and make the gridView.DataBind();

I tried too:

```<code>    DataSourceSelectArguments argumentos = new DataSourceSelectArguments();

    PRODUCTOS_CON_STOCK.Select(argumentos);

    gridView.DataBind();
</code>```

Set the UpdatePanel to updatemode="Always"

But any of all of that worked...
Someone can help me?

Thanks.

答:
Why not dump the datasource setting on the page of PRODUCTOS_CON_STOCK.

I find that when you need to filtere, load, and play?

Just remove the data source from the markup. So, in your GridView, remove the data source id setting of PRODUCTOS_CON_STOCK, and then delete the data source.

You have to write a BIT more code, but you now have control over the data, and MORE important, control over which parameters you need and want.

So, say I have this markup:

A grid, and also a search/text box to filter the grid.

```<code><asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large">
</asp:TextBox>

<asp:Button ID="cmdSearch" runat="server" Text="search"
    style="margin-left:15px" CssClass="btn" OnClick="cmdSearch_Click" />

<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table"  >
        <Columns>
            <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
            <asp:BoundField DataField="Engine" HeaderText="Engine"  />
            <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="View">
                <ItemTemplate>
                <asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
                    OnClientClick ="popimage(this);return false"
                    ImageUrl = '<%# Eval("ImagePath") %>' />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>
</code>```

Note close - I did build this grid using the wizards. But I THEN removed the Datasource ID for the GV, and removed the Datasource that was created in the markup.

So, now my code to load is this:

```<code>   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid("");
    }

    void LoadGrid(string MySearch)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
            {
                if (MySearch != "")
                {
                    cmdSQL.CommandText += @" WHERE Fighter LIKE @Fighter + '%'";
                    cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
                }
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }
</code>```

And I get this:

And note the "optional" filter for the text box. If you type in some text, (I used a "like" match in sql), then the code is only this:

```<code>    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }
</code>```

but, the idea here is often it is much better to dump the SqlDataSoruce placed in the markup, and roll + write your own code. The problem is you can try and set the data source in code, but ALSO WITH a data source on the page - they fight over each other. So, try the above idea - and remove the data source in the markup.

Body:
First of all, sorry if I make mistakes in english...

I'm making a web with c#, and I have some problems for refresh the data displayed in the GridView

I'm getting the data throw the SqlDataSource defined at the aspx view:

<asp:SqlDataSource ID="PRODUCTOS_CON_STOCK" runat="server" ConnectionString="<%$ ConnectionStrings:XXXX %>" ProviderName="<%$ ConnectionStrings:XXX.ProviderName %>" DataSourceMode="DataSet" SelectCommand=" select EAN, CODART.....  "> </asp:SqlDataSource>

When I click a button, I update some data in the database, and I want refresh de GridView with the new data, without reload the page.
I'm making: gridView.DataBind();, but that doesn't refresh the data in the GridView.

(At the database is updated)

The GridView is inside of an UpdatePanel.

I was trying some things, like:

Reassing the DataSourceID  and make the gridView.DataBind();

Assing the DataSourceID in null, make the gridView.DataBind();, and alter reassing the DataSourceID and make the gridView.DataBind();

I tried too:

    DataSourceSelectArguments argumentos = new DataSourceSelectArguments();

    PRODUCTOS_CON_STOCK.Select(argumentos);

    gridView.DataBind();

Set the UpdatePanel to updatemode="Always"

But any of all of that worked...
Someone can help me?

Thanks.

Body:
Why not dump the datasource setting on the page of PRODUCTOS_CON_STOCK.

I find that when you need to filtere, load, and play?

Just remove the data source from the markup. So, in your GridView, remove the data source id setting of PRODUCTOS_CON_STOCK, and then delete the data source.

You have to write a BIT more code, but you now have control over the data, and MORE important, control over which parameters you need and want.

So, say I have this markup:

A grid, and also a search/text box to filter the grid.

<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large">
</asp:TextBox>

<asp:Button ID="cmdSearch" runat="server" Text="search"
    style="margin-left:15px" CssClass="btn" OnClick="cmdSearch_Click" />

<br />
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table"  >
        <Columns>
            <asp:BoundField DataField="Fighter" HeaderText="Fighter"  />
            <asp:BoundField DataField="Engine" HeaderText="Engine"  />
            <asp:BoundField DataField="Thrust" HeaderText="Thrust"  />
            <asp:BoundField DataField="Description" HeaderText="Description" />

            <asp:TemplateField HeaderText="View">
                <ItemTemplate>
                <asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
                    OnClientClick ="popimage(this);return false"
                    ImageUrl = '<%# Eval("ImagePath") %>' />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

Note close - I did build this grid using the wizards. But I THEN removed the Datasource ID for the GV, and removed the Datasource that was created in the markup.

So, now my code to load is this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid("");
    }

    void LoadGrid(string MySearch)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
            {
                if (MySearch != "")
                {
                    cmdSQL.CommandText += @" WHERE Fighter LIKE @Fighter + '%'";
                    cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
                }
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }
    }

And I get this:

And note the "optional" filter for the text box. If you type in some text, (I used a "like" match in sql), then the code is only this:

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        LoadGrid(txtSearch.Text);
    }

but, the idea here is often it is much better to dump the SqlDataSoruce placed in the markup, and roll + write your own code. The problem is you can try and set the data source in code, but ALSO WITH a data source on the page - they fight over each other. So, try the above idea - and remove the data source in the markup.


来源: stackexchange

问:
flutter how to generate random numbers without duplication
Is there any way to generate random numbers without duplication?
For instance I want to generate 50 random numbers from 1 to 100 no duplication, any way to do this or do I have to check every time incoming number is already created or not?</p>

答:
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.

```<code>import 'dart:math';

class RandomList {
  static final _random = new Random();

  static List<int> uniqueSample({int limit, int n}) {
    final List<int> sortedResult = [];
    final List<int> result = [];
    for (int i = 0; i < n; i++) {
      int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time

      // Increment the number so that it picks from the remaining list of available numbers
      int j = 0;
      for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;

      sortedResult.insert(j, rn);
      result.add(rn);
    }
    return result;
  }
}
</code>```

I haven't tested it exhaustively but it seems to work.

ContentLicense: CC BY-SA 4.0

Body:
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.

import 'dart:math';

class RandomList {
  static final _random = new Random();

  static List<int> uniqueSample({int limit, int n}) {
    final List<int> sortedResult = [];
    final List<int> result = [];
    for (int i = 0; i < n; i++) {
      int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time

      // Increment the number so that it picks from the remaining list of available numbers
      int j = 0;
      for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;

      sortedResult.insert(j, rn);
      result.add(rn);
    }
    return result;
  }
}

I haven't tested it exhaustively but it seems to work.


问:
How to simply download a JAR using Maven?
How do I download JAR during a build in Maven script? </p>

答:
Maven does not work like that. Here's the closest you'll get to my knowledge:

```<code>mvn dependency:get -DremoteRepositories=http://repo1.maven.org/maven2/ \
                   -DgroupId=junit -DartifactId=junit -Dversion=4.8.2 \
                   -Dtransitive=false
</code>```

Note that all parameters except transitive are required.

Also note that Maven will download the jar to your local repository, and there's no sensible way (that I know of) to copy it to a local directory.

Reference:

dependency:get

ContentLicense: CC BY-SA 3.0

Body:
Maven does not work like that. Here's the closest you'll get to my knowledge:

mvn dependency:get -DremoteRepositories=http://repo1.maven.org/maven2/ \
                   -DgroupId=junit -DartifactId=junit -Dversion=4.8.2 \
                   -Dtransitive=false

Note that all parameters except transitive are required.

Also note that Maven will download the jar to your local repository, and there's no sensible way (that I know of) to copy it to a local directory.

Reference:

dependency:get


问:
Model not saving refresh token
Just trying to save the refresh token from Google OAuth 2.0 into the abstractuser profile which signed in. It displays the refresh token and the user correctly. However when logged in the user doesn't have the refresh token stored in the model.

pipeline.py:

```<code>from .models import Profile
def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data
    print(extra_data["refresh_token"],user)
    Profile.objects.get_or_create(
        username=user, defaults={"refresh_token": extra_data["refresh_token"]}
    )
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    refresh_token = models.CharField(max_length=255, default="")

</code>```

Now when displaying it, it comes up empty.

calendar.html:

```<code>{% block content %}

    {{user.refresh_token}}

    <h1>Calendar</h1>
    <button>+</button>
    <ul>
        {% for result in results %}
            <li>{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}</li>
        {% endfor %}
    </ul>
{% endblock %}
</code>```

答:
The queryset method get_or_create does not update values in the model, it only creates a new object if it doesn't exist. If you're trying to update values in an existing object, you should use the second value that get_or_create returns to confirm it already exists and make the necessary updates.

So the adjustment would look like this:

```<code>def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data

    profile, created = Profile.objects.get_or_create(
        username=user, defaults={"refresh_token":
        extra_data["refresh_token"]}
    )

    # `created` will be false if the object exists

    if not created:
        profile.refresh_token = extra_data["refresh_token"]
        profile.save()
</code>```

Title: Model not saving refresh token

Body:
Just trying to save the refresh token from Google OAuth 2.0 into the abstractuser profile which signed in. It displays the refresh token and the user correctly. However when logged in the user doesn't have the refresh token stored in the model.

pipeline.py:

from .models import Profile
def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data
    print(extra_data["refresh_token"],user)
    Profile.objects.get_or_create(
        username=user, defaults={"refresh_token": extra_data["refresh_token"]}
    )

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    refresh_token = models.CharField(max_length=255, default="")

Now when displaying it, it comes up empty.

calendar.html:

{% block content %}

    {{user.refresh_token}}

Calendar

    <button>+</button>

        {% for result in results %}

{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}

        {% endfor %}

{% endblock %}

Body:
The queryset method get_or_create does not update values in the model, it only creates a new object if it doesn't exist. If you're trying to update values in an existing object, you should use the second value that get_or_create returns to confirm it already exists and make the necessary updates.

So the adjustment would look like this:

def save_token(user,*args,**kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data

    profile, created = Profile.objects.get_or_create(
        username=user, defaults={"refresh_token":
        extra_data["refresh_token"]}
    )

    # `created` will be false if the object exists

    if not created:
        profile.refresh_token = extra_data["refresh_token"]
        profile.save()


问:
AWS IAM instance policy applying credentials to instance in one region, but not another
I have a setup where I launch AWS EC2 instances from templates and their AMI contains the AWS CLI, so it can copy over the contents of a private S3 bucket on launch. This template automatically applies an IAM role with the "AmazonS3ReadOnlyAccess" policy. This has been working as intended so far in the eu-west-2 region, but now I wanted to run these instances in us-east-2 region. I copied the AMI and made a new template using identical settings to the ones in eu-west-2, but when the script to sync the S3 buckets launches (it's just a bat file that runs "aws s3 sync ... ...") the contents of the synced folder are empty.

After a bit of looking around I noticed that it throws a "fatal error: Unable to locate credentials" error. I checked the credentials using "aws configure list" and get that access_key, secret_key and region are not set. If I run the same instance back in eu-west-2 these fields are populated.

I've tried recopying the base AMI, recreating the launch templates, creating region specific buckets, creating new IAM policies and all this as both a IAM user and the root user, the credentials still get set in eu-west-2, but not us-east-2.
The only configurations that differ are the VPC, subnet and routing table settings - for obvious reasons, as they need to be in a new region.
Does anybody know why this might be happening? As I've run out of ideas.

us-east-2a instance

us-east-2b instance

答:
Ok, so as I was continuing to have issues with the copied AMI, I decided to just build one from scratch on the us-east-2 server.

I made a new instance, set it up, and created a new AMI. When I launched it the instance policy applied correctly and everything worked. When I made a template from the AMI, however, everything the credentials were missing again. I tried launching the instance from the AMI (not the template) everything worked again. I compared the settings between the template and AMI launched instances and the only difference (besides different IP's and such) was the subnet - the working AMI image was on us-east-2a, the template created instance was on us-east-2b. Now this seems odd to me, that policy applied credentials would be subnet dependent, but as much as I tested this seems to be the case.

TL;DR. Policy set credentials were not being applied due to new images not being launched on same subnet as to where the original AMI was built on(us-east-2a and us-east-2b). Solved by setting launch template to use same subnet.


问:
How to pass var values from .js file to the variables in the bash file
I have a variables.js file that includes several variables with values like:

```<code>var var_1 = 1;
var var_2 = 'someText';
</code>```

I need to pass these values to variables within the vars bash file:

```<code>VAR_1
VAR_2
</code>```

That sounds like a decently simple task, however, having a lack of practical experience with bash scripts baffles me.

Tried using source or reading line by line, however, it didn't lead to a possible solution.

答:
With GNU grep and a Perl-compatible regular expression (-P):

```<code>VAR_1=$(grep -Po '(?<=^var var_1 = ).*?(?=;)' variables.js)
VAR_2=$(grep -Po '(?<=^var var_2 = ).*?(?=;)' variables.js)
</code>```

See: The Stack Overflow Regular Expressions FAQ -> Lookarounds

Body:
I have a variables.js file that includes several variables with values like:

var var_1 = 1;
var var_2 = 'someText';

I need to pass these values to variables within the vars bash file:

VAR_1
VAR_2

That sounds like a decently simple task, however, having a lack of practical experience with bash scripts baffles me.

Tried using source or reading line by line, however, it didn't lead to a possible solution.

Body:
With GNU grep and a Perl-compatible regular expression (-P):

VAR_1=$(grep -Po '(?<=^var var_1 = ).*?(?=;)' variables.js)
VAR_2=$(grep -Po '(?<=^var var_2 = ).*?(?=;)' variables.js)

See: The Stack Overflow Regular Expressions FAQ -> Lookarounds


问:
Testing ladder logic
We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.

The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.

答:
The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality.

Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder

```<code>|---|R15|---+---|/R16|---------(R18)--------|
|           |
|---|R12|---+
</code>```

to an expression like

```<code>always @(*) R18 = !R16 && ( R15 | R12);
</code>```

or you could use an assign statement

```<code>assign R18 = R16 && (R15 | R12);
</code>```

a latching relay

```<code>assign R18 = (set condition) || R18 && !(break condition);
</code>```

Then use a free verilog simulator like Icarus to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic!  And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn.

(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.

Verilog will be an easier language to develop your tests and testbenches in!

It may be helpful to program in some unit delays.

Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!

Good luck.
jbd

There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:

http://cq.cx/ladder.pl

OwnerDisplayName: Erik van Brakel

ContentLicense: CC BY-SA 2.5

Title: Testing ladder logic

Body:
The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality.

Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder

|---|R15|---+---|/R16|---------(R18)--------|
|           |
|---|R12|---+

to an expression like

always @(*) R18 = !R16 && ( R15 | R12);

or you could use an assign statement

assign R18 = R16 && (R15 | R12);

a latching relay

assign R18 = (set condition) || R18 && !(break condition);

Then use a free verilog simulator like Icarus to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic!  And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn.

(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.

Verilog will be an easier language to develop your tests and testbenches in!

It may be helpful to program in some unit delays.

Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!

Good luck.
jbd

There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:

http://cq.cx/ladder.pl

OwnerDisplayName: jbdavid

LastEditorDisplayName: jbdavid


问:
How can I stop the time from displaying in a GridView when displaying a date?
I have a web application that I am working on(ASP.NET 2.0 & C#). In it, I have a gridview that gets data from an Oracle Database. Some of the data that I need to display is dates. But when the dates in my gridview show like this:

2009-04-02 00:00:00

I'd prefer they show without the time. I'm using the codebehind to get the data, so I cant alter the fields of the gridview manually. This is all the code for my gridview :

```<code><asp:GridView ID="Grid" runat="server" EmptyDataText="There are no data records to display." ></asp:GridView>
</code>```

How do I stop the time from displaying?

答:
if you set your datasource programmatically (code behind), you can still have all your columns in the gridview (use asp:DataBoundColumn)

```<code>DataFormatString="{0:d}"
</code>```

EDIT

this code is for your aspx page, if you really want to stick your presentation logic in your code behind - you have 2 options:

format the Date on "RowDataBound" event

format the Date in your query - that way you won't have to deal with formatting in code at all

OwnerDisplayName: zohair

Body:
I have a web application that I am working on(ASP.NET 2.0 & C#). In it, I have a gridview that gets data from an Oracle Database. Some of the data that I need to display is dates. But when the dates in my gridview show like this:

2009-04-02 00:00:00

I'd prefer they show without the time. I'm using the codebehind to get the data, so I cant alter the fields of the gridview manually. This is all the code for my gridview :

<asp:GridView ID="Grid" runat="server" EmptyDataText="There are no data records to display." ></asp:GridView>

How do I stop the time from displaying?

LastEditorDisplayName: Rich B

Body:
if you set your datasource programmatically (code behind), you can still have all your columns in the gridview (use asp:DataBoundColumn)

DataFormatString="{0:d}"

EDIT

this code is for your aspx page, if you really want to stick your presentation logic in your code behind - you have 2 options:

format the Date on "RowDataBound" event

format the Date in your query - that way you won't have to deal with formatting in code at all

OwnerDisplayName: rm

LastEditorDisplayName: rm


问:
WPF's DataContext questions
I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.

```<code>MainViewModel model = new MainViewModel();
this.DataContext = model;
</code>```

And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).

When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;.

Is this correct?

How can I do the same thing in XAML file?

What's the magic behind this DataContext thing? I mean, how does DataContext work?

答:
Yes that is correct as far as i know, since this is quite repetetive some MVVM frameworks do this linking for you.

In XAML:

```<code><UserControl ...
             xmlns:vm="clr-namespace:MyApp.ViewModels">
    <UserControl.DataContext>
        <vm:MyViewModel />
    </UserControl.DataContext>
    <!-- ... -->
</UserControl>
</code>```

It enables short bindings where the Path is relative to the DataContext, e.g. {Binding Name} binds to DataContext.Name. It also is inherited which can be useful.

Please read the Data Binding Overview if you haven't.

Title: WPF's DataContext questions

Body:
I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.

MainViewModel model = new MainViewModel();
this.DataContext = model;

And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).

When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;.

Is this correct?

How can I do the same thing in XAML file?

What's the magic behind this DataContext thing? I mean, how does DataContext work?

Body:
Yes that is correct as far as i know, since this is quite repetetive some MVVM frameworks do this linking for you.

In XAML:

<UserControl ...
             xmlns:vm="clr-namespace:MyApp.ViewModels">
    <UserControl.DataContext>
        <vm:MyViewModel />
    </UserControl.DataContext>
    <!-- ... -->
</UserControl>

It enables short bindings where the Path is relative to the DataContext, e.g. {Binding Name} binds to DataContext.Name. It also is inherited which can be useful.

Please read the Data Binding Overview if you haven't.


问:
docker compose with remote context gives ssh error connection refused
I have a problem with docker-compose when I try to run this command from my local machine on my remote server using docker context:

```<code>docker-compose --context remote up -d
</code>```

I get this:

```<code>ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused
</code>```

I only get this error with this command, everything else works fine (like ps or logs commands). Also regular ssh connection works fine, so I don't think there is something wrong with my ssh configuration.

Running the command with verbose gives no useful information, as far as I can see.

答:
I had this exact issue. These 3 commands would run fine.

```<code>docker --context remote ps
docker --context remote run hello-world
ssh root@my-ubuntu-host
</code>```

However, with more complicated docker-compose.yml files, I would get a connection refused error. Running with sudo did not fix the issue for me.

Turns out, ufw (which was pre-installed and pre-configured on my digital ocean droplet), was rate-limiting new SSH connections. And it seems docker-compose doesn't run everything in a single session, and instead runs each command separately.

The solution for me was to remove the rate-limit on SSH connections.

```<code>ufw delete limit 22/tcp
ufw reload
</code>```

I'm about a year too late with this answer but hopefully it will help someone out there.

Body:
I have a problem with docker-compose when I try to run this command from my local machine on my remote server using docker context:

docker-compose --context remote up -d

I get this:

ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused

I only get this error with this command, everything else works fine (like ps or logs commands). Also regular ssh connection works fine, so I don't think there is something wrong with my ssh configuration.

Running the command with verbose gives no useful information, as far as I can see.

Body:
I had this exact issue. These 3 commands would run fine.

docker --context remote ps
docker --context remote run hello-world
ssh root@my-ubuntu-host

However, with more complicated docker-compose.yml files, I would get a connection refused error. Running with sudo did not fix the issue for me.

Turns out, ufw (which was pre-installed and pre-configured on my digital ocean droplet), was rate-limiting new SSH connections. And it seems docker-compose doesn't run everything in a single session, and instead runs each command separately.

The solution for me was to remove the rate-limit on SSH connections.

ufw delete limit 22/tcp
ufw reload

I'm about a year too late with this answer but hopefully it will help someone out there.


问:
What is the difference between these two ES queries?
Version of ES: 7.16.

I'm aware that "types" have more or less been phased out in v7 ... seemingly leaving only "_doc" as the endpoint after the index name. Can anyone say whether there's any difference between these 2 queries in ES 7?

```<code>search_url = f'{ES_URL}my_index/_doc/_search?q={search_string}'
</code>```

or

```<code>search_url = f'{ES_URL}my_index/_search?q={search_string}'
</code>```

They seem to return the same hits...

Will the second become illegal in a future ES version?

答:
there's no difference in 7.X, no

in 8.X the first one will error as there are no types, so only the second one will work

https://www.elastic.co/guide/en/elasticsearch/reference/8.0/removal-of-types.html and https://www.elastic.co/guide/en/elasticsearch/reference/7.16/removal-of-types.html go into that more

Body:
Version of ES: 7.16.

I'm aware that "types" have more or less been phased out in v7 ... seemingly leaving only "_doc" as the endpoint after the index name. Can anyone say whether there's any difference between these 2 queries in ES 7?

search_url = f'{ES_URL}my_index/_doc/_search?q={search_string}'

or

search_url = f'{ES_URL}my_index/_search?q={search_string}'

They seem to return the same hits...

Will the second become illegal in a future ES version?


问:
Optimize MIN/MAX lookup by constraint on other table
I have a table vals with an integer id and some integer value. And another table times with PRIMARY id and an integer time.

```<code>CREATE TABLE times (
  id int(11) NOT NULL PRIMARY KEY,
  time int(11) NOT NULL
) ENGINE=MyISAM;

CREATE TABLE vals (
  id int(11) NOT NULL,
  value int(11) NOT NULL,
  UNIQUE KEY value (value, id)
) ENGINE=MyISAM;
</code>```

My goal is to select the highest value given a constraint on time.

Additionally I know that with a high probability the highest value matching the constraint is within the first few highest values, but not necessarily.

Working query:

```<code>SELECT MAX(value)
   FROM vals v
   JOIN times t ON v.id = t.id AND t.time > UNIX_TIMESTAMP() - 86400
</code>```

However it is not particularly efficient if the tables are big. But whatever way round I change this query, I end up materializing either at least all ids satisfying the constraint on t.time or all ids present in times which have a corresponding id in values [which also is most rows] (or worse), according to EXPLAIN.

Getting SELECT value, id FROM vals ORDER BY value DESC LIMIT 10 is very fast thanks to the index.

But I cannot manage to tell mariadb "hey look, please iterate on the by value ordered resultset and give me the first value matching this condition by its id".

Doing something akin to:

```<code>SELECT value
FROM (
    SELECT value,
          (SELECT time > UNIX_TIMESTAMP() - 86400
              FROM times t WHERE t.id = v.id) AS active
    FROM vals v
    ORDER BY value DESC
    LIMIT 10
) x
WHERE active LIMIT 1
</code>```

is pretty fast (and I'd then increase the LIMIT 10 to LIMIT 100 to LIMIT 1000 etc. in code to successively search a larger amount of rows if none is found) as this actually just fetches the time for the N highest values.

However, is there a way to do that in a single query, without materializing the full resultset on the times table?

P.s.: Changing the columns is not acceptable, altering indices is.

The database version used is mariadb 10.5. To clarify on the actual contents:

Most (80%-90%) times in the times table are greater than UNIX_TIMESTAMP() - 86400. The ids are auto_increment with a lot of holes.

vals contains hundreds of different values overall, most (60%) entries in times have a corresponding entry in vals.

Both tables have a couple millions of rows.

答:
I would never try to create tables that have columns as reserved words that may cause confusion.  Although Time itself may not be, consider better naming.  However, that said, I would first start by having compound indexes as below:

```<code>Table    Index
Times    ( time, id)  -- to optimize your time filtering requirement
Vals     ( id, value ) -- since the ID will be the basis of the JOIN, not the value
</code>```

Now, your query.  To get the filtered set of records, do a query of your times table base just on that basis and you get the IDs.  That is then joined to the values table

```<code>SELECT
      MAX( v.value)
   FROM
      times t
         JOIN vals v
            on t.id = v.id
   where
      t.time > UNIX_TIMESTAMP() - 86400
</code>```

Your where is optimized by the times index on the time column, that is all that needs.  Then, a direct JOIN to the values that qualify the times based on the common ID between them.  Finally, its just the MAX() value from the values table.  Since no aggregation, it will just return a single record out of all that qualify from the time restriction.

Body:
I have a table vals with an integer id and some integer value. And another table times with PRIMARY id and an integer time.

CREATE TABLE times (
  id int(11) NOT NULL PRIMARY KEY,
  time int(11) NOT NULL
) ENGINE=MyISAM;

CREATE TABLE vals (
  id int(11) NOT NULL,
  value int(11) NOT NULL,
  UNIQUE KEY value (value, id)
) ENGINE=MyISAM;

My goal is to select the highest value given a constraint on time.

Additionally I know that with a high probability the highest value matching the constraint is within the first few highest values, but not necessarily.

Working query:

SELECT MAX(value)
   FROM vals v
   JOIN times t ON v.id = t.id AND t.time > UNIX_TIMESTAMP() - 86400

However it is not particularly efficient if the tables are big. But whatever way round I change this query, I end up materializing either at least all ids satisfying the constraint on t.time or all ids present in times which have a corresponding id in values [which also is most rows] (or worse), according to EXPLAIN.

Getting SELECT value, id FROM vals ORDER BY value DESC LIMIT 10 is very fast thanks to the index.

But I cannot manage to tell mariadb "hey look, please iterate on the by value ordered resultset and give me the first value matching this condition by its id".

Doing something akin to:

SELECT value
FROM (
    SELECT value,
          (SELECT time > UNIX_TIMESTAMP() - 86400
              FROM times t WHERE t.id = v.id) AS active
    FROM vals v
    ORDER BY value DESC
    LIMIT 10
) x
WHERE active LIMIT 1

is pretty fast (and I'd then increase the LIMIT 10 to LIMIT 100 to LIMIT 1000 etc. in code to successively search a larger amount of rows if none is found) as this actually just fetches the time for the N highest values.

However, is there a way to do that in a single query, without materializing the full resultset on the times table?

P.s.: Changing the columns is not acceptable, altering indices is.

The database version used is mariadb 10.5. To clarify on the actual contents:

Most (80%-90%) times in the times table are greater than UNIX_TIMESTAMP() - 86400. The ids are auto_increment with a lot of holes.

vals contains hundreds of different values overall, most (60%) entries in times have a corresponding entry in vals.

Both tables have a couple millions of rows.

Body:
I would never try to create tables that have columns as reserved words that may cause confusion.  Although Time itself may not be, consider better naming.  However, that said, I would first start by having compound indexes as below:

Table    Index
Times    ( time, id)  -- to optimize your time filtering requirement
Vals     ( id, value ) -- since the ID will be the basis of the JOIN, not the value

Now, your query.  To get the filtered set of records, do a query of your times table base just on that basis and you get the IDs.  That is then joined to the values table

SELECT
      MAX( v.value)
   FROM
      times t
         JOIN vals v
            on t.id = v.id
   where
      t.time > UNIX_TIMESTAMP() - 86400

Your where is optimized by the times index on the time column, that is all that needs.  Then, a direct JOIN to the values that qualify the times based on the common ID between them.  Finally, its just the MAX() value from the values table.  Since no aggregation, it will just return a single record out of all that qualify from the time restriction.


问:
Can not start android emulator - Hyper V detected but Hypervisor platform is not available
I am running into an issue where I can't start the xamarin android emulator, it says:

```<code>Device error: WARNING | unexpected '-prop' value ('monodroid.avdname=pie_9_0_-_api_28'), only 'qemu.' properties are supported
WARNING | unexpected '-prop' value ('emu.uuid=c23d7e88-c1e4-4283-bb2b-e2632b5c3c16'), only 'qemu.' properties are supported
ERROR   | x86 emulation currently requires hardware acceleration!
CPU acceleration status: Hyper-V detected and Windows Hypervisor Platform is not available. Please either disable Hyper-V or upgrade to Windows 10 1803 or later. To disable Hyper-V, start a command prompt as Administrator, run 'bcdedit /set hypervisorlaunchtype off', reboot. If u
More info on configuring VM acceleration on Windows:
https://developer.android.com/studio/run/emulator-acceleration#vm-windows
General information on acceleration: https://developer.android.com/studio/run/emulator-acceleration.
</code>```

I need Hyper-V to be enabled for the emulator acceleration, otherwise if i disable it, the apps on the emulator run painfully slowly. The thing is I had hyper-v enabled before, and all of my emulators ran just fine with it, then suddenly I started getting this error. Both Hyper-V and Windows Hypervisor Platform are enabled in windows features. I also have HAXM accelerator installed for the android. I also tried running the following commands: bcdedit /set hypervisorlaunchtype auto and dism /online /enable-feature /feature-name:Microsoft-Hyper-V -All; both commands resulted in "operation completed successfully". I also tried running "C:\Program Files (x86)\Android\android-sdk\emulator\emulator-check.exe" accel, and this is what I got:

```<code>accel:
0
Please disable Hyper-V before using the Android Emulator.  Start a command prompt as Administrator, run 'bcdedit /set hypervisorlaunchtype off', reboot.WHPX (10.0.19042) is installed and usable.
accel
</code>```

I am not sure what is going on, and why my emulators suddenly can not run with Hyper-V enabled. Has anyone faced this issue before? Any help would be much appreciated. Thanks

答:
Uninstall HAXM; it reads: WHPX (10.0.19042) is installed and usable.

This is the "Windows Hypervisor Platform" ...

https://learn.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/hardware-acceleration?pivots=windows

Body:
I am running into an issue where I can't start the xamarin android emulator, it says:

Device error: WARNING | unexpected '-prop' value ('monodroid.avdname=pie_9_0_-_api_28'), only 'qemu.' properties are supported
WARNING | unexpected '-prop' value ('emu.uuid=c23d7e88-c1e4-4283-bb2b-e2632b5c3c16'), only 'qemu.' properties are supported
ERROR   | x86 emulation currently requires hardware acceleration!
CPU acceleration status: Hyper-V detected and Windows Hypervisor Platform is not available. Please either disable Hyper-V or upgrade to Windows 10 1803 or later. To disable Hyper-V, start a command prompt as Administrator, run 'bcdedit /set hypervisorlaunchtype off', reboot. If u
More info on configuring VM acceleration on Windows:
https://developer.android.com/studio/run/emulator-acceleration#vm-windows
General information on acceleration: https://developer.android.com/studio/run/emulator-acceleration.

I need Hyper-V to be enabled for the emulator acceleration, otherwise if i disable it, the apps on the emulator run painfully slowly. The thing is I had hyper-v enabled before, and all of my emulators ran just fine with it, then suddenly I started getting this error. Both Hyper-V and Windows Hypervisor Platform are enabled in windows features. I also have HAXM accelerator installed for the android. I also tried running the following commands: bcdedit /set hypervisorlaunchtype auto and dism /online /enable-feature /feature-name:Microsoft-Hyper-V -All; both commands resulted in "operation completed successfully". I also tried running "C:\Program Files (x86)\Android\android-sdk\emulator\emulator-check.exe" accel, and this is what I got:

accel:
0
Please disable Hyper-V before using the Android Emulator.  Start a command prompt as Administrator, run 'bcdedit /set hypervisorlaunchtype off', reboot.WHPX (10.0.19042) is installed and usable.
accel

I am not sure what is going on, and why my emulators suddenly can not run with Hyper-V enabled. Has anyone faced this issue before? Any help would be much appreciated. Thanks


问:
Pickle.dump to variable
I'm new in python and i wanted to know if there is a solution for this problem:

I know that this may sound strange but i want to save the pickle.dump data into a variable.
I begin to think that may i could bypass it by making a fake class to instead of writing in a file, writing in a variable:

```<code>class PickleDatatoVar(object):
    def __init__(self):
        self.data = None
    def write(self, data):
        self.data = data
    def get(self):
        return self.data
</code>```

and then:

```<code>pick = PickleDatatoVar()
pickle.dump(Int, pick)
var = pick.get()
</code>```

Nothing is presented as error, but the output is just a '.'

So is there a solution to instead of saving that in a file saving into a variable?

答:
I found a quick and clean explanation here on stackoverlfow by Farhan K:</p>
```<code>import pickle

mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = str(pickle.dumps(mydict), encoding="latin1")

unpickled_dict = pickle.loads(bytes(string_of_bytes_obj, "latin1"))
</code>```

Title: Pickle.dump to variable

Body:
I'm new in python and i wanted to know if there is a solution for this problem:

I know that this may sound strange but i want to save the pickle.dump data into a variable.
I begin to think that may i could bypass it by making a fake class to instead of writing in a file, writing in a variable:

class PickleDatatoVar(object):
    def __init__(self):
        self.data = None
    def write(self, data):
        self.data = data
    def get(self):
        return self.data

and then:

pick = PickleDatatoVar()
pickle.dump(Int, pick)
var = pick.get()

Nothing is presented as error, but the output is just a '.'

So is there a solution to instead of saving that in a file saving into a variable?

Body:
I found a quick and clean explanation here on stackoverlfow by Farhan K:

import pickle

mydict = { 'a': 1111, 'b': 2222 }
string_of_bytes_obj = str(pickle.dumps(mydict), encoding="latin1")

unpickled_dict = pickle.loads(bytes(string_of_bytes_obj, "latin1"))


问:
How to hide/remove labels with No Data in a multiple labeled horizontal Bar Chart
Following this question: Bar Chart with multiple labels.
I tried to replicate the code with a horizontal bar chart. I would like to know how I could remove/hide the labels with No data.

So instead of this:

looks more like this:

I attach the code below.

I would appreciate it if someone could steer me in the right direction here.
Thank you in advance.

Cheers

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

df = pd.DataFrame(
    {"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)

test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
            aggfunc=np.sum)

fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
    pos.append(bar.get_y()+bar.get_height()/2.)

ax.set_yticks(pos,minor=True)
lab = []
for i in range(len(pos)):
    l = test.columns.values[i//len(test.index.values)]
    lab.append(l)

ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)

plt.show()
plt.close()
</code>```

答:
I edited your code to check if each cell value is nan when creating the labels.

If the cell value is nan then the label value is set to an empty string, if the cell value is not nan then the true label is used.

```<code>import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

df = pd.DataFrame(
    {"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)

test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
            aggfunc=np.sum)

fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
    pos.append(bar.get_y()+bar.get_height()/2.)

ax.set_yticks(pos,minor=True)
lab = []

#EDITED FROM HERE
arr = []
for i in range(len(test.iloc[0].values)):
    arr.append(test.iloc[0].values[i])
    arr.append(test.iloc[1].values[i])

for i in range(len(pos)):
    l = test.columns.values[i//len(test.index.values)]
    val = arr[i]
    if np.isnan(val):
        lab.append("")
    else:
        lab.append(l)
#TO HERE

ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)

plt.show()
plt.close()
</code>```

Body:
Following this question: Bar Chart with multiple labels.
I tried to replicate the code with a horizontal bar chart. I would like to know how I could remove/hide the labels with No data.

So instead of this:

looks more like this:

I attach the code below.

I would appreciate it if someone could steer me in the right direction here.
Thank you in advance.

Cheers

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

df = pd.DataFrame(
    {"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)

test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
            aggfunc=np.sum)

fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
    pos.append(bar.get_y()+bar.get_height()/2.)

ax.set_yticks(pos,minor=True)
lab = []
for i in range(len(pos)):
    l = test.columns.values[i//len(test.index.values)]
    lab.append(l)

ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)

plt.show()
plt.close()

Body:
I edited your code to check if each cell value is nan when creating the labels.

If the cell value is nan then the label value is set to an empty string, if the cell value is not nan then the true label is used.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

df = pd.DataFrame(
    {"DEPARTMENT": ["Accounting", "Administration", "Finance", "Finance", "Human resources", "IT", "Marketing", "R&D"], "DATE": ["June", "June", "July", "June", "June","June","June","June"], "COUNT": [10, 33, 16, 23, 3, 3, 5, 9]}
)

test=pd.pivot_table(df, values='COUNT', index='DATE',columns='DEPARTMENT',
            aggfunc=np.sum)

fig=plt.figure(dpi=300)
ax=test.plot(kind='barh',color=['#4472C4'], legend=False)
ax = plt.gca()
pos = []
for bar in ax.patches:
    pos.append(bar.get_y()+bar.get_height()/2.)

ax.set_yticks(pos,minor=True)
lab = []

#EDITED FROM HERE
arr = []
for i in range(len(test.iloc[0].values)):
    arr.append(test.iloc[0].values[i])
    arr.append(test.iloc[1].values[i])

for i in range(len(pos)):
    l = test.columns.values[i//len(test.index.values)]
    val = arr[i]
    if np.isnan(val):
        lab.append("")
    else:
        lab.append(l)
#TO HERE

ax.set_yticklabels(lab,minor=True)
ax.tick_params(axis='y', which='major', pad=120, size=0)
plt.setp(ax.get_xticklabels(), rotation=0)

plt.show()
plt.close()


问:
Does Typescript have Operator Overloading?
My question is if there is operator overloading in typescript, if it exists I could give an example or a link where you can read about it.</p>

答:
If you'd like operator overloading to exist, you could contribute to this language proposal: https://github.com/tc39/proposal-operator-overloading

If the proposal is declined you'll have a very thorough reason why it shouldn't be added to the language.


答:
If you just want to download a JAR once from a maven mirror I suggest you could just do this manually:

For Maven 1:

http://mirrors.ibiblio.org/pub/mirrors/maven/

For Maven 2:

http://mirrors.ibiblio.org/pub/mirrors/maven2/

These are the repositories (a mirror anyway) that maven will get its JARs from - you can easily access them in the webbrowser of your choice and download the JARs etc. Just browse through the hierarchy (it looks like any Java packag hierarchy) until you find the artefact, then pick the right version and you're good.

For example version 3.6.6.Final of hibernate-core from group org.hibernate you'd find here:

http://mirrors.ibiblio.org/pub/mirrors/maven2/org/hibernate/hibernate-core/3.6.6.Final/

Title: How to simply download a JAR using Maven?

Body: How do I download JAR during a build in Maven script?


问:
C# ConfigurationManager in .NET Core
I have a shared .NET Standard library that was originally being referenced by a .NET 4.8 MVC 4 project. There is a lot of code in this shared library that uses the ConfigurationManager, like:

```<code>var sze = ConfigurationManager.AppSettings["MaxAttachmentSize"];
</code>```

This value for MaxAttachmentSize (and others) was being stored in the web.config.

Now I have a .NET 6 project that I'm building, which will use this same shared project, and I need to find a way to make these configuration app settings work in the new .NET Core application.  What's the best way to do this?

My questions I guess are:

Is there a way to get ConfigurationManager to read from the .NET Core's appsettings.json file like it reads from web.config in the ASP.NET MVC 4 project?

If not, is there another configuration reader that I can use instead that will do double duty being able to work for both projects like I need?

The big spanner in the works though is the fact that all calls to ConfigurationManger right now are static, so if the .NET Core option could be static as well that would be incredibly helpful. If not, it'll just be more work moving the ASP.NET MVC 4 project to make those settings dependency injection available.

答:
now you can get it even more easy

```<code>using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

string sze = Configuration.GetSection("AppSettings:MaxAttachmentSize").Value;
</code>```

after adding to appsettings.json

```<code>  "AppSettings": {
    "MaxAttachmentSize": "size1",
    "MinAttachmentSize": "size2"
  }
</code>```

Title: C# ConfigurationManager in .NET Core

Body:
I have a shared .NET Standard library that was originally being referenced by a .NET 4.8 MVC 4 project. There is a lot of code in this shared library that uses the ConfigurationManager, like:

var sze = ConfigurationManager.AppSettings["MaxAttachmentSize"];

This value for MaxAttachmentSize (and others) was being stored in the web.config.

Now I have a .NET 6 project that I'm building, which will use this same shared project, and I need to find a way to make these configuration app settings work in the new .NET Core application.  What's the best way to do this?

My questions I guess are:

Is there a way to get ConfigurationManager to read from the .NET Core's appsettings.json file like it reads from web.config in the ASP.NET MVC 4 project?

If not, is there another configuration reader that I can use instead that will do double duty being able to work for both projects like I need?

The big spanner in the works though is the fact that all calls to ConfigurationManger right now are static, so if the .NET Core option could be static as well that would be incredibly helpful. If not, it'll just be more work moving the ASP.NET MVC 4 project to make those settings dependency injection available.

Body:
now you can get it even more easy

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

string sze = Configuration.GetSection("AppSettings:MaxAttachmentSize").Value;

after adding to appsettings.json

  "AppSettings": {
    "MaxAttachmentSize": "size1",
    "MinAttachmentSize": "size2"
  }


问:
Facebook graph API, Assign system user to a page
We have Page-Access-Token with all the permissions available (just for testing purposes), we also have a Business System User token and this is the steps we are trying to do

1: We connect our business to the facebook page as an agency using this api call

/me/agencies?access_token=${PAGE_ACCESS_TOKEN}&business=${BUSINESS_ID}&permitted_tasks=['ADVERTISE']

we will become partners with the page successfully.

2: we try to assign our business System user to the page that we just connected our business to using this api call

/me/assigned_users?business=${BUSINESS_ID}&user=${SYSTEM_USER_ID}&access_token=${PAGE_ACCESS_TOKEN}

but this request will fails and we get this response

```<code>error: {
  message: 'Invalid parameter',
  type: 'OAuthException',
  code: 100,
  error_subcode: 1752100,
  is_transient: false,
  error_user_title: 'User is not Business Scoped',
  error_user_msg: 'The user ID provided is not business scoped. Please provide a business or a system user ID',
  fbtrace_id: 'AMSzq06ES6nymFDFD31JWAk'
}
</code>```

we know that it's possible for the System User to be assigned to the page because you can do that in the businees.facebook.com but we want to do it using graph api

Things we confirmed

The System User ID and Business ID are both correct

The Business is already connected to the page as we mentioned in the step 1, and we confirmed that by looking at Page Roles from the page settings we saw our page as an agency for the page

Things we saw that were interesting
if the page owner have role in the business the second api call would end up successfully and the system user will be assigned to the page

So, How can we assign our system user to the pages that connect to our business

答: Found a workaround, I created a Business Asset Group, added the system user to this group in the business.facebook.com then through Graph Api I could add the page to this group and the system user now have control over the page just like how I want it.

Body:
We have Page-Access-Token with all the permissions available (just for testing purposes), we also have a Business System User token and this is the steps we are trying to do

1: We connect our business to the facebook page as an agency using this api call

/me/agencies?access_token=${PAGE_ACCESS_TOKEN}&business=${BUSINESS_ID}&permitted_tasks=['ADVERTISE']

we will become partners with the page successfully.

2: we try to assign our business System user to the page that we just connected our business to using this api call

/me/assigned_users?business=${BUSINESS_ID}&user=${SYSTEM_USER_ID}&access_token=${PAGE_ACCESS_TOKEN}

but this request will fails and we get this response

error: {
  message: 'Invalid parameter',
  type: 'OAuthException',
  code: 100,
  error_subcode: 1752100,
  is_transient: false,
  error_user_title: 'User is not Business Scoped',
  error_user_msg: 'The user ID provided is not business scoped. Please provide a business or a system user ID',
  fbtrace_id: 'AMSzq06ES6nymFDFD31JWAk'
}

we know that it's possible for the System User to be assigned to the page because you can do that in the businees.facebook.com but we want to do it using graph api

Things we confirmed

The System User ID and Business ID are both correct

The Business is already connected to the page as we mentioned in the step 1, and we confirmed that by looking at Page Roles from the page settings we saw our page as an agency for the page

Things we saw that were interesting
if the page owner have role in the business the second api call would end up successfully and the system user will be assigned to the page

So, How can we assign our system user to the pages that connect to our business


问:
How to extract a certain substring from string using regex in python - dictionary value?
I have a str 'data' below contains some url content. using regex I want to only extract "url":"https://www.google.com". Here's what I tried so far:

```<code>impor re
url = re.findall('"url":.*', data)
</code>```

Any help would be appreciated.

{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}

答:
Using regex for this kid of task is really not appropriate ... The data seems to be a JSON "encoded" string. In python you can convert it to a dict and extract its value:

import json

encodedData = '{"ref":{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"},"url":"https:://google.com","__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}}'

data = json.loads(encodedData)
url = data['url']

print(url) # https:://google.com
```

Note: your pasted data seems to be missing some part of the json. I added {"ref": at the beginning and } at the end.

Body:
I have a str 'data' below contains some url content. using regex I want to only extract "url":"https://www.google.com". Here's what I tried so far:

impor re
url = re.findall('"url":.*', data)

Any help would be appreciated.

{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}, "url":"https:://google.com" ,"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}

Body:
Using regex for this kid of task is really not appropriate ... The data seems to be a JSON "encoded" string. In python you can convert it to a dict and extract its value:

import json

encodedData = '{"ref":{"__ref":"QXNzZXRDb250cmFjdFR5cGU6NDU0OTE3"},"decimals":null,"relayId":"QXNzZXRUeXBlOjE1MDQ5OTUxMQ==","favoritesCount":10,"isDelisted":false,"isFavorite":false,"isFrozen":false,"hasUnlockableContent":false,"tokenId":"3379","collection":{"__ref":"Q29sbGVjdGlvblR5cGU6MzY3NDA5MQ=="},"orderData":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:orderData"},"name":"Flame River Chumbi","authenticityMetadata":null,"imageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","creator":null,"assetOwners(first:1)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:assetOwners(first:1)"},"animationUrl":null,"backgroundColor":null,"description":"Chumbi are adorable bipedal creatures that inhabit a lush and mysterious forest valley. They have a spiritual connection to the forest and use magical spells to maintain and protect it.","isListable":true,"isReportedSuspicious":false,"traits(first:100)":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)"},"displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"},"url":"https:://google.com","__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:traits(first:100)","displayImageUrl":"https:\u002F\u002Flh3.googleusercontent.com\u002FtM1wwmVb1dA5DadG-QXFBd1nWnqi6DRh7fL0nHgjr2eZkSMKIhcPcwSuBLEvRIgOQRuFDKiovy1kpHSGz4NciKw6oSON-_gdz8aXKw","externalLink":null,"isEditableByOwner":{"__ref":"client:QXNzZXRUeXBlOjE1MDQ5OTUxMQ==:isEditableByOwner"}}'

data = json.loads(encodedData)
url = data['url']

print(url) # https:://google.com

Note: your pasted data seems to be missing some part of the json. I added {"ref": at the beginning and } at the end.


问:
Django queryset - Add HAVING constraint after annotate(F())
I had a seemingly normal situation with adding HAVING to the query.
I read here and here, but it did not help me

I need add HAVING to my query

MODELS :

```<code>class Package(models.Model):
    status = models.IntegerField()

class Product(models.Model):
    title = models.CharField(max_length=10)
    packages = models.ManyToManyField(Package)
</code>```

Products:

```<code>|id|title|
| - | - |
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
</code>```

Packages:

```<code>|id|status|
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 2 |
</code>```

Product_Packages:

```<code>|product_id|package_id|
| - | - |
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 2 |
| 2 | 3 |
| 4 | 3 |
| 4 | 4 |
</code>```

visual

pack_1 (A, B) status OK

pack_2 (B, C) status not ok

pack_3 (B, D) status OK

pack_4 (D) status not ok

My task is to select those products that have the latest package in status = 1

Expected result is :  A, B

my query is like this

```<code>SELECT prod.title, max(tp.id)
FROM "product" as prod
INNER JOIN "product_packages" as p_p ON (p.id = p_p.product_id)
INNER JOIN "package" as pack ON (pack.id = p_p.package_id)
GROUP BY prod.title
HAVING pack.status = 1
</code>```

it returns exactly what I needed

```<code>|title|max(pack.id)|
| - | - |
| A | 1 |
| B | 3 |
</code>```

BUT my orm does not work correctly
I try like this

```<code>p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id', 'pack_id')
</code>```

p.query

SELECT "product"."id", MAX("product_packages"."package_id") AS "pack_id"

FROM "product" LEFT OUTER JOIN "product_packages" ON ("product"."id" = "product_packages"."product_id") LEFT OUTER JOIN "package" ON ("product_packages"."package_id" = "package"."id")

WHERE "package"."status" = 1

GROUP BY "product"."id"

please help me to make correct ORM

答:
How the query looks like when you remove

```<code>.values('id', 'pack_id')
</code>```

At the end?

If I remember correctly then:

```<code>p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1)
</code>```

and

```<code>    p = Product.objects.annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id')
</code>```

Will result with different queries

Body:
I had a seemingly normal situation with adding HAVING to the query.
I read here and here, but it did not help me

I need add HAVING to my query

MODELS :

class Package(models.Model):
    status = models.IntegerField()

class Product(models.Model):
    title = models.CharField(max_length=10)
    packages = models.ManyToManyField(Package)

Products:

|id|title|
| - | - |
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |

Packages:

|id|status|
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 2 |

Product_Packages:

|product_id|package_id|
| - | - |
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
| 3 | 2 |
| 2 | 3 |
| 4 | 3 |
| 4 | 4 |

visual

pack_1 (A, B) status OK

pack_2 (B, C) status not ok

pack_3 (B, D) status OK

pack_4 (D) status not ok

My task is to select those products that have the latest package in status = 1

Expected result is :  A, B

my query is like this

SELECT prod.title, max(tp.id)
FROM "product" as prod
INNER JOIN "product_packages" as p_p ON (p.id = p_p.product_id)
INNER JOIN "package" as pack ON (pack.id = p_p.package_id)
GROUP BY prod.title
HAVING pack.status = 1

it returns exactly what I needed

|title|max(pack.id)|
| - | - |
| A | 1 |
| B | 3 |

BUT my orm does not work correctly
I try like this

p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id', 'pack_id')

p.query

SELECT "product"."id", MAX("product_packages"."package_id") AS "pack_id"

FROM "product" LEFT OUTER JOIN "product_packages" ON ("product"."id" = "product_packages"."product_id") LEFT OUTER JOIN "package" ON ("product_packages"."package_id" = "package"."id")

WHERE "package"."status" = 1

GROUP BY "product"."id"

please help me to make correct ORM

Body:
How the query looks like when you remove

.values('id', 'pack_id')

At the end?

If I remember correctly then:

p = Product.objects.values('id').annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1)

and

    p = Product.objects.annotate(pack_id = Max('packages')).annotate(my_status = F('packages__status')).filter(my_status=1).values('id')

Will result with different queries


问:
In Django, how to create a model that stores proposed changes to another model?
I'm using Python 3.9 and Django 3.2.  I have the following model

```<code>class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address, through='CoopAddressTags')
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()
    description = models.TextField(null=True)
    approved = models.BooleanField(default=False, null=True)
</code>```

We would like to set up a situation where someone could propose a change to a row in the db that would be reviewed before being saved, so I've created this struture

```<code>class CoopChange(Coop):
    """
    """
    created_at = models.DateTimeField(null=False, default=datetime.now)
</code>```

The problem is that when I create a migration, the table that is created simply points back to the original model, instead of storing all the fields

```<code>        Table "public.directory_coopchange"
   Column    |           Type           | Modifiers
-------------+--------------------------+-----------
 coop_ptr_id | integer                  | not null
 created_at  | timestamp with time zone | not null
</code>```

This is non-ideal because the original table would contain both finalized entries and those suggested for changes.  Is there a way to create an entity that stores proposed changes that mirrors the structure of the original entity?

答:
There are a few of ways you could tackle this

Change Coop to an abstract base class:
https://docs.djangoproject.com/en/4.0/topics/db/models/#abstract-base-classes

Then you can inherit two classes from it CoopProposed and CoopApplied and you can work out what logic happens to create each

Just use the one class Coop and add a property called approved defaulted to False and then set it to True when you approve the changes.
This might not be what you want as it will overwrite any previous changes and you might want to keep a history of changes.

Add a property proposed as a JSONField (check the docs if the DB you are using supports it) on the Coop class.  This can store a whole dictionary with the keys and values of the proposed changes.  When approved, the field can be read and applied to the model's properties in a function or something like that.

class Coop():
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    ...
    proposed = models.JSONField("Proposed Changes", null=True)

    def apply_proposed_changes(self):
       proposed = self.proposed
       self.name = proposed.get('name')
       for type in proposed.get('types'):
           self.types.add(CoopType.objects.get(name=type))
       ...

```

In any case if you're trying to inherit all the properties from Coop you need to understand how Django model inheritance work and all the caveats before you get bitten later down the track:
https://docs.djangoproject.com/en/4.0/topics/db/models/#model-inheritance

Body:
I'm using Python 3.9 and Django 3.2.  I have the following model

class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address, through='CoopAddressTags')
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()
    description = models.TextField(null=True)
    approved = models.BooleanField(default=False, null=True)

We would like to set up a situation where someone could propose a change to a row in the db that would be reviewed before being saved, so I've created this struture

class CoopChange(Coop):
    """
    """
    created_at = models.DateTimeField(null=False, default=datetime.now)

The problem is that when I create a migration, the table that is created simply points back to the original model, instead of storing all the fields

        Table "public.directory_coopchange"
   Column    |           Type           | Modifiers
-------------+--------------------------+-----------
 coop_ptr_id | integer                  | not null
 created_at  | timestamp with time zone | not null

This is non-ideal because the original table would contain both finalized entries and those suggested for changes.  Is there a way to create an entity that stores proposed changes that mirrors the structure of the original entity?

Body:
There are a few of ways you could tackle this

Change Coop to an abstract base class:
https://docs.djangoproject.com/en/4.0/topics/db/models/#abstract-base-classes

Then you can inherit two classes from it CoopProposed and CoopApplied and you can work out what logic happens to create each

Just use the one class Coop and add a property called approved defaulted to False and then set it to True when you approve the changes.
This might not be what you want as it will overwrite any previous changes and you might want to keep a history of changes.

Add a property proposed as a JSONField (check the docs if the DB you are using supports it) on the Coop class.  This can store a whole dictionary with the keys and values of the proposed changes.  When approved, the field can be read and applied to the model's properties in a function or something like that.

class Coop():
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    ...
    proposed = models.JSONField("Proposed Changes", null=True)

    def apply_proposed_changes(self):
       proposed = self.proposed
       self.name = proposed.get('name')
       for type in proposed.get('types'):
           self.types.add(CoopType.objects.get(name=type))
       ...

In any case if you're trying to inherit all the properties from Coop you need to understand how Django model inheritance work and all the caveats before you get bitten later down the track:
https://docs.djangoproject.com/en/4.0/topics/db/models/#model-inheritance


问:
Reactjs counter onClick
Using MUI Boxes i am trying to display a counter variable which gets incremented everytime one of these cells is clicked.I tried adding a counter as a state of a cell which gets incremented whenever the color of each Cell component is changed (everytime a cell is clicked) but doesn't seem to be working.

// =====================================================================================================================
//  C O M P O N E N T
// =====================================================================================================================

class Cell extends React.Component {
    state = {
        color: '#bbdefb',
        count: 0,
    };

    onChange = () => {
        this.setState({color: 'red'});
        this.setState({count: count++});
    };

    render() {
        return (

        );
    }
}

class Main extends React.PureComponent {
    render() {
        return (
            <Box sx={SX.root}>
                <Box sx={SX.page}>
                    <MathGrid sx={SX.math1} />
                    <Box sx={SX.firstrow}>
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                    </Box>
                    <Box sx={SX.secondrow}>
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                    </Box>
                    <Box sx={SX.thirdrow}>
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                    </Box>
                    <Box sx={SX.forthrow}>
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                        <Cell />
                    </Box>
                </Box>
                <Box sx={SX.header} />
                <Box sx={SX.footer}>
                    <Box sx={SX.counter}>{count}</Box>
                </Box>
            </Box>
        );
    }

    // -----------------------------------------------------------------------------------------------------------------
    //  I N T E R N A L
    // -----------------------------------------------------------------------------------------------------------------
}

// =====================================================================================================================
//  E X P O R T
// =====================================================================================================================
export default Main;```

答:
4 things :

If you define your count on the individual Cell component you have one count  by component Cell (so if you want on count for the group, you need to  create a count directly on Main
_ You use count on Main component but where is from, how you take it ?
_ after setState the component directly re-render so you never past by your second setState (your update color, not your count)

for update count on setState, you need to call this.state.count, count is not define

you can't use this.state.count++ because it's mutable but you can use this.state.count + 1

Try cell like this and see the comportement with comment different setState :

```<code>class Cell extends React.Component {
  state = {
    color: "#bbdefb",
    count: 0,
  };

  onChange = () => {
    this.setState({ color: "red" });
    this.setState({ count: this.state.count++ });
    // this.setState({ color: "red", count: this.state.count + 1 });
  };

  render() {
    return (
      <div
        style={{
          backgroundColor: this.state.color,
          width: 20,
          height: 20,
          opacity: "60%",
          outlineStyle: "solid",
          outlineWidth: "1px",
          outlineColor: "#1a237e",
        }}
        onClick={this.onChange}
      >
        {this.state.count}
      </div>
    );
  }
}
</code>```

Title: Reactjs counter onClick

Body:
4 things :

If you define your count on the individual Cell component you have one count  by component Cell (so if you want on count for the group, you need to  create a count directly on Main
_ You use count on Main component but where is from, how you take it ?
_ after setState the component directly re-render so you never past by your second setState (your update color, not your count)

for update count on setState, you need to call this.state.count, count is not define

you can't use this.state.count++ because it's mutable but you can use this.state.count + 1

Try cell like this and see the comportement with comment different setState :

class Cell extends React.Component {
  state = {
    color: "#bbdefb",
    count: 0,
  };

  onChange = () => {
    this.setState({ color: "red" });
    this.setState({ count: this.state.count++ });
    // this.setState({ color: "red", count: this.state.count + 1 });
  };

  render() {
    return (
      <div
        style={{
          backgroundColor: this.state.color,
          width: 20,
          height: 20,
          opacity: "60%",
          outlineStyle: "solid",
          outlineWidth: "1px",
          outlineColor: "#1a237e",
        }}
        onClick={this.onChange}
      >
        {this.state.count}
      </div>
    );
  }
}


问:
Name binding in C
This is more of a theoritical question.Is it possible to bind multiple names to a single object?(either in the stack or heap memory).I know that pointers are not actually considered binding,since the assigned value is a memory address.</p>

答:
Objects residing in the heap are only available as pointers returned by allocation functions, hence bindings do not really apply to this type of object, and it is quite obvious that multiple pointers can point to the same object.

Objects defined with automatic storage, aka on the stack, cannot have multiple bindings as each object definition defines a single identifier.  Parts of union objects can alias the same memory area, and can be referenced via different members, but again, not exactly bindings either.

Global objects (data or code) have the same restrictions, but the linker may map different names to the same location and therefore create different bindings for the same object, possibly with different types. These are usually called aliases and can be controlled with compiler specific pragmas and attributes. This is mostly used for library functions and is beyond the scope of the C Standard, where term binding is not defined, nor used for this purpose.

If the compiler is not aware of these aliases, it may assume that objects defined with different names do not alias one another, hence generate code that may produce unexpected results.

Title: Name binding in C


问:
Separating generic type definition of function in TypeScript?
For instance, in Haskell, having corresponding standalone definitions for each type and function is the standard way to define a function.

The definition of  id in Haskell is:

```<code>id :: forall a. a -> a
id = \a -> a
</code>```

In TypeScript, we can write

```<code>const id = <T>(a: T) => a;
</code>```

but often, I want to define similarly in the manner of Haskell.

```<code>type id<T> = (a:T) => T
const id:id<T> = a => a;
</code>```

This generates an error: Cannot find name 'T'.ts(2304)

Please note:

I know the code below works,

```<code>type id<T> = (a: T) => T
const id: id<number> = a => a;
</code>```

but my Question is for

```<code>const id = <T>(a: T) => a;
</code>```

Is there any proper way to write in the separation manner?

TypeScript Version 4.5.5

答:
```<code>type id = <T>(a: T) => T
const id: id = a => a;
</code>```

Body:
For instance, in Haskell, having corresponding standalone definitions for each type and function is the standard way to define a function.

The definition of  id in Haskell is:

id :: forall a. a -> a
id = \a -> a

In TypeScript, we can write

const id = <T>(a: T) => a;

but often, I want to define similarly in the manner of Haskell.

type id<T> = (a:T) => T
const id:id<T> = a => a;

This generates an error: Cannot find name 'T'.ts(2304)

Please note:

I know the code below works,

type id<T> = (a: T) => T
const id: id<number> = a => a;

but my Question is for

const id = <T>(a: T) => a;

Is there any proper way to write in the separation manner?

TypeScript Version 4.5.5


答:
In C, an object is a:

region of data storage in the execution environment, the contents of which can represent values (§3.5)
Thus,

```<code>union {
    int a;
    int b;
} u;
</code>```

binds u.a and u.b to the same object. (Both names happen to have the same type, but that's not required.)

We could argue about whether a and b are strictly speaking bindings, but the standard seems to say that they are:

An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter.

Title: Name binding in C

Body: This is more of a theoritical question.Is it possible to bind multiple names to a single object?(either in the stack or heap memory).I know that pointers are not actually considered binding,since the assigned value is a memory address.

Body:
In C, an object is a:

region of data storage in the execution environment, the contents of which can represent values (§3.5)
Thus,

union {
    int a;
    int b;
} u;

binds u.a and u.b to the same object. (Both names happen to have the same type, but that's not required.)

We could argue about whether a and b are strictly speaking bindings, but the standard seems to say that they are:

An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter.


问:
Understanding the practical benefits of Durable Functions
I've read a few articles about Azure Durable Functions but for whatever reason the benefit still hasn't quite landed with me.

One article provides a real world example:

Let’s say you’re selling airline tickets. You can imagine that as a
person buys a ticket, we need to:

Check for the availability of the ticket.
Make a request to get the seat map.
Get their mileage points if they’re a loyalty member. Give them a mobile notification if the payment comes through and they have an app
installed

I appreciate this is a workflow with multiple asynchronous awaits, but what's the issue with a standard Azure Function which simply places the API calls and awaits the results before continuing?

It would be great to understand how Durable Functions improve the above example compared to Standard Functions.

答:
You can find (maybe you already did) some scenarios examples on MS pages already:

https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-cloud-backup?tabs=csharp#scenario-overview

https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor?tabs=csharp#scenario-overview

https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor-python#scenario-overview

https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-phone-verification?tabs=csharp#scenario-overview

From own experience we used Durable Functions mostly for the functionality to start over from the point where e.g. function (one of its stages) failed. With this we can like "continue" to complete whole chain only referring to same entity in durable functions. With non-durable function this could also be achieved, of course, but somehow needed additional services like service bus.