答:
Looks like your data bricks has been created within a VNET see this link or this link. When this is done, the databricks instances are created within one of the subnets within this VNET. It seems that at the point of triggering, all the IPs within the subnet were already utilized.
You cannot ad should not extend the IP space. Please do not attempt to change the existing VNET configuration as this will affect your databricks cluster.
You have the following options.

Check when less number of databricks instances are being instantiated and
schedule your ADF during this time. You should be looking at
distributing the execution across the time so we don't attempt to
peak over the existing IPs in the subnet.

Request your IT department to create a new VNET and subnet and
create a new Databricks cluster in this VNET.

Title: Azure Databricks Execution Fail - CLOUD_PROVIDER_LAUNCH_FAILURE

Body:
I'm using Azure DataFactory for my data ingestion and using an Azure Databricks notebook through ADF's Notebook activity.

The Notebook uses an existing instance pool of Standard DS3_V2 (2-5 nodes autoscaled) with 7.3LTS Spark Runtime version. The same Azure subscription is used by multiple teams for their respective data pipelines.

During the ADF pipeline execution, I'm facing a notebook activity failure frequently with the below error message

{
  "reason": {
    "code": "CLOUD_PROVIDER_LAUNCH_FAILURE",
    "type": "CLOUD_FAILURE",
    "parameters": {
      "azure_error_code": "SubnetIsFull",
      "azure_error_message": "Subnet /subscriptions/<Subscription>/resourceGroups/<RG>/providers/Microsoft.Network/virtualNetworks/<VN>/subnets/<subnet> with address prefix 10.237.35.128/26 does not have enough capacity for 2 IP addresses."
    }
  }
}

Can anyone explain what this error is and how I can reduce the occurrence of this? (The documents I found are not explanatory)


来源: stackexchange

问:
Comparing two arrays in C ignoring the order of the elements inside each array
I want to compare two arrays in C, ignoring the order of the elements inside each array, I had two ideas to solve this problem.
Well, they're the same, to be honest. The first idea is to make a variable and increment it with 1 if we find our element inside the second table (please see the code below).
But this one doesn't work if we give it as an example {3, 2, 2, 1} {1, 2, 3, 4}.
the second idea (which I obviously couldn't code) is: setting a variable c=0 for example, after the first loop:

```<code>for (i = 0; i < n; i++) {
    c = 0;
    for (...
}
</code>```

this c will count the number of fails

```<code>if (T1[i] != T2[j]) {
    c += 1
}
</code>```

Then before exiting the j loop, we check if c==n where n is the length of the table. Meaning we have n fails.
after that, unsetting cat the beginning of the i loop

this is my code:

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

int main() {
    int n, i, j, c = 0;
    printf("give the size of the first array: \n");
    scanf("%d", &n);
    int T1[n];
    int T2[n];
    // remplissage de T1
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table1: ", i + 1);
        scanf("%d", &T1[i]);
    }
    // remplissage de T2
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table2: ", i + 1);
        scanf("%d", &T2[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (T1[i] == T2[j]) {
                c += 1;
                break;
            }
        }
    }
    if (c == n) {
        printf("True");
    } else {
        printf("False");
    }
}
</code>```

答:
With this approach

```<code>for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        if (T1[i] == T2[j]) {
            c += 1;
            break;
            }
        }
    }
</code>```

the two arrays int T1[] = { 1, 1, 1, 1, 1 }; and int T2[] = { 1, 2, 3, 4, 5 }; will be always equal.

Also the approach with two pairs of such nested for loops where the arrays are swapped in the if statement will not help. In this case for example these arrays int T1[] = { 1, 2, 2, 2 }; and int T2[] = { 1, 1, 1, 2 }; again will be equal.

If you are allowed to sort arrays then you should sort the both arrays and compare them.

Otherwise you can use the approach shown in the demonstration program below.

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

int main( void )
{
    enum { n = 5 };

    int a1[n] = { 1, 2, 3, 2, 1 };
    int a2[n] = { 3, 2, 2, 1, 1 };

    int equal = 1;
    for (size_t i = 0; equal && i < n; i++)
    {
        size_t count = 1;
        for (size_t j = 0; j != i; j++)
        {
            if (a1[i] == a1[j]) ++count;
        }

        for (size_t j = 0; count && j < n; j++)
        {
            if (a2[j] == a1[i]) --count;
        }

        equal = count == 0;
    }

    printf( "The arrays are %sequal.\n", equal ? "" : "not " );
}
</code>```

The program output is

```<code>The arrays are equal.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to compare two arrays in C, ignoring the order of the elements inside each array, I had two ideas to solve this problem.
Well, they're the same, to be honest. The first idea is to make a variable and increment it with 1 if we find our element inside the second table (please see the code below).
But this one doesn't work if we give it as an example {3, 2, 2, 1} {1, 2, 3, 4}.
the second idea (which I obviously couldn't code) is: setting a variable c=0 for example, after the first loop:

for (i = 0; i < n; i++) {
    c = 0;
    for (...
}

this c will count the number of fails

if (T1[i] != T2[j]) {
    c += 1
}

Then before exiting the j loop, we check if c==n where n is the length of the table. Meaning we have n fails.
after that, unsetting cat the beginning of the i loop

this is my code:

#include <stdio.h>

int main() {
    int n, i, j, c = 0;
    printf("give the size of the first array: \n");
    scanf("%d", &n);
    int T1[n];
    int T2[n];
    // remplissage de T1
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table1: ", i + 1);
        scanf("%d", &T1[i]);
    }
    // remplissage de T2
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table2: ", i + 1);
        scanf("%d", &T2[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (T1[i] == T2[j]) {
                c += 1;
                break;
            }
        }
    }
    if (c == n) {
        printf("True");
    } else {
        printf("False");
    }
}

Body:
With this approach

for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        if (T1[i] == T2[j]) {
            c += 1;
            break;
            }
        }
    }

the two arrays int T1[] = { 1, 1, 1, 1, 1 }; and int T2[] = { 1, 2, 3, 4, 5 }; will be always equal.

Also the approach with two pairs of such nested for loops where the arrays are swapped in the if statement will not help. In this case for example these arrays int T1[] = { 1, 2, 2, 2 }; and int T2[] = { 1, 1, 1, 2 }; again will be equal.

If you are allowed to sort arrays then you should sort the both arrays and compare them.

Otherwise you can use the approach shown in the demonstration program below.

#include <stdio.h>

int main( void )
{
    enum { n = 5 };

    int a1[n] = { 1, 2, 3, 2, 1 };
    int a2[n] = { 3, 2, 2, 1, 1 };

    int equal = 1;
    for (size_t i = 0; equal && i < n; i++)
    {
        size_t count = 1;
        for (size_t j = 0; j != i; j++)
        {
            if (a1[i] == a1[j]) ++count;
        }

        for (size_t j = 0; count && j < n; j++)
        {
            if (a2[j] == a1[i]) --count;
        }

        equal = count == 0;
    }

    printf( "The arrays are %sequal.\n", equal ? "" : "not " );
}

The program output is

The arrays are equal.


问:
Why date comparison gives wrong result?
```<code>$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = date("d.m.Y");

print_r($examDay1 <= $today);  //true

print_r($examDay2 <= $today);  // false as I expected

print_r($examDay3 <= $today);  // true for some reason
</code>```

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

答:
The date() function in php returns a string so you can't use those operators to compare. If you want to be able to compare dates, something like this would work:

```<code>   $examDay1 = new DateTimeImmutable("07.02.2022");
   $examDay2 = new DateTimeImmutable("18.03.2022");
   $examDay3 = new DateTimeImmutable("06.04.2022");

   $today = new DateTimeImmutable('now');

   print_r($examDay1 <= $today);  //true
   print_r($examDay2 <= $today);  // false
   print_r($examDay3 <= $today);  // false
</code>```

If you prefer the procedural style, you can use date_create_immutable() instead of new DateTimeImmutable()

Title: Why date comparison gives wrong result?

Body:
$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = date("d.m.Y");

print_r($examDay1 <= $today);  //true

print_r($examDay2 <= $today);  // false as I expected

print_r($examDay3 <= $today);  // true for some reason

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

Body:
The date() function in php returns a string so you can't use those operators to compare. If you want to be able to compare dates, something like this would work:

   $examDay1 = new DateTimeImmutable("07.02.2022");
   $examDay2 = new DateTimeImmutable("18.03.2022");
   $examDay3 = new DateTimeImmutable("06.04.2022");

   $today = new DateTimeImmutable('now');

   print_r($examDay1 <= $today);  //true
   print_r($examDay2 <= $today);  // false
   print_r($examDay3 <= $today);  // false

If you prefer the procedural style, you can use date_create_immutable() instead of new DateTimeImmutable()


问:
How can I stop dark mode from messing up how my app looks?
I am a student trying to learn app development with android studio. For my first project, im just building a basic calculator app. I have stumbled across a problem that I couldnt solve and didnt find a helpfull post about. It occurs when I trun on dark mode on the virtual device. Here are 2 pictures showing what happens.

How it looks with dark mode

How it is supposed to look

My activity_main.xml consists of some buttons that all have the same style and a TextView.
I left all the other files untouched. Id love some advice on how to fix this. Thanks for reading!

答:
there are two themes : night and not night check in IDE Design tab you can view how it looks in both click the circle in pane where design is displaying it displays Not Night and Night whatever theme you are using it will affect because of these two modes, by default IDE shows not night

To show screen same in both modes you need to change some settings like in your activity_main.xml at root layout change background to @color/white and see what happens it should be sorted out since your button colors are dark ...the text Placeholder color needs to be changed accordingly

```<code><LinearLayout
background=@color/white

other layout etc to follow
</code>```

Body:
there are two themes : night and not night check in IDE Design tab you can view how it looks in both click the circle in pane where design is displaying it displays Not Night and Night whatever theme you are using it will affect because of these two modes, by default IDE shows not night

To show screen same in both modes you need to change some settings like in your activity_main.xml at root layout change background to @color/white and see what happens it should be sorted out since your button colors are dark ...the text Placeholder color needs to be changed accordingly

<LinearLayout
background=@color/white

other layout etc to follow


问:
Calculate Adstock in DAX: how to add value of cell above?
In Power BI I need to build a so called AdStock measure: This is today's value plus a decayed yesterday's value. Easy and straightforward in Excel like this:

But how can I do this in DAX?

The solution of the first answers unfortunately is not correct if AdSpend decreases somewhen, the result is not correct from Index 4 on:

It should look like this:

答:
Calculated Column:

```<code>AdStock :=
VAR AdStockRate = 0.5
VAR ThisIndex = [Index]
RETURN
    [AdSpend]
        + SUMX (
            FILTER ( Table1 , [Index] < ( ThisIndex - [Index] ) ),
            [AdSpend] * AdStockRate ^ [Index]
        )
</code>```

Amend the table name (Table1 here) as required.

Note that I have hard-coded the AdStockRate (0.5) here, though naturally it could be replaced with a dynamic reference.

Or, as a Measure:

```<code>AdStock :=
VAR AdStockRate = 0.5
VAR ThisIndex =
    MIN ( Table1[Index] )
VAR AdSpend =
    MIN ( Table1[AdSpend] )
RETURN
    AdSpend
        + SUMX (
            FILTER ( ALL ( Table1 ), Table1[Index] < ThisIndex ),
            Table1[AdSpend] * AdStockRate ^ ( ThisIndex - Table1[Index] )
        )
</code>```

Body:
Calculated Column:

AdStock :=
VAR AdStockRate = 0.5
VAR ThisIndex = [Index]
RETURN
    [AdSpend]
        + SUMX (
            FILTER ( Table1 , [Index] < ( ThisIndex - [Index] ) ),
            [AdSpend] * AdStockRate ^ [Index]
        )

Amend the table name (Table1 here) as required.

Note that I have hard-coded the AdStockRate (0.5) here, though naturally it could be replaced with a dynamic reference.

Or, as a Measure:

AdStock :=
VAR AdStockRate = 0.5
VAR ThisIndex =
    MIN ( Table1[Index] )
VAR AdSpend =
    MIN ( Table1[AdSpend] )
RETURN
    AdSpend
        + SUMX (
            FILTER ( ALL ( Table1 ), Table1[Index] < ThisIndex ),
            Table1[AdSpend] * AdStockRate ^ ( ThisIndex - Table1[Index] )
        )


问:
Pytorch Linear Regression wrong result on particular dataset
I'm using pytorch to implement a simple linear regression model.
The code works perfectly for randomly created datasets, but when it comes to the dataset I wanted to train, it gives significantly wrong results.

Here is the code:

```<code>x = torch.linspace(1,100,steps=100)
learn_rate = 0.000001
x_train = x[:100]
x_test = x[100:]
y_train = data[:100]
y_test = data[100:]
# y_train = -0.01*x_train + torch.randn(100)*10 #Code for generating random data.
w = torch.rand(1,requires_grad=True)
b= torch.rand(1,requires_grad=True)

for i in range(1000):
  loss = torch.mean((y_train-(w*x_train+b))**2)
  if(i%100==0):
   print(loss)
  loss.backward()
  w.data.add_(-w.grad.data*learn_rate)
  b.data.add_(-b.grad.data*learn_rate)
  w.grad.data.zero_()
  b.grad.data.zero_()

</code>```

The result it gives makes no sense.

However, when I used a randomly generated dataset, it works perfectly:

The dataset actually looks similar. I am not sure for the reason of the inaccuracy of this model.

Code for plotting data:

```<code>plt.plot(x_train.numpy(),y_train.numpy())
plt.plot(x_train.numpy(),(w*x_train+b).data.numpy())
plt.show()
</code>```

--
Now the problem seems to be that weight converges much faster than bias. At the current learning rate, bias will not converge to the optimal. However, if I increase the learning rate just by a little, the weight will simply diverge. I have to set two learning rates.
However, I'm wondering whether setting different learning rate is the best solution for a simple model like this, because I've found out that not much model actually uses different learning rate for different parameters.

答:
Your code seems to be correct, but your model converges slower when there is a large bias in your data (because it now has to update the bias parameter many times before it reaches the correct value).

You could try running it for more iterations or increasing the learning rate.

Body:
I'm using pytorch to implement a simple linear regression model.
The code works perfectly for randomly created datasets, but when it comes to the dataset I wanted to train, it gives significantly wrong results.

Here is the code:

x = torch.linspace(1,100,steps=100)
learn_rate = 0.000001
x_train = x[:100]
x_test = x[100:]
y_train = data[:100]
y_test = data[100:]
# y_train = -0.01*x_train + torch.randn(100)*10 #Code for generating random data.
w = torch.rand(1,requires_grad=True)
b= torch.rand(1,requires_grad=True)

for i in range(1000):
  loss = torch.mean((y_train-(w*x_train+b))**2)
  if(i%100==0):
   print(loss)
  loss.backward()
  w.data.add_(-w.grad.data*learn_rate)
  b.data.add_(-b.grad.data*learn_rate)
  w.grad.data.zero_()
  b.grad.data.zero_()

The result it gives makes no sense.

However, when I used a randomly generated dataset, it works perfectly:

The dataset actually looks similar. I am not sure for the reason of the inaccuracy of this model.

Code for plotting data:

plt.plot(x_train.numpy(),y_train.numpy())
plt.plot(x_train.numpy(),(w*x_train+b).data.numpy())
plt.show()

--
Now the problem seems to be that weight converges much faster than bias. At the current learning rate, bias will not converge to the optimal. However, if I increase the learning rate just by a little, the weight will simply diverge. I have to set two learning rates.
However, I'm wondering whether setting different learning rate is the best solution for a simple model like this, because I've found out that not much model actually uses different learning rate for different parameters.


问:
How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

```<code>|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|
</code>```

When I try this query:

```<code>SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
</code>```

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

答:
Try it:</p>

```<code>SELECT s.Title, s.Desc
FROM Section as s
INNER JOIN (
  SELECT DISTINCT s.id
  FROM Section as s
  INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
) q ON s.Id = q.Id
</code>```

OwnerDisplayName: cdeszaq

ContentLicense: CC BY-SA 2.5

Body:
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|

When I try this query:

SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

Body:
Try it:

SELECT s.Title, s.Desc
FROM Section as s
INNER JOIN (
  SELECT DISTINCT s.id
  FROM Section as s
  INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
) q ON s.Id = q.Id

OwnerDisplayName: Ekeko

LastEditorDisplayName: Ekeko


问:
Displaying views that contain 'partial'/'nested' widgets in EXTjs 4
I'm having trouble understanding how I need to define and use the MVC model for my test EXTjs4 app. Consider the following structure.

app.js

```<code>Ext.application({
    name: 'AM',
    appFolder: 'app',
    controllers: ['Cards', 'Fourscrum'],
    launch: function () {
        Ext.create('Ext.container.Viewport', {
            defaults: { flex: 1 },
            layout: {
                type: 'hbox',
                align: 'stretch',
            },
            items:
            [
                Ext.widget('Fourscrum')
            ]
        });
</code>```

Controller:

Cards.js

```<code>Ext.define('AM.controller.Cards', {
    extend: 'Ext.app.Controller',
        stores: ['BacklogCards', 'InprogressCards', 'ReviewCards', 'DoneCards', 'Cards', 'Priorities', 'Sizes'],
        models: ['Card', 'Priority', 'Size'],
        views: ['card.List', 'priority.prioritycombo', 'card.Edit'],
</code>```

Fourscrum.js

```<code>Ext.define('AM.controller.Fourscrum', {
    extend: 'Ext.app.Controller',
    stores: ['BacklogCards', 'InprogressCards', 'ReviewCards', 'DoneCards', 'Cards', 'Priorities', 'Sizes'],
    models: ['Card', 'Priority', 'Size'],
    views: ['scrum.Fourscrum', 'card.List'],
</code>```

view.scrum.Fourscrum.js

```<code>Ext.define('AM.view.scrum.Fourscrum', {   // *** Variable
    extend: 'Ext.panel.Panel',
    alias: 'widget.Fourscrum',       // *** Variable

    width: 400,
    height: 300,

    layout: 'column',

    title: 'Scrum',                  // *** Variable
    items:
    [
        Ext.widget('cardlist',
        {
            alias: 'widget.backlogcardlist',
            title: "Backlog",
            store: 'BacklogCards'
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.backlogcardlist',
            title: "Backlog",
            store: 'BacklogCards'
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.inprogresscardlist',
            title: "In Progress",
            store: "InprogressCards"
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.reviewcardlist',
            title: "Review",
            store: "ReviewCards"
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.donecardlist',
            title: "Done",
            store: "DoneCards"
        })
    ]

});
</code>```

My ideal structure for this app is as follows:

Viewport defined (inside app.js)

which contains a Fourscrum.js view (which is just a panel)

which contains 4 different List.js views (which are just grids).

Trying to accomplish this, I currently get a few errors when i start messing with the above code:

Item undefined

namespace undefined

Does anyone know why this doesn't work?

PS. I can get this example to work if I replace my 'cardlist' widgets with panels directly defined in the Fourscrum view.

PPS. This also works properly if I forego the Fourscrum container panel all together :(

EDIT:

I felt my explanation was a little unclear so I've uploaded an image to help describe the program. I'm not sure where I need to define the stores, models, and views with this nested structure. So I've repeated it in both controllers. I hope that's not what is causing the problem.

EDIT2:

```<code>Ext.define('AM.view.card.List', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.cardlist',

    //title: 'List',
    //store: 'Cards',

    //multiSelect: true,
    viewConfig: {
        plugins: {
            ptype: 'gridviewdragdrop',
            dragGroup: 'ddzone',
            dropGroup: 'ddzone'
        }
    },
    //            selType: 'cellmodel',
    //            plugins: [
    //                Ext.create('Ext.grid.plugin.CellEditing', {
    //                    clicksToEdit: 1
    //                })
    //            ],

    columns: [
        {
            header: 'ID',
            dataIndex: 'external_id',
            field: 'textfield',
            width: 30
        },
        {
            header: 'Name',
            dataIndex: 'name',
            field: 'textfield',
            width: 150
        },
        {
            header: 'Priority',
            dataIndex: 'priority_id',
            renderer: function (value) {
                var display = '';
                Ext.data.StoreManager.get("Priorities").each(function (rec) {
                    if (rec.get('id') === value) {
                        display = rec.get('short_name');
                        return false;
                    }
                });
                return display;
            },
            width: 60,
            field: { xtype: 'PriorityCombo' }
        },
        {
            header: 'Size',
            dataIndex: 'size_id',
            renderer: function (value) {
                var display = '';
                Ext.data.StoreManager.get("Sizes").each(function (rec) {
                    if (rec.get('id') === value) {
                        display = rec.get('short_name');
                        return false;
                    }
                });
                return display;
            },
            width: 60
        },
        {
            xtype: 'actioncolumn',
            width: 16,
            items: [{
                icon: 'Styles/Images/zoom.png',  // Use a URL in the icon config
                tooltip: 'Zoom In',
                handler: function (grid, rowIndex, colIndex) {
                    var rec = grid.getStore().getAt(rowIndex);
                    alert("Edit " + rec.get('name'));
                }
            }]
        }
    ]

});
</code>```

答:
I think I see a big problem in your code (if you pasted all of it).
In your view definitions if you are extending Ext components you MUST have the following function  that ends in the callParent method like below.</p>

```<code>initComponent: function() {
  this.items = this.buildMyItems();

  this.callParent(arguments);
},

buildMyItems: function(){
  //my code
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble understanding how I need to define and use the MVC model for my test EXTjs4 app. Consider the following structure.

app.js

Ext.application({
    name: 'AM',
    appFolder: 'app',
    controllers: ['Cards', 'Fourscrum'],
    launch: function () {
        Ext.create('Ext.container.Viewport', {
            defaults: { flex: 1 },
            layout: {
                type: 'hbox',
                align: 'stretch',
            },
            items:
            [
                Ext.widget('Fourscrum')
            ]
        });

Controller:

Cards.js

Ext.define('AM.controller.Cards', {
    extend: 'Ext.app.Controller',
        stores: ['BacklogCards', 'InprogressCards', 'ReviewCards', 'DoneCards', 'Cards', 'Priorities', 'Sizes'],
        models: ['Card', 'Priority', 'Size'],
        views: ['card.List', 'priority.prioritycombo', 'card.Edit'],

Fourscrum.js

Ext.define('AM.controller.Fourscrum', {
    extend: 'Ext.app.Controller',
    stores: ['BacklogCards', 'InprogressCards', 'ReviewCards', 'DoneCards', 'Cards', 'Priorities', 'Sizes'],
    models: ['Card', 'Priority', 'Size'],
    views: ['scrum.Fourscrum', 'card.List'],

view.scrum.Fourscrum.js

Ext.define('AM.view.scrum.Fourscrum', {   // *** Variable
    extend: 'Ext.panel.Panel',
    alias: 'widget.Fourscrum',       // *** Variable

    width: 400,
    height: 300,

    layout: 'column',

    title: 'Scrum',                  // *** Variable
    items:
    [
        Ext.widget('cardlist',
        {
            alias: 'widget.backlogcardlist',
            title: "Backlog",
            store: 'BacklogCards'
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.backlogcardlist',
            title: "Backlog",
            store: 'BacklogCards'
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.inprogresscardlist',
            title: "In Progress",
            store: "InprogressCards"
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.reviewcardlist',
            title: "Review",
            store: "ReviewCards"
        }),
        Ext.widget('cardlist',
        {
            alias: 'widget.donecardlist',
            title: "Done",
            store: "DoneCards"
        })
    ]

});

My ideal structure for this app is as follows:

Viewport defined (inside app.js)

which contains a Fourscrum.js view (which is just a panel)

which contains 4 different List.js views (which are just grids).

Trying to accomplish this, I currently get a few errors when i start messing with the above code:

Item undefined

namespace undefined

Does anyone know why this doesn't work?

PS. I can get this example to work if I replace my 'cardlist' widgets with panels directly defined in the Fourscrum view.

PPS. This also works properly if I forego the Fourscrum container panel all together :(

EDIT:

I felt my explanation was a little unclear so I've uploaded an image to help describe the program. I'm not sure where I need to define the stores, models, and views with this nested structure. So I've repeated it in both controllers. I hope that's not what is causing the problem.

EDIT2:

Ext.define('AM.view.card.List', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.cardlist',

    //title: 'List',
    //store: 'Cards',

    //multiSelect: true,
    viewConfig: {
        plugins: {
            ptype: 'gridviewdragdrop',
            dragGroup: 'ddzone',
            dropGroup: 'ddzone'
        }
    },
    //            selType: 'cellmodel',
    //            plugins: [
    //                Ext.create('Ext.grid.plugin.CellEditing', {
    //                    clicksToEdit: 1
    //                })
    //            ],

    columns: [
        {
            header: 'ID',
            dataIndex: 'external_id',
            field: 'textfield',
            width: 30
        },
        {
            header: 'Name',
            dataIndex: 'name',
            field: 'textfield',
            width: 150
        },
        {
            header: 'Priority',
            dataIndex: 'priority_id',
            renderer: function (value) {
                var display = '';
                Ext.data.StoreManager.get("Priorities").each(function (rec) {
                    if (rec.get('id') === value) {
                        display = rec.get('short_name');
                        return false;
                    }
                });
                return display;
            },
            width: 60,
            field: { xtype: 'PriorityCombo' }
        },
        {
            header: 'Size',
            dataIndex: 'size_id',
            renderer: function (value) {
                var display = '';
                Ext.data.StoreManager.get("Sizes").each(function (rec) {
                    if (rec.get('id') === value) {
                        display = rec.get('short_name');
                        return false;
                    }
                });
                return display;
            },
            width: 60
        },
        {
            xtype: 'actioncolumn',
            width: 16,
            items: [{
                icon: 'Styles/Images/zoom.png',  // Use a URL in the icon config
                tooltip: 'Zoom In',
                handler: function (grid, rowIndex, colIndex) {
                    var rec = grid.getStore().getAt(rowIndex);
                    alert("Edit " + rec.get('name'));
                }
            }]
        }
    ]

});

Body:
I think I see a big problem in your code (if you pasted all of it).
In your view definitions if you are extending Ext components you MUST have the following function  that ends in the callParent method like below.

initComponent: function() {
  this.items = this.buildMyItems();

  this.callParent(arguments);
},

buildMyItems: function(){
  //my code
}


问:
how to fix the error passing data problem in flutter
in order to get the weather of a location I've created a LoadingScreen class as shown bellow :

```<code>import 'package:flutter/material.dart';
import '../services/location.dart';
import '../services/networking.dart';
 import './location_screen.dart';
  const apiKey = 'd8cdd9eca073d9bbf5ef49405cbf50e8';

class LoadingScreen extends StatefulWidget {
  const LoadingScreen({ Key? key }) : super(key: key);

  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
    double? longitude;
    double? lattitude;

  @override
  void initState() {
    // TODO: implement initStat
    super.initState();
     getLocationData();
  }
  void getLocationData() async {
       Location located = Location();
     await  located.getLocation();

     longitude = located.longitude;
     lattitude  = located.lattitude;
     print(longitude);
     print(lattitude);
  NetworkHelper networkhelper =
 NetworkHelper('https://api.openweathermap.org/data/2.5/weather?lat=$lattitude&lon=$longitude&appid=$apiKey');

   var weatherdata =  await networkhelper.getData();

/*  Navigator.push(context, MaterialPageRoute(
        builder: (context) {
          return  LocationScreen(
            locationWeather: weatherdata,
            );
          },
        ),
        );*/
     Navigator.of(context).pushNamed(LocationScreen.routeName, arguments: weatherdata);
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
         body: Center(child: CircularProgressIndicator()),
    );
  }
}

</code>```

with the help of the Network class, I've seperated getdata method as shown in the code bellow :

```<code>import 'package:http/http.dart' as http;
import 'dart:convert';

class NetworkHelper {

    final String url;
    NetworkHelper(this.url);

  Future getData() async{

   var response =   await http.get(Uri.parse(url));

   if (response.statusCode == 200) {

         String  data = response.body;
         return jsonDecode(data);

   } else {
     print(response.statusCode);
   }

  }

}
</code>```

when the app opens..it shows a spiner to navigate through the LocationScreen page :

```<code>import 'package:flutter/material.dart';

class LocationScreen extends StatefulWidget {

 // var locationWeather;

 //LocationScreen({this.locationWeather});

    static const routeName = '/location-screen';
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
    double? temperature;
    int? condition;
    String? cityName;

    @override
    void intiState(){

   var weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;

    updateUi(weatherData);
     super.initState();
    }

   void updateUi(dynamic weatherData){
     try {
        temperature = weatherData['main']['temp'];
      condition = weatherData['weather'][0]['id'];
      cityName = weatherData['name'];
      print(temperature);
     } catch (e) {
       print('An error has occured, please try again');
     }

   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image:DecorationImage(
            image: AssetImage('images/location_background.jpg'),
            fit: BoxFit.cover,
               colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.8), BlendMode.dstATop),
            ),
        ),
        constraints: BoxConstraints.expand(),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                    ElevatedButton(
                      onPressed: (){},
                      child: Icon(Icons.arrow_back_ios,
                      size: 50,
                      ),
                      ),
                    TextButton(
                      onPressed: (){},
                       child: Icon(Icons.location_city,
                       size: 50,
                       ),
                       ),
                ],
              ),
              Padding(
                padding:  EdgeInsets.only(left: 15),
                child: Row(
                  children: [
                    Text('32°', style: TextStyle(
                        fontFamily: 'Spartan MB',
                        fontSize: 100,
                    ),
                    ),
                    Text('☀', style: TextStyle(
                      fontSize: 100.0,
                    ),
                    ),
                  ],
                ),
                 ),
                 Padding(padding: EdgeInsets.only(right: 20),
                 child: Text("It's  time in San Francisco!",
                 textAlign: TextAlign.right,
                  style: TextStyle(
                     fontFamily: 'Spartan MB',
                     fontSize: 60.0,
                  ),
                  ),
                 ),
            ],
          ),
          ),
             ),
    );
  }
}
</code>```

I've passed the weather data using Navigator.of(context).pushNamed method
but when I tried to get the data in order to update the LocationScreen ..I couldn't receive anything (print(temperature) doesn't work) knowing that, when I printed the weather data in the getlocationdata method ..everything worked so that mean there were no problem with my API url ..so where is the problem?

code of the main.dart :

```<code>import 'package:flutter/material.dart';
import './screens/loading_screen.dart';
import './screens/location_screen.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
      routes: {
        LocationScreen.routeName: (ctx) => LocationScreen(),
      },
    );
  }
}
</code>```

Thank you in advance for your help

答:
There's a typo inside the class _LocationScreenState. It says intiState() when it should be initState().

The IDE should give a warning "The method doesn't override an inherited method" because of the typo.

Also, you can't use ModalRoute.of(context) in initState. It wouldn't make sense because initState is supposed to be executed only once, but usually Something.of(context) means it might change over time. If you try to use it in initState(), flutter gives an error saying that you should use didChangeDependencies() instead. So you should delete your initState() and write this instead:

```<code>@override
void didChangeDependencies() {
  super.didChangeDependencies();
  var weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;
  updateUi(weatherData);
}
</code>```

Also, if you're going to change some state variables, you always have to surround them with setState(() { ... }). Otherwise the widget doesn't update on the screen. So add these two lines:

```<code>void updateUi(dynamic weatherData){
  try {
    setState(() {      //      <--- ADD THIS LINE!
      temperature = weatherData['main']['temp'];
      condition = weatherData['weather'][0]['id'];
      cityName = weatherData['name'];
      print(temperature);
    });                //      <--- ADD THIS LINE!
  } catch (e) {
    print('An error has occured, please try again');
  }
}
</code>```

OR, You could also just make it a StatelessWidget instead of StatefulWidget. Then things would be simpler. You could get rid of updateUi() and you wouldn't need these variables in the class:

```<code>double? temperature;
int? condition;
String? cityName;
</code>```

Instead you would just query the ModalRoute in the build method like this:

```<code>@override
Widget build(BuildContext context) {
  final weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;
  final double? temperature = weatherData['main']['temp'];
  final int? condition = weatherData['weather'][0]['id'];
  final String? cityName = weatherData['name'];
  print('temperature: $temperature');
  return Scaffold(
    body: Container(
      ...
</code>```

Whether StatefulWidget or StatelessWidget is better, depends on where you want to handle possible run-time changes in the weather display (if you're planning to make the app so that the weather info will change during run-time). If you want to handle the changes inside LocationScreen, then it should be StatefulWidget. Otherwise it should be a StatelessWidget and merely display the data that's coming from somewhere else.

Body:
in order to get the weather of a location I've created a LoadingScreen class as shown bellow :

import 'package:flutter/material.dart';
import '../services/location.dart';
import '../services/networking.dart';
 import './location_screen.dart';
  const apiKey = 'd8cdd9eca073d9bbf5ef49405cbf50e8';

class LoadingScreen extends StatefulWidget {
  const LoadingScreen({ Key? key }) : super(key: key);

  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
    double? longitude;
    double? lattitude;

  @override
  void initState() {
    // TODO: implement initStat
    super.initState();
     getLocationData();
  }
  void getLocationData() async {
       Location located = Location();
     await  located.getLocation();

     longitude = located.longitude;
     lattitude  = located.lattitude;
     print(longitude);
     print(lattitude);
  NetworkHelper networkhelper =
 NetworkHelper('https://api.openweathermap.org/data/2.5/weather?lat=$lattitude&lon=$longitude&appid=$apiKey');

   var weatherdata =  await networkhelper.getData();

/*  Navigator.push(context, MaterialPageRoute(
        builder: (context) {
          return  LocationScreen(
            locationWeather: weatherdata,
            );
          },
        ),
        );*/
     Navigator.of(context).pushNamed(LocationScreen.routeName, arguments: weatherdata);
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
         body: Center(child: CircularProgressIndicator()),
    );
  }
}

with the help of the Network class, I've seperated getdata method as shown in the code bellow :

import 'package:http/http.dart' as http;
import 'dart:convert';

class NetworkHelper {

    final String url;
    NetworkHelper(this.url);

  Future getData() async{

   var response =   await http.get(Uri.parse(url));

   if (response.statusCode == 200) {

         String  data = response.body;
         return jsonDecode(data);

   } else {
     print(response.statusCode);
   }

  }

}

when the app opens..it shows a spiner to navigate through the LocationScreen page :

import 'package:flutter/material.dart';

class LocationScreen extends StatefulWidget {

 // var locationWeather;

 //LocationScreen({this.locationWeather});

    static const routeName = '/location-screen';
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
    double? temperature;
    int? condition;
    String? cityName;

    @override
    void intiState(){

   var weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;

    updateUi(weatherData);
     super.initState();
    }

   void updateUi(dynamic weatherData){
     try {
        temperature = weatherData['main']['temp'];
      condition = weatherData['weather'][0]['id'];
      cityName = weatherData['name'];
      print(temperature);
     } catch (e) {
       print('An error has occured, please try again');
     }

   }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image:DecorationImage(
            image: AssetImage('images/location_background.jpg'),
            fit: BoxFit.cover,
               colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.8), BlendMode.dstATop),
            ),
        ),
        constraints: BoxConstraints.expand(),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                    ElevatedButton(
                      onPressed: (){},
                      child: Icon(Icons.arrow_back_ios,
                      size: 50,
                      ),
                      ),
                    TextButton(
                      onPressed: (){},
                       child: Icon(Icons.location_city,
                       size: 50,
                       ),
                       ),
                ],
              ),
              Padding(
                padding:  EdgeInsets.only(left: 15),
                child: Row(
                  children: [
                    Text('32°', style: TextStyle(
                        fontFamily: 'Spartan MB',
                        fontSize: 100,
                    ),
                    ),
                    Text('☀', style: TextStyle(
                      fontSize: 100.0,
                    ),
                    ),
                  ],
                ),
                 ),
                 Padding(padding: EdgeInsets.only(right: 20),
                 child: Text("It's  time in San Francisco!",
                 textAlign: TextAlign.right,
                  style: TextStyle(
                     fontFamily: 'Spartan MB',
                     fontSize: 60.0,
                  ),
                  ),
                 ),
            ],
          ),
          ),
             ),
    );
  }
}

I've passed the weather data using Navigator.of(context).pushNamed method
but when I tried to get the data in order to update the LocationScreen ..I couldn't receive anything (print(temperature) doesn't work) knowing that, when I printed the weather data in the getlocationdata method ..everything worked so that mean there were no problem with my API url ..so where is the problem?

code of the main.dart :

import 'package:flutter/material.dart';
import './screens/loading_screen.dart';
import './screens/location_screen.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
      routes: {
        LocationScreen.routeName: (ctx) => LocationScreen(),
      },
    );
  }
}

Thank you in advance for your help

Body:
There's a typo inside the class _LocationScreenState. It says intiState() when it should be initState().

The IDE should give a warning "The method doesn't override an inherited method" because of the typo.

Also, you can't use ModalRoute.of(context) in initState. It wouldn't make sense because initState is supposed to be executed only once, but usually Something.of(context) means it might change over time. If you try to use it in initState(), flutter gives an error saying that you should use didChangeDependencies() instead. So you should delete your initState() and write this instead:

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  var weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;
  updateUi(weatherData);
}

Also, if you're going to change some state variables, you always have to surround them with setState(() { ... }). Otherwise the widget doesn't update on the screen. So add these two lines:

void updateUi(dynamic weatherData){
  try {
    setState(() {      //      <--- ADD THIS LINE!
      temperature = weatherData['main']['temp'];
      condition = weatherData['weather'][0]['id'];
      cityName = weatherData['name'];
      print(temperature);
    });                //      <--- ADD THIS LINE!
  } catch (e) {
    print('An error has occured, please try again');
  }
}

OR, You could also just make it a StatelessWidget instead of StatefulWidget. Then things would be simpler. You could get rid of updateUi() and you wouldn't need these variables in the class:

double? temperature;
int? condition;
String? cityName;

Instead you would just query the ModalRoute in the build method like this:

@override
Widget build(BuildContext context) {
  final weatherData = ModalRoute.of(context)!.settings.arguments as dynamic;
  final double? temperature = weatherData['main']['temp'];
  final int? condition = weatherData['weather'][0]['id'];
  final String? cityName = weatherData['name'];
  print('temperature: $temperature');
  return Scaffold(
    body: Container(
      ...

Whether StatefulWidget or StatelessWidget is better, depends on where you want to handle possible run-time changes in the weather display (if you're planning to make the app so that the weather info will change during run-time). If you want to handle the changes inside LocationScreen, then it should be StatefulWidget. Otherwise it should be a StatelessWidget and merely display the data that's coming from somewhere else.


问:
Find consecutively increasing numbers in subarray C++
I am currently working on finding at least 4 and 5 consecutive numbers (such as {3, 4, 5, 6} and {2, 3, 4, 5, 6}) in one row of a 2D array.

For example, if you were given a 2D array like this:

```<code>int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};
</code>```

How would you go about testing if only the subarray {6, 3, 4, 5, 1} has at least 4 consecutive numbers?

Here is what I considered at first (please note that I am new to C++):

```<code>int lowerStraight(int arr[][5]) {

    //lower straight code
    int lowerStraightSum = 0;
    int minNum, nextNum, threeNum, fourNum;
    minNum = findMin(arr);
    nextNum = minNum + 1;
    threeNum = nextNum + 1;
    fourNum = threeNum + 1;
    for (int i = 0; i < 5; i++) {
        if (arr[1][i] == nextNum) {
            if (arr[1][i] == threeNum) {
                if (arr[1][i] == fourNum) {
                    lowerStraightSum = 30;
            }
        }
    }
}
cout << lowerStraightSum;
return lowerStraightSum; }
</code>```

The code above prints 0 even if the array has 4 or more consecutive numbers. Plus, it assumes that the minimum number is where the consecutive numbers start, which may not be the case. Any advice on both of these things is appreciated.

答:
It will help you to split the big problem into more smaller problems. Make a function for the smaller problem and call it from an "above" to solve the bigger problem.

So let us first forget about many rows in a 2 dimansional matrix, but just on one row. One row is a simple array.

And the we analyze the requirement "consecutive numbers". Somthing like, 4,5,6,7,8.

If we look at these numbers, then we find out that main property of such a sequence is that the delta between one number and another number is 1.

So, looking at the array "90, 80, 70, 1, 2, 3, 4, 5, 60, 50, 40" we could iterate over the array and check if a "number - the previous number" is 1.

Then we can count, how many times we get a delta of one. For this we can use a counter. Because we look at sequences with 4 or 5 elements, we can compare the counter with 4 or 5. If the counter is below 4 or 5, and the delta is not 1, then we reset the counter and count again, if we find more consecutive numbers.

Your statement "at least 4 and 5" implies, that also longer sequences are OK. But it is a little bit ambigous. Because we then would not need to look at 5. Just >= 4 would be sufficient.

But this can be dealt with easily.

There are really many possible implementations.

Here is one of them in easy words

```<code>#include <iostream>

// Specify matrix size
const int NumberOfRows = 5;
const int NumberOfColumns = 5;

// Define some test data
int arr[NumberOfRows][NumberOfColumns] = {
    {1, 2, 3, 4, 5},
    {3, 4, 6, 1, 1},
    {6, 3, 4, 5, 1},
    {6, 1, 2, 3, 3},
    {1, 2, 3, 4, 6},
};

// Calculate max Number of consecutives in one row
int consecutives(int row[NumberOfColumns]) {

    // Here we will store the result
    int maxConsecutives = 0;

    // Current consecutives
    int consecutiveCounter = 1;

    // Check deltas
    for (int column = 1; column < NumberOfColumns; ++column) {
        if ((row[column] - row[column - 1]) == 1) {

            // We found a consecutive. Increment counter
            ++consecutiveCounter;
        }
        else {
            // This value is not a consecutive one.
            // Save the max value of consectutive values
            if (consecutiveCounter > maxConsecutives)

                // Save new max value
                maxConsecutives = consecutiveCounter;

            consecutiveCounter = 1;
        }
    }
    if (consecutiveCounter > maxConsecutives)

        // Save new max value
        maxConsecutives = consecutiveCounter;
    return maxConsecutives;
}
int main() {
    for (int row = 0; row < NumberOfRows; ++row) {

        int con = consecutives(arr[row]);

        if (con >= 4)
            std::cout << "Row " << row << " has at least " << con << " consecutives\n";
    }
}
</code>```

Body:
I am currently working on finding at least 4 and 5 consecutive numbers (such as {3, 4, 5, 6} and {2, 3, 4, 5, 6}) in one row of a 2D array.

For example, if you were given a 2D array like this:

int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};

How would you go about testing if only the subarray {6, 3, 4, 5, 1} has at least 4 consecutive numbers?

Here is what I considered at first (please note that I am new to C++):

int lowerStraight(int arr[][5]) {

    //lower straight code
    int lowerStraightSum = 0;
    int minNum, nextNum, threeNum, fourNum;
    minNum = findMin(arr);
    nextNum = minNum + 1;
    threeNum = nextNum + 1;
    fourNum = threeNum + 1;
    for (int i = 0; i < 5; i++) {
        if (arr[1][i] == nextNum) {
            if (arr[1][i] == threeNum) {
                if (arr[1][i] == fourNum) {
                    lowerStraightSum = 30;
            }
        }
    }
}
cout << lowerStraightSum;
return lowerStraightSum; }

The code above prints 0 even if the array has 4 or more consecutive numbers. Plus, it assumes that the minimum number is where the consecutive numbers start, which may not be the case. Any advice on both of these things is appreciated.

Body:
It will help you to split the big problem into more smaller problems. Make a function for the smaller problem and call it from an "above" to solve the bigger problem.

So let us first forget about many rows in a 2 dimansional matrix, but just on one row. One row is a simple array.

And the we analyze the requirement "consecutive numbers". Somthing like, 4,5,6,7,8.

If we look at these numbers, then we find out that main property of such a sequence is that the delta between one number and another number is 1.

So, looking at the array "90, 80, 70, 1, 2, 3, 4, 5, 60, 50, 40" we could iterate over the array and check if a "number - the previous number" is 1.

Then we can count, how many times we get a delta of one. For this we can use a counter. Because we look at sequences with 4 or 5 elements, we can compare the counter with 4 or 5. If the counter is below 4 or 5, and the delta is not 1, then we reset the counter and count again, if we find more consecutive numbers.

Your statement "at least 4 and 5" implies, that also longer sequences are OK. But it is a little bit ambigous. Because we then would not need to look at 5. Just >= 4 would be sufficient.

But this can be dealt with easily.

There are really many possible implementations.

Here is one of them in easy words

#include <iostream>

// Specify matrix size
const int NumberOfRows = 5;
const int NumberOfColumns = 5;

// Define some test data
int arr[NumberOfRows][NumberOfColumns] = {
    {1, 2, 3, 4, 5},
    {3, 4, 6, 1, 1},
    {6, 3, 4, 5, 1},
    {6, 1, 2, 3, 3},
    {1, 2, 3, 4, 6},
};

// Calculate max Number of consecutives in one row
int consecutives(int row[NumberOfColumns]) {

    // Here we will store the result
    int maxConsecutives = 0;

    // Current consecutives
    int consecutiveCounter = 1;

    // Check deltas
    for (int column = 1; column < NumberOfColumns; ++column) {
        if ((row[column] - row[column - 1]) == 1) {

            // We found a consecutive. Increment counter
            ++consecutiveCounter;
        }
        else {
            // This value is not a consecutive one.
            // Save the max value of consectutive values
            if (consecutiveCounter > maxConsecutives)

                // Save new max value
                maxConsecutives = consecutiveCounter;

            consecutiveCounter = 1;
        }
    }
    if (consecutiveCounter > maxConsecutives)

        // Save new max value
        maxConsecutives = consecutiveCounter;
    return maxConsecutives;
}
int main() {
    for (int row = 0; row < NumberOfRows; ++row) {

        int con = consecutives(arr[row]);

        if (con >= 4)
            std::cout << "Row " << row << " has at least " << con << " consecutives\n";
    }
}


问:
JavaScript: get code to run every minute
Is there a way to make some JS code be executed every 60 seconds? I'm thinking it might be possible with a while loop, but is there a neater solution? JQuery welcome, as always.

答:
to call a function on exactly the start of every minute

let date = new Date();
let sec = date.getSeconds();
setTimeout(()=>{
  setInterval(()=>{
    // do something
  }, 60 * 1000);
}, (60 - sec) * 1000);
```


问:
How to visit an array indexed by indexed in php / Laravel?
I got an API response like

["at123@gmail.com","adhd5@gmail.com","adahsad5@gmail.com"]

I got this array in a request variable $request->optional_email I am trying to access data by a loop like below:

foreach ($request->optional_email as $key => $optionalEmail) {
    $email->email = $optionalEmail[$key];
    $email->save();
}
```

But it doesn't work. How can I solve it?

答:
As the $request->optional_email is just a list you do not need to use the $key variable in the foreach.
Instead you should just use the value ($optionalEmail) of the foreach so your code would look something like this:

foreach ($request->optional_email as $optionalEmail) {
    $email->email = $optionalEmail;
    $email->save();
}
```

Body:
I got an API response like

["at123@gmail.com","adhd5@gmail.com","adahsad5@gmail.com"]

I got this array in a request variable $request->optional_email I am trying to access data by a loop like below:

foreach ($request->optional_email as $key => $optionalEmail) {
    $email->email = $optionalEmail[$key];
    $email->save();
}

But it doesn't work. How can I solve it?


问:
sql trigger to stop duplicates across row
I have a table with multiple records:

User_Name     ( e.g. 'TOM')

Question_ID    (eg 'q002')

Answer         (e.g. 'D')

i want to create a trigger so that no one can submit an answer to the same question twice.
It has to be a trigger only.

```<code>CREATE TRIGGER trigger_Check_Duplicates

ON submit_Answer

FOR INSERT
AS

IF SELECT???

PRINT 'duplicate'

raiserror('cant submit answer to same question twice')

ROLLBACK

End
</code>```

答:
Create trigger </p>

```<code>CREATE TRIGGER dbo.uniqueUserQuestion
ON dbo.submit_Answer
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    IF EXISTS
    (
        SELECT 1
        FROM dbo.submit_Answer T
        INNER JOIN INSERTED I
        ON T.user_name = I.user_name
            AND T.question_id = I.question_id
    )
    BEGIN
        -- Do dupe handling here
        PRINT 'duplicate'
        raiserror('cant submit answer to same question twice')
        return
    END

    -- actually add it in
    INSERT INTO
        dbo.submit_Answer
    SELECT
        *
    FROM
        INSERTED I
END
GO
</code>```

Body:
I have a table with multiple records:

User_Name     ( e.g. 'TOM')

Question_ID    (eg 'q002')

Answer         (e.g. 'D')

i want to create a trigger so that no one can submit an answer to the same question twice.
It has to be a trigger only.

CREATE TRIGGER trigger_Check_Duplicates

ON submit_Answer

FOR INSERT
AS

IF SELECT???

PRINT 'duplicate'

raiserror('cant submit answer to same question twice')

ROLLBACK

End

Body:
Create trigger

CREATE TRIGGER dbo.uniqueUserQuestion
ON dbo.submit_Answer
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    IF EXISTS
    (
        SELECT 1
        FROM dbo.submit_Answer T
        INNER JOIN INSERTED I
        ON T.user_name = I.user_name
            AND T.question_id = I.question_id
    )
    BEGIN
        -- Do dupe handling here
        PRINT 'duplicate'
        raiserror('cant submit answer to same question twice')
        return
    END

    -- actually add it in
    INSERT INTO
        dbo.submit_Answer
    SELECT
        *
    FROM
        INSERTED I
END
GO


问:
How to refresh page with button in js document with node.js?
I have tried switching the button to be above the script, and also tried making a function in the app.js file. None of these two methods work.</p>
```<code>res.write("<script>" + "function refreshPage() {location.reload()}" + "</script>")
res.write('<br> <button onclick=' + '"refreshPage()">')

</code>```

答:
you can always use
window.location.reload() to reload the page
or maybe simulate the Ctrl + R action using keydown or keypress event, I hope this was helpful

Body:
I have tried switching the button to be above the script, and also tried making a function in the app.js file. None of these two methods work.

res.write("")
res.write('
 <button onclick=' + '"refreshPage()">')


问:
Postgres parse vacation days test to table
I have a table that store configurations and I need to use them in a query.
The starting table has its value stored as this text:

---
'1':
  '1': New Year's Day
  '6': Epiphany
'11':
  '1': All the Saints
'12':
  '24': Christmas Eve
  '25': First Christmas Day
  '26': Second Christmas Day
  '31': New Year's Eve
'5':
  '1': International Workers' Day
'8':
  '15': Mid-August
```

In the second row, for example, I have the month, end in the third row, with a two space indentation, I have the number of the day with its description separated with a colon.

I want to have it in a table like this one:

id
description
month
day

1
New Year's Day
1
1

I put an example in db<>fiddle.

答:
More dark regex sorcery to transform text data into a json format.

So that the data can be extracted via json methods.

```<code>INSERT INTO holidays (holiday,description)
select
  make_date(2018, l2.Month, l2.Day) as holiday
, l2.Name as description
from test
cross join lateral (
  select
  regexp_replace(
   regexp_replace(
    regexp_replace(
     regexp_replace(wh,
      '^\W+(\d+)\W+(\w.*)$',' {"day":"\1","name":"\2"},','gm')
    , '^''(\d+)'':', '{"month":"\1","days":[','gm')
    , '\},(\s*)(?=\{"month"|$)', '}\1]},','g')
    , '^.*?(\{.*\}).*$', '[\1]')::json as whjs
) l1
cross join lateral (
  select
    (mjs.value->>'month')::int as Month
  , (djs.value->>'day'):: int as Day
  , djs.value->>'name' as Name
  from json_array_elements(l1.whjs) mjs
  cross join lateral json_array_elements(mjs.value->'days') djs
) l2
</code>```
```
9 rows affected
```

```<code>select * from holidays;
</code>```

id
description
holiday

1
New Year's Day
2018-01-01

2
Epiphany
2018-01-06

3
All the Saints
2018-11-01

4
Christmas Eve
2018-12-24

5
First Christmas Day
2018-12-25

6
Second Christmas Day
2018-12-26

7
New Year's Eve
2018-12-31

8
International Workers' Day
2018-05-01

9
Mid-August
2018-08-15

Test on db<>fiddle here

Body:
I have a table that store configurations and I need to use them in a query.
The starting table has its value stored as this text:

---
'1':
  '1': New Year's Day
  '6': Epiphany
'11':
  '1': All the Saints
'12':
  '24': Christmas Eve
  '25': First Christmas Day
  '26': Second Christmas Day
  '31': New Year's Eve
'5':
  '1': International Workers' Day
'8':
  '15': Mid-August

In the second row, for example, I have the month, end in the third row, with a two space indentation, I have the number of the day with its description separated with a colon.

I want to have it in a table like this one:

id
description
month
day

1
New Year's Day
1
1

I put an example in db<>fiddle.

Body:
More dark regex sorcery to transform text data into a json format.

So that the data can be extracted via json methods.

INSERT INTO holidays (holiday,description)
select
  make_date(2018, l2.Month, l2.Day) as holiday
, l2.Name as description
from test
cross join lateral (
  select
  regexp_replace(
   regexp_replace(
    regexp_replace(
     regexp_replace(wh,
      '^\W+(\d+)\W+(\w.*)$',' {"day":"\1","name":"\2"},','gm')
    , '^''(\d+)'':', '{"month":"\1","days":[','gm')
    , '\},(\s*)(?=\{"month"|$)', '}\1]},','g')
    , '^.*?(\{.*\}).*$', '[\1]')::json as whjs
) l1
cross join lateral (
  select
    (mjs.value->>'month')::int as Month
  , (djs.value->>'day'):: int as Day
  , djs.value->>'name' as Name
  from json_array_elements(l1.whjs) mjs
  cross join lateral json_array_elements(mjs.value->'days') djs
) l2

9 rows affected

select * from holidays;

id
description
holiday

1
New Year's Day
2018-01-01

2
Epiphany
2018-01-06

3
All the Saints
2018-11-01

4
Christmas Eve
2018-12-24

5
First Christmas Day
2018-12-25

6
Second Christmas Day
2018-12-26

7
New Year's Eve
2018-12-31

8
International Workers' Day
2018-05-01

9
Mid-August
2018-08-15

Test on db<>fiddle here


问:
Laravel Collection Macro Filter by Today
I have the following scenario:

A businesses table whose model has transactions as:

    public function transactions(): HasMany {
        return $this->hasMany(Transaction::class);
    }
```
<ol start="2">
<li>A transactions table (transactions belong to a business) - has an id, amount and timestamp columns.</li>
</ol>
<p>I am displaying all the businesses in a blade view with their transactions count and value. Now I want to filter the transaction count and value by today's date. I have seen the best way is to do a Collection Macro. Here is what I have so far in App Service Provider (which is not working):</p>
```Collection::macro('filterByToday', function ($value) {
     return $this->filter(function ($value) {
         return $value->created_at === Carbon::today();
     });
});
```
<p>How can I write this macro such that in blade I can loop through all the businesses displaying this transactions like:</p>
```@foreach($businesses as $business)
   Count: {{ $business->transaction->filterByToday()->count() }}
   Value: {{ $business->transaction->filterByToday()->sum('amount') }}
@endforeach
```

答:
Your macro should not receive any arguments and be defined in the boot method of a ServiceProvider class.

If you're using a custom ServiceProvider class, make sure it is registered in the $providers array in config/app.php

# AppServiceProvider
public function boot()
{
    Collection::macro('filterByToday', function () { // <-- 0 arguments
        return $this->filter(function ($value) {
            return $value->created_at === Carbon::today();
        });
    });
}
```

Body:
I have the following scenario:

A businesses table whose model has transactions as:

    public function transactions(): HasMany {
        return $this->hasMany(Transaction::class);
    }

A transactions table (transactions belong to a business) - has an id, amount and timestamp columns.

I am displaying all the businesses in a blade view with their transactions count and value. Now I want to filter the transaction count and value by today's date. I have seen the best way is to do a Collection Macro. Here is what I have so far in App Service Provider (which is not working):

Collection::macro('filterByToday', function ($value) {
     return $this->filter(function ($value) {
         return $value->created_at === Carbon::today();
     });
});

How can I write this macro such that in blade I can loop through all the businesses displaying this transactions like:

@foreach($businesses as $business)
   Count: {{ $business->transaction->filterByToday()->count() }}
   Value: {{ $business->transaction->filterByToday()->sum('amount') }}
@endforeach


问:
Switching git users
According to this SO question (here) and many others, you can change the user you are working with by simply

```<code>git config user.name "username1"
git config user.password "password1"
</code>```

Ok. Great that's done, and when I check with

```<code>git config user.name //I get username1
</code>```

But as soon as I push to my git repo that I created in the account using that username, I get...

```<code>remote: Permission to username1/reponame.git denied to username2
</code>```

I should mention, when I type

```<code>ssh -T git@github.com
</code>```

I get

```<code>Hi username2! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

So, ssh authentication takes over any other way of signing into git? How can I maintain that ssh authentication with username2 for the username2/repo.git (work github account), while still being able to switch to username1/repo.git (personal github account)?

答:
You are trying to configure git, but the truth is that you need to configure ssh for two different users. Your ssh does not know nothing about your git configuration - you need to prepare your .ssh/config in such a way so that you could work with GitHub (in your case) from two different accounts.

This is how I do it:

```<code>Host github.com
        User git
        IdentityFile ~/.ssh/id_ed25519-account1
Host github-account2
        User git
        IdentityFile ~/.ssh/id_ed25519-account2
</code>```

Here, whenever I need to work with account1 on GitHub - it will just work. However, if I need to work from my another account - I change remotes by replacing github.com part to github-account2, like this:

git clone git@github-account2:torvalds/linux.git

Title: Switching git users

Body:
According to this SO question (here) and many others, you can change the user you are working with by simply

git config user.name "username1"
git config user.password "password1"

Ok. Great that's done, and when I check with

git config user.name //I get username1

But as soon as I push to my git repo that I created in the account using that username, I get...

remote: Permission to username1/reponame.git denied to username2

I should mention, when I type

ssh -T git@github.com

I get

Hi username2! You've successfully authenticated, but GitHub does not provide shell access.

So, ssh authentication takes over any other way of signing into git? How can I maintain that ssh authentication with username2 for the username2/repo.git (work github account), while still being able to switch to username1/repo.git (personal github account)?

Body:
You are trying to configure git, but the truth is that you need to configure ssh for two different users. Your ssh does not know nothing about your git configuration - you need to prepare your .ssh/config in such a way so that you could work with GitHub (in your case) from two different accounts.

This is how I do it:

Host github.com
        User git
        IdentityFile ~/.ssh/id_ed25519-account1
Host github-account2
        User git
        IdentityFile ~/.ssh/id_ed25519-account2

Here, whenever I need to work with account1 on GitHub - it will just work. However, if I need to work from my another account - I change remotes by replacing github.com part to github-account2, like this:

git clone git@github-account2:torvalds/linux.git


问:
discord.py problems with on_member_join()
What am I doing wrong?

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role_1 = member.guild.get_role(start_role_id)
    await member.add_roles(role_1)
```

I searched for answers on the forums for a long time and nothing helped.

答:
Did you enable intents in Discord Developer Portal? while initializing bot add intents=discord.Intents.all(). Also I fixed your code.

```<code>bot = commands.Bot(command_prefix='', intents=discord.Intents.all())

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role1 = discord.utils.get(member.server.roles, id=role_id)
    await member.add_roles(role1)
</code>```

Body:
What am I doing wrong?

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role_1 = member.guild.get_role(start_role_id)
    await member.add_roles(role_1)

I searched for answers on the forums for a long time and nothing helped.

Body:
Did you enable intents in Discord Developer Portal? while initializing bot add intents=discord.Intents.all(). Also I fixed your code.

bot = commands.Bot(command_prefix='', intents=discord.Intents.all())

@bot.event
async def on_member_join(member):
    print(f"{member} join")
    role1 = discord.utils.get(member.server.roles, id=role_id)
    await member.add_roles(role1)


问:
Prettier package not getting detected by WebStorm IDE
I just started using WebStorm lately, and I always used Prettier for my projects inside VS Code, so I wanted to implement it here, but encountered a problem when WebStorm doesn't detect Prettier installation.

When I'm heading into Settings > Languages & Frameworks > Prettier I can't choose the package in "Prettier package" dropdown menu. Yeah I can link the installation myself, but every time I create a new project the settings are getting reset (as well with "Run with files") so it's not the way to go.

How can I fix the problem? I already checked node.js path, reinstalled Prettier using -G multiple times, updated node, but nothing helped me. Any solutions?

答:
globally install prettier:
npm install --global prettier

then from webstorm, go to Prettier preferences, insert this path under Prettier package: /usr/local/lib/node_modules/prettier

this is where your global node_modules are installed (not project level).

choose which files it should run for, insert {**/*,*}.{js,ts,jsx,tsx} for JS/ TS files.

Happy coding!


问:
service crash with "Context.startForegroundService() did not then call Service.startForeground()"
Hello friends. I use this code inside the service for the pedometer service and I will
encounter the following error. Thank you for your help.

*error
android.app.RemoteServiceException: Context.startForegroundService() did not then call
Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

```<code>class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    try {
        running = true
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
    } catch (e: Exception) {

    }
    return START_STICKY

}

override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onSensorChanged(event: SensorEvent?) {
    if (running) {
        totalStep = event!!.values[0]
        val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
        Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
    }
}

override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun stopService(name: Intent?): Boolean {
    return super.stopService(name)
}

override fun onDestroy() {
    val intent = Intent(this, MyPhoneReciver::class.java)
    sendBroadcast(intent)
    super.onDestroy()
}
</code>```

}

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

答:
Android O you can set the background limitation as below;</p>
```<code>    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context!!.startForegroundService(Intent(context, MyService::class.java))
    } else {
        context!!.startService(Intent(context, MyService::class.java))
    }
</code>```

Body:
Hello friends. I use this code inside the service for the pedometer service and I will
encounter the following error. Thank you for your help.

*error
android.app.RemoteServiceException: Context.startForegroundService() did not then call
Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    try {
        running = true
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
    } catch (e: Exception) {

    }
    return START_STICKY

}

override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onSensorChanged(event: SensorEvent?) {
    if (running) {
        totalStep = event!!.values[0]
        val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
        Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
    }
}

override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun stopService(name: Intent?): Boolean {
    return super.stopService(name)
}

override fun onDestroy() {
    val intent = Intent(this, MyPhoneReciver::class.java)
    sendBroadcast(intent)
    super.onDestroy()
}

}

Body:
Android O you can set the background limitation as below;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context!!.startForegroundService(Intent(context, MyService::class.java))
    } else {
        context!!.startService(Intent(context, MyService::class.java))
    }


问:
Setting QPixmap size to fill space in QGridLayout
I have been trying to display an image in a QGridLayout, and resize it according to the space available to it. However I can't seem to get the right size.

I have created a class ImageWidget(Qwidget), which is what is referenced as self below, and an instance of which ImageWidget0 is added to the QGridLayout Layout with Layout.addWidget(ImageWidget0, 0, 0).

This is how I'm resizing the pixmap, and it is displaying the image in the layout  at the specified size with no problems:

self.label = QLabel(self)
self.pixmap = self.pixmap.scaled(image_size[0], image_size[1], Qt.KeepAspectRatio)
self.label.setPixmap(self.pixmap)
self.show()
```
<p>However different methods of assigning <code>image_size</code> are giving undesirable results. Both of the following, using the size of the widget and the size of the label respectively, produce an <code>image_size</code> of (100, 30), which is too small:</p>
<pre class="lang-py prettyprint-override"><code>image_size = (self.width(), self.height())
image_size = (self.label.width(), self.label.height())
</code>```

So I tried to get the size of the rows and columns instead using the only methods I could find in the QGridLayout documentation, but the following (perhaps unsuprisingly) both produce an image_size of (0, 0):

image_size = (self.parent().layout.columnMinimumWidth(0), self.parent().layout.rowMinimumHeight(0))
image_size = (self.parentWidget().layout.columnMinimumWidth(0), self.parentWidget().layout.rowMinimumHeight(0))
```

To be clear: The layout itself is NOT CHANGING for all these different pixmap sizes. If image_size is manually set too large, it clips out (which is fine), but when it is too small, it just shrinks in the available space. This is what make me think the problem doesn't lie in the layout adjusting to the pixmap size.

I can post more code if required, but I was trying to keep this succinct and to the point.

答:
As @musicamante pointed out, it is pointless using the widget size at construction as the layout has not yet been set. I got around this by adding a "load image" button, which could add the image once the layout had been created, allowing me to set the size correctly using:

image_size = (self.width(), self.height())
image_size = (self.width(), self.height())
```

Body:
I have been trying to display an image in a QGridLayout, and resize it according to the space available to it. However I can't seem to get the right size.

I have created a class ImageWidget(Qwidget), which is what is referenced as self below, and an instance of which ImageWidget0 is added to the QGridLayout Layout with Layout.addWidget(ImageWidget0, 0, 0).

This is how I'm resizing the pixmap, and it is displaying the image in the layout  at the specified size with no problems:

self.label = QLabel(self)
self.pixmap = self.pixmap.scaled(image_size[0], image_size[1], Qt.KeepAspectRatio)
self.label.setPixmap(self.pixmap)
self.show()

However different methods of assigning image_size are giving undesirable results. Both of the following, using the size of the widget and the size of the label respectively, produce an image_size of (100, 30), which is too small:

image_size = (self.width(), self.height())
image_size = (self.label.width(), self.label.height())

So I tried to get the size of the rows and columns instead using the only methods I could find in the QGridLayout documentation, but the following (perhaps unsuprisingly) both produce an image_size of (0, 0):

image_size = (self.parent().layout.columnMinimumWidth(0), self.parent().layout.rowMinimumHeight(0))
image_size = (self.parentWidget().layout.columnMinimumWidth(0), self.parentWidget().layout.rowMinimumHeight(0))

To be clear: The layout itself is NOT CHANGING for all these different pixmap sizes. If image_size is manually set too large, it clips out (which is fine), but when it is too small, it just shrinks in the available space. This is what make me think the problem doesn't lie in the layout adjusting to the pixmap size.

I can post more code if required, but I was trying to keep this succinct and to the point.


问:
How to align both the Text and the labelText in the TextFormField in center vertically and without affecting the border?
If you notice the below image, both the label and the text is aligned to top.

Can any one help with what has to be done to make the alignment to centre these two vertically?

Also if you notice just above the 'Email' the border is cut. Could some one help with code snippet to avoid this?

Also is there any way, can we format based on the content(value) of the 'TextFormField'?

The following are the coding which produces the above images.

```<code>TextFormField(
  decoration: InputDecoration(
    fillColor: Colors.white,
    filled: true,
    contentPadding: EdgeInsets.all(10.0),
    labelText: 'Email:',
    labelStyle: TextStyle(color: Colors.red, height: 3),
    prefixIcon: Icon(Icons.email_outlined),
    enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.white, width: 1.0)),
    focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red, width: 2.0)),
    prefixStyle: TextStyle(
      inherit: true,
      color: Colors.red,
    ),
 ),
</code>```

Ideally I wanted a text box like the below one

答:
Flutter allows two types of Edit Input.

Filled Text Field (if the border uses UnderlineInputBorder)

Outlined Text Field (if the border uses OutlineInputBorder)

The following code snippet helped me to fix the issue.

```<code>   Container(
      padding: EdgeInsets.zero,
      decoration: BoxDecoration(border: Border.all()),
      child: TextFormField(
         decoration: const InputDecoration(
            fillColor: Colors.white,
            filled: true,
            contentPadding: EdgeInsets.all(10.0),
            labelText: 'Email:',
            labelStyle: TextStyle(color: Colors.red, height: 1),
            prefixIcon: Icon(Icons.email_outlined),
            enabledBorder: UnderlineInputBorder(
                     borderSide: BorderSide(color: Colors.transparent)),
            focusedBorder: UnderlineInputBorder(
                     borderSide: BorderSide(color: Colors.transparent)),
            prefixStyle: TextStyle(
               inherit: true,
               color: Colors.red,
            ),
         ),
      ),
   )
</code>```

Body:
If you notice the below image, both the label and the text is aligned to top.

Can any one help with what has to be done to make the alignment to centre these two vertically?

Also if you notice just above the 'Email' the border is cut. Could some one help with code snippet to avoid this?

Also is there any way, can we format based on the content(value) of the 'TextFormField'?

The following are the coding which produces the above images.

TextFormField(
  decoration: InputDecoration(
    fillColor: Colors.white,
    filled: true,
    contentPadding: EdgeInsets.all(10.0),
    labelText: 'Email:',
    labelStyle: TextStyle(color: Colors.red, height: 3),
    prefixIcon: Icon(Icons.email_outlined),
    enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.white, width: 1.0)),
    focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red, width: 2.0)),
    prefixStyle: TextStyle(
      inherit: true,
      color: Colors.red,
    ),
 ),

Ideally I wanted a text box like the below one

Body:
Flutter allows two types of Edit Input.

Filled Text Field (if the border uses UnderlineInputBorder)

Outlined Text Field (if the border uses OutlineInputBorder)

The following code snippet helped me to fix the issue.

   Container(
      padding: EdgeInsets.zero,
      decoration: BoxDecoration(border: Border.all()),
      child: TextFormField(
         decoration: const InputDecoration(
            fillColor: Colors.white,
            filled: true,
            contentPadding: EdgeInsets.all(10.0),
            labelText: 'Email:',
            labelStyle: TextStyle(color: Colors.red, height: 1),
            prefixIcon: Icon(Icons.email_outlined),
            enabledBorder: UnderlineInputBorder(
                     borderSide: BorderSide(color: Colors.transparent)),
            focusedBorder: UnderlineInputBorder(
                     borderSide: BorderSide(color: Colors.transparent)),
            prefixStyle: TextStyle(
               inherit: true,
               color: Colors.red,
            ),
         ),
      ),
   )


问:
NLog environment variable config files
I'm stuck on this kinda simple problem. I'm trying to make multiple nlog config files, so that nlog can load them depending on environment variable.
I've added nlog.debug.config, nlog.production.config, and changed ASPNETCORE_ENVIRONMENT to corresponding value,  but no luck so far. I guess it's not that simple. I could set it up inside Startup.cs file, like this:

```<code>env.ConfigureNLog("nlog.environment.config");
</code>```

But is there some automatic way?

答:
The accepted answer is good, but NLog provides a standard way to do this as well.  The .NET Core appsettings.json file is already environment specific, and you can configure NLog within these files.

For example, in appsettings.Staging.json you could have one "NLog" element and a different setting in appsettings.Production.json.

Here is the documentation.

Title: NLog environment variable config files

Body:
I'm stuck on this kinda simple problem. I'm trying to make multiple nlog config files, so that nlog can load them depending on environment variable.
I've added nlog.debug.config, nlog.production.config, and changed ASPNETCORE_ENVIRONMENT to corresponding value,  but no luck so far. I guess it's not that simple. I could set it up inside Startup.cs file, like this:

env.ConfigureNLog("nlog.environment.config");

But is there some automatic way?


问:
QUERY speed with limit and milion records
Hi i have a 7milion records db table for testing query speed.

I tested up my 2 queries which are the same query with different limit parametres:

query 1 -

```<code>SELECT    *
FROM      table
LIMIT     20, 50;
</code>```

query 2 -

```<code>SELECT    *
FROM      table
LIMIT     6000000, 6000030;
</code>```

query exec times are:

query 1 - 0.006 sec

query 2 - 5.500 sec

In both of these queries, I am fetching same number of records, but in the second case it's taking more time. Can someone please explain the reasons behind this?

答:
It's the difference between returning 50 rows and 6000030 rows (or ~1million rows since you said there were only 7million rows).

With two arguments, the first argument specifies the offset of the
  first row to return, and the second specifies the maximum number of
  rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

http://dev.mysql.com/doc/refman/5.0/en/select.html

Also, I think you're looking for 30 row pages so your queries should be using 30 as the second parameter in the limit clause.

```<code>SELECT    *
FROM      table
LIMIT     20, 30;

SELECT    *
FROM      table
LIMIT     6000000, 30;
</code>```

Body:
Hi i have a 7milion records db table for testing query speed.

I tested up my 2 queries which are the same query with different limit parametres:

query 1 -

SELECT    *
FROM      table
LIMIT     20, 50;

query 2 -

SELECT    *
FROM      table
LIMIT     6000000, 6000030;

query exec times are:

query 1 - 0.006 sec

query 2 - 5.500 sec

In both of these queries, I am fetching same number of records, but in the second case it's taking more time. Can someone please explain the reasons behind this?

Body:
It's the difference between returning 50 rows and 6000030 rows (or ~1million rows since you said there were only 7million rows).

With two arguments, the first argument specifies the offset of the
  first row to return, and the second specifies the maximum number of
  rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

http://dev.mysql.com/doc/refman/5.0/en/select.html

Also, I think you're looking for 30 row pages so your queries should be using 30 as the second parameter in the limit clause.

SELECT    *
FROM      table
LIMIT     20, 30;

SELECT    *
FROM      table
LIMIT     6000000, 30;


问:
PowerShell merging data from multiple CSVs
I have a bunch of CSV files containing information about DHCP scopes (100+ files, one for each server). I wish to merge the data from all into a new table. There are ways to merge the CSVs but that's not good enough, because one the most important piece of information is not included inside the individual CSV files...that of the server name. The server name is coming from the filename itself. Hence the approach to build a new table.

My issue is that the properties for SubnetMask, StartRange, EndRange, ScopeID and State are being output in the same "cell". I managed to do it for the ScopeName (i.e. managed to get one ScopeName per line), but not sure how to approach the rest.

```<code>$outputTable = $null
$files = Get-ChildItem -Path "C:\Temp\Discovery\" -Filter *Scopes.csv
Write-Host $files
ForEach($file in $files)
{
    $scopeFile = Import-Csv $file

    ForEach ($scopeName in $scopeFile.Name)
    {
        $outputTable += @(
                    [pscustomobject]@{
                    ` DHCPServer=$file.Name.ToString().Split(".")[0];
                    ` ScopeName=$scopeName;
                    ` SubnetMask=$scopeFile.SubnetMask;
                    ` StartRange=$scopeFile.StartRange;
                    ` EndRange=$scopeFile.EndRange;
                    ` ScopeID=$scopeFile.ScopeID
                    ` State=$scopeFile.State
                    }
                )
    }
}

$outputTable | ft
</code>```

Current output:

Expected output:

```<code>DHCPServerName,ScopeName,SubnetMask,StartRange,EndRange,ScopeID,State
server1,london,255.255.0.0,192.168.0.1,192.168.0.254,192.168.0.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,NotActive
</code>```

答:
You can use a calculated property with Select-Object to add the file's Name as a new column of your Csv:

```<code>$merged = foreach($file in Get-ChildItem -Path C:\Temp\Discovery\ -Filter *Scopes.csv)
{
    Import-Csv $file.FullName | Select-Object @{
        Name = 'DHCPServerName'
        Expression = { $file.Name.Split(".")[0] }
    }, *
}

$merged | Format-Table
</code>```

Body:
I have a bunch of CSV files containing information about DHCP scopes (100+ files, one for each server). I wish to merge the data from all into a new table. There are ways to merge the CSVs but that's not good enough, because one the most important piece of information is not included inside the individual CSV files...that of the server name. The server name is coming from the filename itself. Hence the approach to build a new table.

My issue is that the properties for SubnetMask, StartRange, EndRange, ScopeID and State are being output in the same "cell". I managed to do it for the ScopeName (i.e. managed to get one ScopeName per line), but not sure how to approach the rest.

$outputTable = $null
$files = Get-ChildItem -Path "C:\Temp\Discovery\" -Filter *Scopes.csv
Write-Host $files
ForEach($file in $files)
{
    $scopeFile = Import-Csv $file

    ForEach ($scopeName in $scopeFile.Name)
    {
        $outputTable += @(
                    [pscustomobject]@{
                    ` DHCPServer=$file.Name.ToString().Split(".")[0];
                    ` ScopeName=$scopeName;
                    ` SubnetMask=$scopeFile.SubnetMask;
                    ` StartRange=$scopeFile.StartRange;
                    ` EndRange=$scopeFile.EndRange;
                    ` ScopeID=$scopeFile.ScopeID
                    ` State=$scopeFile.State
                    }
                )
    }
}

$outputTable | ft

Current output:

Expected output:

DHCPServerName,ScopeName,SubnetMask,StartRange,EndRange,ScopeID,State
server1,london,255.255.0.0,192.168.0.1,192.168.0.254,192.168.0.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,Active
server1,london,255.255.0.0,192.168.1.1,192.168.0.254,192.168.1.1,NotActive

Body:
You can use a calculated property with Select-Object to add the file's Name as a new column of your Csv:

$merged = foreach($file in Get-ChildItem -Path C:\Temp\Discovery\ -Filter *Scopes.csv)
{
    Import-Csv $file.FullName | Select-Object @{
        Name = 'DHCPServerName'
        Expression = { $file.Name.Split(".")[0] }
    }, *
}

$merged | Format-Table


问:
JavaScript Error Element is null: while interacting ShadownDom element
I am writing code in Javascript to automate the website https://www.fashionette.co.uk/. I have to use cookies when the user lands on the page for the first time

I am writing the following code to get cookies:

```<code>JavascriptExecutor js = (JavascriptExecutor)webdriver;
WebElement element= (WebElement) js.executeScript("return document.getElementById('usercentrics-root').shadowRoot.querySelector(\"[data-testid='uc-accept-all-button']\");");
            element.click()
</code>```

it locate element in browser correctly:

But In Intellij it gives me error:

```<code>java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.click()" because "element" is null
</code>```

答:
If you are using Java create a browser instance and find elements:

```<code>System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
WebElement WE = driver.findElementByCss("YourCSSSelector");
WE.click();
</code>```

If you are using JavaScript change your into:

```<code>WebElement element = (WebElement) js.executeScript
("document.getElementById('usercentrics-root').
shadowRoot.querySelector(\"[data-testid='uc-accept-all-button'])\");
</code>```

Body:
I am writing code in Javascript to automate the website https://www.fashionette.co.uk/. I have to use cookies when the user lands on the page for the first time

I am writing the following code to get cookies:

JavascriptExecutor js = (JavascriptExecutor)webdriver;
WebElement element= (WebElement) js.executeScript("return document.getElementById('usercentrics-root').shadowRoot.querySelector(\"[data-testid='uc-accept-all-button']\");");
            element.click()

it locate element in browser correctly:

But In Intellij it gives me error:

java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.click()" because "element" is null

Body:
If you are using Java create a browser instance and find elements:

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
WebElement WE = driver.findElementByCss("YourCSSSelector");
WE.click();

If you are using JavaScript change your into:

WebElement element = (WebElement) js.executeScript
("document.getElementById('usercentrics-root').
shadowRoot.querySelector(\"[data-testid='uc-accept-all-button'])\");