问:
How to handle realign of components in runtime after screen resize delphi
I searched a lot in google to get a clearer info on how I could solve my current issue, but I got scalability of components as the best answer, that's... not yet my issue.

So, long story short: I want to realign components on my form after the user resizes the window, the form is populated dinamically from a SQL query, this is the constructor code:

```<code>procedure TForm2.MakeWindow;
var
  dummyMaskedit, dummyEdit: TEdit;
  dummyMemo: TMemo;
  dummyCombobox: TComboBox;
  dummyLabel: TLabel;
  dummyLBox: TListBox;
  dummybutton: TButton;
  i, f: integer;
  buffer, workarea: double;
begin
  FDQDB.Close;
  FDQDB.Open('SELECT * FROM Defs WHERE active = 1');

  i := 0;
  f := 1;
  buffer := Layout1.Width;
  workarea := Layout1.Width;
  SetLength(aMasks, 0);
  while not FDQDB.Eof do
  begin
    case AnsiIndexStr(FDQDB.FieldByName('comptype').AsString,
      ['tedit', 'tcombobox', 'tmaskedit', 'tlistbox']) of
      0: // TEdit
        begin
          dummyEdit := TEdit.Create(self);
          dummyEdit.Parent := Form2.Layout1;
          dummyEdit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyEdit.Width >= 0 then
          begin
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end;
          dummyEdit.Name := 'field' + IntToStr(f);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyEdit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyEdit.Position.Y - 17;
            Position.X := dummyEdit.Position.X;
          end;
        end;

      1: // TComboBox
        begin
          dummyCombobox := TComboBox.Create(self);
          dummyCombobox.Parent := Form2.Layout1;
          dummyCombobox.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyCombobox.Width >= 0 then
          begin
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end;
          dummyCombobox.Name := 'field' + IntToStr(f);
          dummyCombobox.Items.Delimiter := '|';
          dummyCombobox.Items.StrictDelimiter := true;
          dummyCombobox.Items.DelimitedText :=
            AnsiUpperCase(FDQDB.FieldByName('combovalue').AsString);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyCombobox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyCombobox.Position.Y - 17;
            Position.X := dummyCombobox.Position.X;
          end;
        end;

      2: // TMaskEdit
        begin
          dummyMaskedit := TEdit.Create(self);
          dummyMaskedit.Parent := Form2.Layout1;
          dummyMaskedit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyMaskedit.Width >= 0 then
          begin
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end;
          dummyMaskedit.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyMaskedit.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyMaskedit.OnExit := MaskTextExit;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyMaskedit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyMaskedit.Position.Y - 17;
            Position.X := dummyMaskedit.Position.X;
          end;
        end;

      3: // TListBox
        begin
          dummyLBox := TListBox.Create(self);
          dummyLBox.Parent := Form2.Layout1;
          dummyLBox.Width := FDQDB.FieldByName('size').AsInteger;
          inc(i);
          buffer := workarea;
          if buffer - dummyLBox.Width >= 0 then
          begin
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end;
          dummyLBox.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyLBox.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyLBox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyLBox.Position.Y - 17;
            Position.X := dummyLBox.Position.X;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '+';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y;
            Name := 'ba' + dummyLBox.Name;
            OnClick := ButtonsAddClick;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '-';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y + 28;
            Name := 'br' + dummyLBox.Name;
            OnClick := ButtonsRemClick;
          end;
        end;
    end;
    FDQDB.Next;
  end;
  FDQDB.Close;
end;
</code>```

That works nice and pretty on the windowed state of the application, this code is applied to the onCreate event of the form:

```<code>procedure TForm2.FormCreate(Sender: TObject);
begin
  FDCDB.Params.Database := ExtractFilePath(ParamStr(0)) + 'window.db';
  MakeWindow;
end;
</code>```

The first form, main form of the application, is the one that summons the new form that has the components built in runtime:

```<code>procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
end;
</code>```

The second form has a TLayout, just like the first form. Then, when I create the form I bring the TLayout of the second form to the first. So far so good, it works when the application is launched in windowed mode.
But when I put form1 in fullscreen mode, then click the Button that creates the form2, the components stays on the same position as in windowed mode. I've tried changing the workarea variable to these:

```<code>Screen.width, //components behave as the application were in fullscreen the whole time
Screen.WorkAreaWidth, //same as screen.width
(Layout1.Parent as TLayout).Width, //invalid typecast
(Layout1.GetParentComponent as TLayout).Width //invalid typecast
</code>```

None of them worked.
I wanna be able to adjust the position of the components on the screen based on its visual width, so if the user resizes the window before creating the new form, the components gets aligned properly.
Anyone knows a solution for that? Thanks in advance

答:
But when I put form1 in fullscreen mode, then click the Button that
  creates the form2, the components stays on the same position as in
  windowed mode.

At TForm1.SpeedButton1Click() you call Application.CreateForm(TForm2, Form2); which triggers TForm2.FormCreate(Sender: TObject); which calls MakeWindow. At this point Form2 knows only about the design time size.

After MakeWindow is done, the TForm1.SpeedButton1Click() continues:

```<code>Form2.Layout1.parent := Self.Layout1.Parent;
Form2.Layout1.Width := Self.Layout1.Width;
</code>```

but these do not anymore affect the layout of the controls.

You need to set Form2.Layout1.Width before you call MakeWindow, for example:

```<code>procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
  MakeWindow; // remove it from TForm2.FormCreate()
end;
</code>```

Body:
I searched a lot in google to get a clearer info on how I could solve my current issue, but I got scalability of components as the best answer, that's... not yet my issue.

So, long story short: I want to realign components on my form after the user resizes the window, the form is populated dinamically from a SQL query, this is the constructor code:

procedure TForm2.MakeWindow;
var
  dummyMaskedit, dummyEdit: TEdit;
  dummyMemo: TMemo;
  dummyCombobox: TComboBox;
  dummyLabel: TLabel;
  dummyLBox: TListBox;
  dummybutton: TButton;
  i, f: integer;
  buffer, workarea: double;
begin
  FDQDB.Close;
  FDQDB.Open('SELECT * FROM Defs WHERE active = 1');

  i := 0;
  f := 1;
  buffer := Layout1.Width;
  workarea := Layout1.Width;
  SetLength(aMasks, 0);
  while not FDQDB.Eof do
  begin
    case AnsiIndexStr(FDQDB.FieldByName('comptype').AsString,
      ['tedit', 'tcombobox', 'tmaskedit', 'tlistbox']) of
      0: // TEdit
        begin
          dummyEdit := TEdit.Create(self);
          dummyEdit.Parent := Form2.Layout1;
          dummyEdit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyEdit.Width >= 0 then
          begin
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyEdit.Width - 8;
            dummyEdit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyEdit.Position.X := workarea - buffer - dummyEdit.Width + 5;
          end;
          dummyEdit.Name := 'field' + IntToStr(f);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyEdit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyEdit.Position.Y - 17;
            Position.X := dummyEdit.Position.X;
          end;
        end;

      1: // TComboBox
        begin
          dummyCombobox := TComboBox.Create(self);
          dummyCombobox.Parent := Form2.Layout1;
          dummyCombobox.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyCombobox.Width >= 0 then
          begin
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyCombobox.Width - 8;
            dummyCombobox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyCombobox.Position.X := workarea - buffer -
              dummyCombobox.Width + 5;
          end;
          dummyCombobox.Name := 'field' + IntToStr(f);
          dummyCombobox.Items.Delimiter := '|';
          dummyCombobox.Items.StrictDelimiter := true;
          dummyCombobox.Items.DelimitedText :=
            AnsiUpperCase(FDQDB.FieldByName('combovalue').AsString);
          inc(f);

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyCombobox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyCombobox.Position.Y - 17;
            Position.X := dummyCombobox.Position.X;
          end;
        end;

      2: // TMaskEdit
        begin
          dummyMaskedit := TEdit.Create(self);
          dummyMaskedit.Parent := Form2.Layout1;
          dummyMaskedit.Width := FDQDB.FieldByName('size').AsInteger;
          if buffer - dummyMaskedit.Width >= 0 then
          begin
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyMaskedit.Width - 8;
            dummyMaskedit.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyMaskedit.Position.X := workarea - buffer -
              dummyMaskedit.Width + 5;
          end;
          dummyMaskedit.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyMaskedit.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyMaskedit.OnExit := MaskTextExit;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyMaskedit.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyMaskedit.Position.Y - 17;
            Position.X := dummyMaskedit.Position.X;
          end;
        end;

      3: // TListBox
        begin
          dummyLBox := TListBox.Create(self);
          dummyLBox.Parent := Form2.Layout1;
          dummyLBox.Width := FDQDB.FieldByName('size').AsInteger;
          inc(i);
          buffer := workarea;
          if buffer - dummyLBox.Width >= 0 then
          begin
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end
          else
          begin
            inc(i);
            buffer := workarea;
            buffer := buffer - dummyLBox.Width - 8;
            dummyLBox.Position.Y := Panel2.Position.Y + 22 + (45 * i);
            dummyLBox.Position.X := workarea - buffer - dummyLBox.Width + 5;
          end;
          dummyLBox.Name := 'field' + IntToStr(f);
          inc(f);

          SetLength(aMasks, length(aMasks) + 1);
          Masks.field := dummyLBox.Name;
          Masks.mask := FDQDB.FieldByName('mask').AsString;
          aMasks[length(aMasks) - 1] := Masks;

          dummyLabel := TLabel.Create(self);
          with dummyLabel do
          begin
            Parent := dummyLBox.Parent;
            Text := FDQDB.FieldByName('Descricao').AsString;
            Position.Y := dummyLBox.Position.Y - 17;
            Position.X := dummyLBox.Position.X;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '+';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y;
            Name := 'ba' + dummyLBox.Name;
            OnClick := ButtonsAddClick;
          end;

          dummybutton := TButton.Create(self);
          with dummybutton do
          begin
            Parent := dummyLBox.Parent;
            Text := '-';
            Width := 20;
            Position.X := dummyLBox.Width + dummyLBox.Position.X + 3;
            Position.Y := dummyLBox.Position.Y + 28;
            Name := 'br' + dummyLBox.Name;
            OnClick := ButtonsRemClick;
          end;
        end;
    end;
    FDQDB.Next;
  end;
  FDQDB.Close;
end;

That works nice and pretty on the windowed state of the application, this code is applied to the onCreate event of the form:

procedure TForm2.FormCreate(Sender: TObject);
begin
  FDCDB.Params.Database := ExtractFilePath(ParamStr(0)) + 'window.db';
  MakeWindow;
end;

The first form, main form of the application, is the one that summons the new form that has the components built in runtime:

procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
end;

The second form has a TLayout, just like the first form. Then, when I create the form I bring the TLayout of the second form to the first. So far so good, it works when the application is launched in windowed mode.
But when I put form1 in fullscreen mode, then click the Button that creates the form2, the components stays on the same position as in windowed mode. I've tried changing the workarea variable to these:

Screen.width, //components behave as the application were in fullscreen the whole time
Screen.WorkAreaWidth, //same as screen.width
(Layout1.Parent as TLayout).Width, //invalid typecast
(Layout1.GetParentComponent as TLayout).Width //invalid typecast

None of them worked.
I wanna be able to adjust the position of the components on the screen based on its visual width, so if the user resizes the window before creating the new form, the components gets aligned properly.
Anyone knows a solution for that? Thanks in advance

Body:
But when I put form1 in fullscreen mode, then click the Button that
  creates the form2, the components stays on the same position as in
  windowed mode.

At TForm1.SpeedButton1Click() you call Application.CreateForm(TForm2, Form2); which triggers TForm2.FormCreate(Sender: TObject); which calls MakeWindow. At this point Form2 knows only about the design time size.

After MakeWindow is done, the TForm1.SpeedButton1Click() continues:

Form2.Layout1.parent := Self.Layout1.Parent;
Form2.Layout1.Width := Self.Layout1.Width;

but these do not anymore affect the layout of the controls.

You need to set Form2.Layout1.Width before you call MakeWindow, for example:

procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  Application.CreateForm(TForm2, Form2);
  Form2.Layout1.parent := Self.Layout1.Parent;
  Form2.Layout1.Width := Self.Layout1.Width;
  MakeWindow; // remove it from TForm2.FormCreate()
end;


来源: stackexchange

问:
Add a list of variables in a powershell script
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

```<code>$servers= @(
    Server1
    Server2
    Server3
    )
</code>```

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

答:
Filter out the empty lines:

```<code>Get-Content -Path .\servers.txt | Where-Object -FilterScript {$_ -ne ''}
</code>```

Edit: Sure, you can include your server names within your script if you choose to do that. If you have an array, as you've created in your example, then simply iterate over them within a looping construct, doing something to each server, on each loop.

```<code>$Servers = @('Server1','Server2','Server3')

Foreach ($Server in $Servers) {
    "Do something to $Server."
} # End Foreach.

Do something to Server1.
Do something to Server2.
Do something to Server3.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

$servers= @(
    Server1
    Server2
    Server3
    )

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

Body:
Filter out the empty lines:

Get-Content -Path .\servers.txt | Where-Object -FilterScript {$_ -ne ''}

Edit: Sure, you can include your server names within your script if you choose to do that. If you have an array, as you've created in your example, then simply iterate over them within a looping construct, doing something to each server, on each loop.

$Servers = @('Server1','Server2','Server3')

Foreach ($Server in $Servers) {
    "Do something to $Server."
} # End Foreach.

Do something to Server1.
Do something to Server2.
Do something to Server3.


问:
Icon widget cut off by Image widget
I'm trying to implement a "Change my profile picture" icon like how it appears in the profile page in Whatsapp, where a clickable camera icon hovers on the bottom right of the image.

This is the code I used inside a stateful widget:

```<code>Row(
                children: <Widget>[
                  Stack(
                    children: <Widget>[
                      Container(
                        width: 120,
                        child: Image(
                          image: AssetImage('affogato.png'),
                        ),
                      ),
                      Positioned(
                        top: 70,
                        left: 90,
                        child: FloatingActionButton(
                          child: Icon(Icons.camera_alt),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  ),
                ],
              ),
</code>```

Strangely, the Icon seems to take the constraints of the Image container. So when I set the width as 120 and try to push the Icon button to the bottom right edge of the Image, it gets cut off by the Image constraints. How do the constraints of the Container affect the FloatingActionButton even though they're siblings inside the Stack not parent-child widgets? And how can I fix this so that the Icon can float over the edge of the image?

答:
Here's how I did it. I removed the Positioned widget completely and used Padding instead. It seemed to solve the problem. I also wrapped the image in a CircleAvatar to complete the Whatsapp style.

```<code>Row(
    children: <Widget>[
      Stack(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: CircleAvatar(
              radius: 70,
              backgroundColor: Colors.greenAccent,
              child: Container(
                height: 150,
                width: 150,
                child: ClipOval(
                  child: Image(
                    image: AssetImage('lib/rainy.png'),
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 105, top: 80),
            child: Container(
              width: 50,
              height: 50,
              child: FloatingActionButton(
                backgroundColor: Colors.green,
                child: Icon(Icons.camera_alt),
                onPressed: () async {},
              ),
            ),
          ),
        ],
      ),
    ],
  ),
</code>```

Title: Icon widget cut off by Image widget

Body:
I'm trying to implement a "Change my profile picture" icon like how it appears in the profile page in Whatsapp, where a clickable camera icon hovers on the bottom right of the image.

This is the code I used inside a stateful widget:

Row(
                children: <Widget>[
                  Stack(
                    children: <Widget>[
                      Container(
                        width: 120,
                        child: Image(
                          image: AssetImage('affogato.png'),
                        ),
                      ),
                      Positioned(
                        top: 70,
                        left: 90,
                        child: FloatingActionButton(
                          child: Icon(Icons.camera_alt),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  ),
                ],
              ),

Strangely, the Icon seems to take the constraints of the Image container. So when I set the width as 120 and try to push the Icon button to the bottom right edge of the Image, it gets cut off by the Image constraints. How do the constraints of the Container affect the FloatingActionButton even though they're siblings inside the Stack not parent-child widgets? And how can I fix this so that the Icon can float over the edge of the image?

Body:
Here's how I did it. I removed the Positioned widget completely and used Padding instead. It seemed to solve the problem. I also wrapped the image in a CircleAvatar to complete the Whatsapp style.

Row(
    children: <Widget>[
      Stack(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: CircleAvatar(
              radius: 70,
              backgroundColor: Colors.greenAccent,
              child: Container(
                height: 150,
                width: 150,
                child: ClipOval(
                  child: Image(
                    image: AssetImage('lib/rainy.png'),
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 105, top: 80),
            child: Container(
              width: 50,
              height: 50,
              child: FloatingActionButton(
                backgroundColor: Colors.green,
                child: Icon(Icons.camera_alt),
                onPressed: () async {},
              ),
            ),
          ),
        ],
      ),
    ],
  ),


问:
How to fix "error: control reaches end of non-void function"?
```<code>int climbStairs(int n ){

    if(n==1){
        return 1;
    }
    if (n>=2){
         return (2+ climbStairs(n-2)+ climbStairs(n-1));
    }
}
</code>```

How do I fix the compiler error?

答:
And in addition to other answers here is another good trick.

If you are absolutely certain that you know more than the compiler, and there's nothing to return, then put an abort(); as the last line of your function. The compiler is smart enough to know that abort() will never return because it causes a program crash. That will silence the warning.

Note that the program crash is a good thing. Because as in this case, when the "impossible thing" does indeed happen, you get the crash and it will pop open in your debugger if you are using one.

Body:
int climbStairs(int n ){

    if(n==1){
        return 1;
    }
    if (n>=2){
         return (2+ climbStairs(n-2)+ climbStairs(n-1));
    }
}

How do I fix the compiler error?


问:
Python function that takes lists and elements and makes one list
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

```<code>def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]
</code>```

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

答:
Try this

```<code>a = []
b = []

def myFun(*argv):

    for arg in argv:
        a.append(arg)
    myList = str(a).replace('[','').replace(']','')
    b = [myList]
    print(b)

myFun('Hello', 'Welcome', 'to', 'Geeks',['ff','tt'])
</code>```

OUTPUT >> ["'Hello', 'Welcome', 'to', 'Geeks', 'ff', 'tt'"]

hope it will help

Body:
Hopefully an example could illustrate this better. I am creating a function that will take either a list of names, various lists of names, just a name or multiple names (not in a list) and make one list of them all (without importing... non-native libraries? I am ignorant here but I mean I want to use only what's already available in python).

def make_one_list(entry1, entry2, entry3 ...):
   #regardless of what is entered (well.. it has to be list or element)
   #extract elements from list and combine with single elements and...
   return one_big_list_of_all_elements

>>>make_one_list(['John','Mark'],'Mike',['Kate','Ally'],'Shawn','Marina'...)
['John','Mark','Mike','Kate','Ally','Shawn','Marina',...]

My pseudo-code is not set in stone, obviously. I think, eventually, some input checking might be in order but not very pythonic in nature to do that. I am simply doing this as a personal communication function for my office.

THANKS!!

Body:
Try this

a = []
b = []

def myFun(*argv):

    for arg in argv:
        a.append(arg)
    myList = str(a).replace('[','').replace(']','')
    b = [myList]
    print(b)

myFun('Hello', 'Welcome', 'to', 'Geeks',['ff','tt'])

OUTPUT >> ["'Hello', 'Welcome', 'to', 'Geeks', 'ff', 'tt'"]

hope it will help


问:
The pipe 'can' could not be found
I am trying to implement CASL ability manager for my angular 8 app. I did everything that described in the package usage guide but there is an error about can pipe in my component html template.

```<code>The pipe 'can' could not be found
</code>```

So here is my app module:

```<code>@NgModule({
    declarations: [],
    imports: [
...
        AbilityModule.forRoot()
    ],
    exports: [],
    providers: [
...
        { provide: Ability, useFactory: createAbility }
    ],
    bootstrap: [AppComponent]
})
</code>```

I implemented like this casl example also.

createAbility function is shown  below:

```<code>import { AbilityBuilder, Ability } from '@casl/ability'
import { User, Claim } from '@/_models';
import { ABILITIES } from './const-variables';

var user = localStorage.getItem('currentUser');
var currentUser = JSON.parse(user) as User;

export function defineAbilitiesFor(user: User) {
  const { can, rules } = AbilityBuilder.extract();

  if (user.roles.includes("Admin")) {
    can("manage", "all");
  } else {
    user.claims.forEach(claim => {
      ABILITIES.map(ability => {
        if (ability.name === (claim as Claim).type) {
          can(ability.name, ability.module);
        }
      })
    });
  }
  return rules;
}

export function createAbility() {
  return new Ability(defineAbilitiesFor(currentUser), {
    subjectName(subject) {
      if (!subject || typeof subject === "string") {
        return subject;
      }
      return subject.__typename;
    }
  });
}
</code>```

I would tell also it works in my component class with this.ability.can() by injecting Ability class.But it can't work with can pipe

What should I do for getting rid of this error?

Thanks

答:
Have you created your ability? I see you've defined useFactory: createAbility but from the docs the example is:

```<code>import { AbilityBuilder } from '@casl/ability'

export const ability = AbilityBuilder.define(can => {
   can('read', 'all')
})
</code>```

What happens if you change that to useValue and build your definition based on the example?

Title: The pipe 'can' could not be found

Body:
I am trying to implement CASL ability manager for my angular 8 app. I did everything that described in the package usage guide but there is an error about can pipe in my component html template.

The pipe 'can' could not be found

So here is my app module:

@NgModule({
    declarations: [],
    imports: [
...
        AbilityModule.forRoot()
    ],
    exports: [],
    providers: [
...
        { provide: Ability, useFactory: createAbility }
    ],
    bootstrap: [AppComponent]
})

I implemented like this casl example also.

createAbility function is shown  below:

import { AbilityBuilder, Ability } from '@casl/ability'
import { User, Claim } from '@/_models';
import { ABILITIES } from './const-variables';

var user = localStorage.getItem('currentUser');
var currentUser = JSON.parse(user) as User;

export function defineAbilitiesFor(user: User) {
  const { can, rules } = AbilityBuilder.extract();

  if (user.roles.includes("Admin")) {
    can("manage", "all");
  } else {
    user.claims.forEach(claim => {
      ABILITIES.map(ability => {
        if (ability.name === (claim as Claim).type) {
          can(ability.name, ability.module);
        }
      })
    });
  }
  return rules;
}

export function createAbility() {
  return new Ability(defineAbilitiesFor(currentUser), {
    subjectName(subject) {
      if (!subject || typeof subject === "string") {
        return subject;
      }
      return subject.__typename;
    }
  });
}

I would tell also it works in my component class with this.ability.can() by injecting Ability class.But it can't work with can pipe

What should I do for getting rid of this error?

Thanks

Body:
Have you created your ability? I see you've defined useFactory: createAbility but from the docs the example is:

import { AbilityBuilder } from '@casl/ability'

export const ability = AbilityBuilder.define(can => {
   can('read', 'all')
})

What happens if you change that to useValue and build your definition based on the example?


问:
Inherit constants - best style?
This is more of an "is there a better way" question than a real problem.

When having a property that is only accessed in a base class:

```<code> private const bool isSomething = true;
</code>```

I sometimes have to change this value in a project where I inherit from this class. But as it is a constant and used class-wide, I normally change the code in the base class to something like this:

```<code> private const bool isSomething = true;
 protected virtual bool IsSomething{
       get{
           return isSomething;
       }
 }
</code>```

And override the property in the subclass and create a new isSomething constant.

This creates a new field and an override and, in my opinion, is not nice style. Is there a better way to do this?

The value is a constant, and it will be constant in the complete project where I'm using it.

答:
If you need to set the value based on which class you are in but don't want the value to change later, than const is not the right keyword. Instead, you can use readonly and require sub-classes to pass in a value to the constructor.

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants...
  Source

Edit:

To summarize: You have a filed that is only accessed by the base class and the base class should never alter that value. In most cases, the default value is fine. However, there are some cases that arise when a subclass need to set it's own value that is different than the default.

```<code>class Base {
  private readonly bool _isSomething;

  public Base() : this(false) {}

  protected Base(bool isSomething)
  {
    _isSomething = isSomething;
  }
}
class Child {
  public Child() : base(true) {}
}
</code>```

This provides the same functionality as your suggested work-around. The value can not be changed and only a child class can provide a different value. It has an added benefit of not allow the child class invalidate the fact that the value is intended to be constant. The override method allows for this:

```<code>protected override bool IsSomething{
   get{
     return BOOLEAN_EXPRESSION;
   }
}
</code>```

I understand your idea of making it a static value (since we know every instance will use the same value), but that only makes things complicated as static items are not inherited.

ContentLicense: CC BY-SA 3.0

Title: Inherit constants - best style?

Body:
This is more of an "is there a better way" question than a real problem.

When having a property that is only accessed in a base class:

 private const bool isSomething = true;

I sometimes have to change this value in a project where I inherit from this class. But as it is a constant and used class-wide, I normally change the code in the base class to something like this:

 private const bool isSomething = true;
 protected virtual bool IsSomething{
       get{
           return isSomething;
       }
 }

And override the property in the subclass and create a new isSomething constant.

This creates a new field and an override and, in my opinion, is not nice style. Is there a better way to do this?

The value is a constant, and it will be constant in the complete project where I'm using it.

Body:
If you need to set the value based on which class you are in but don't want the value to change later, than const is not the right keyword. Instead, you can use readonly and require sub-classes to pass in a value to the constructor.

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants...
  Source

Edit:

To summarize: You have a filed that is only accessed by the base class and the base class should never alter that value. In most cases, the default value is fine. However, there are some cases that arise when a subclass need to set it's own value that is different than the default.

class Base {
  private readonly bool _isSomething;

  public Base() : this(false) {}

  protected Base(bool isSomething)
  {
    _isSomething = isSomething;
  }
}
class Child {
  public Child() : base(true) {}
}

This provides the same functionality as your suggested work-around. The value can not be changed and only a child class can provide a different value. It has an added benefit of not allow the child class invalidate the fact that the value is intended to be constant. The override method allows for this:

protected override bool IsSomething{
   get{
     return BOOLEAN_EXPRESSION;
   }
}

I understand your idea of making it a static value (since we know every instance will use the same value), but that only makes things complicated as static items are not inherited.


问:
Check if variable exists - Terraform template syntax
I'm trying to check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header.

```<code>$ cat nginx.conf.tmpl

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if location.proxy_set_header }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
</code>```

I tried with if location.proxy_set_header != "" and if location.proxy_set_header without success.

How to check if a variable exists with the String Templates?

答:
If you are using Terraform 0.12.20 or later then you can use the new function can to concisely write a check like this:

```<code>%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if can(location.proxy_set_header) }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
</code>```

The can function returns true if the given expression could evaluate without an error.

The documentation does suggest preferring try in most cases, but in this particular situation your goal is to show nothing at all if that attribute isn't present, and so this equivalent approach with try is, I think, harder to understand for a future reader:

```<code>%{ for location in jsondecode(locations) }
location ${location.path} {
    ${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }
</code>```

As well as being (subjectively) more opaque as to the intent, this ignores the recommendation in the try docs of using it only with attribute lookup and type conversion expressions. Therefore I think the can usage above is justified due to its relative clarity, but either way should work.

Body:
I'm trying to check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header.

$ cat nginx.conf.tmpl

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if location.proxy_set_header }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }

I tried with if location.proxy_set_header != "" and if location.proxy_set_header without success.

How to check if a variable exists with the String Templates?

Body:
If you are using Terraform 0.12.20 or later then you can use the new function can to concisely write a check like this:

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if can(location.proxy_set_header) }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }

The can function returns true if the given expression could evaluate without an error.

The documentation does suggest preferring try in most cases, but in this particular situation your goal is to show nothing at all if that attribute isn't present, and so this equivalent approach with try is, I think, harder to understand for a future reader:

%{ for location in jsondecode(locations) }
location ${location.path} {
    ${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }

As well as being (subjectively) more opaque as to the intent, this ignores the recommendation in the try docs of using it only with attribute lookup and type conversion expressions. Therefore I think the can usage above is justified due to its relative clarity, but either way should work.


问:
Ansible output extract package version using jq
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

```<code>"GeoIP","1.5.0"
</code>```

sample ansible output

```<code>{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}
</code>```

答:
First, make the source valid json by removing the comma in the third to last row.

With that done, we can start at the end and work back. The desired output can be produced using jq's @csv format. That, in turn, requires that the output is in an array. (See the section of the manual titled "Format strings and escaping".) So we need to get the data to look like this.

```<code>jq -r '["GeoIP","1.5.0"] | @csv'
</code>```

One way to do that is to put each item in its own array and add the arrays together. (See the section titled "Addition".)

```<code>jq -r '["GeoIP"] + [.[] | .GeoIP[].version] | @csv'
</code>```

Since map(x) is defined as [.[] | x], you can say this instead.

```<code>jq -r '["GeoIP"] + map(.GeoIP[].version) | @csv'
</code>```

You can use a variable to specify the package name you want like this.

```<code>jq -r --arg "package" "GeoIP" '[$package] + map(.[$package][].version) | @csv'
</code>```

Update

My original solution has unnecessary steps. The array can be made like this.

```<code>jq -r '[ "GeoIP", .[].GeoIP[].version ] | @csv'
</code>```

Or, using a variable

```<code>jq -r --arg "package" "GeoIP" '[$package,(.[] | .[$package][].version)]| @csv'
</code>```

Body:
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

"GeoIP","1.5.0"

sample ansible output

{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}

Body:
First, make the source valid json by removing the comma in the third to last row.

With that done, we can start at the end and work back. The desired output can be produced using jq's @csv format. That, in turn, requires that the output is in an array. (See the section of the manual titled "Format strings and escaping".) So we need to get the data to look like this.

jq -r '["GeoIP","1.5.0"] | @csv'

One way to do that is to put each item in its own array and add the arrays together. (See the section titled "Addition".)

jq -r '["GeoIP"] + [.[] | .GeoIP[].version] | @csv'

Since map(x) is defined as [.[] | x], you can say this instead.

jq -r '["GeoIP"] + map(.GeoIP[].version) | @csv'

You can use a variable to specify the package name you want like this.

jq -r --arg "package" "GeoIP" '[$package] + map(.[$package][].version) | @csv'

Update

My original solution has unnecessary steps. The array can be made like this.

jq -r '[ "GeoIP", .[].GeoIP[].version ] | @csv'

Or, using a variable

jq -r --arg "package" "GeoIP" '[$package,(.[] | .[$package][].version)]| @csv'


问:
SQL Server - Reasons for OPTION (FAST N) to choose other execution plan
What is the reason behind this behavior for a table with ~300,000,000 rows

Following query execution takes 1 sec to complete:

```<code>SELECT * FROM "DB_NAME"."dbo"."TABLE"
WHERE (("G_L Account No_"= 11200)) AND
(("Posting Date">= '2001-02-01 00:00:00.000' AND
"Posting Date"<='2020-02-27 00:00:00.000')) AND
(("Gen_ Prod_ Posting Group"= '3475')) AND
(("Global Dimension 1 Code"= '8204' )) and
"Entry No_"< 298815528
ORDER BY "Entry No_" DESC OPTION (FAST 1270)
</code>```

And the same query with only change in last option of FAST to 1269 takes 5 min to complete.

```<code>SELECT * FROM "DB_NAME"."dbo"."TABLE"
WHERE (("G_L Account No_"= 11200)) AND
(("Posting Date">= '2001-02-01 00:00:00.000' AND
"Posting Date"<='2020-02-27 00:00:00.000')) AND
(("Gen_ Prod_ Posting Group"= '3475')) AND
(("Global Dimension 1 Code"= '8204' )) and
"Entry No_"< 298815528
ORDER BY "Entry No_" DESC OPTION (FAST 1269)
</code>```

I found there is a different plan chosen for both but I can't understand why the plan changes due to number of rows to return with FAST. Original query from application has OPTION (FAST 100) but by testing I found the breakpoint is at 1270 when the query changes the execution plan.

答:
OPTION (FAST N) sets a "row goal".

Smaller values of N encourage choices like nested loops that potentially can start streaming rows quicker and discourage blocking choices like sort merge joins or hash joins.

In your case I imagine the query optimiser has to choose between two different plans.

Seeking into a non covering index on Entry No_ = 298,815,528 then scanning it in descending order and doing lookups to get the remaining columns and evaluate the other predicates in the WHERE clause.

Scan the table (clustered index or heap), evaluate the predicates and then sort all matching rows.

As option 1 does not require an initial step of identifying and sorting all rows that match the WHERE clause before delivering even the first row this has the potential to be faster to deliver a small number of rows. However this will lead to catastrophically bad overall performance as execution plan 1 will have to do in the order of 300 million look-ups before it stops executing and delivers the complete result (5 mins to execute this amount of lookups would be pretty quick so maybe the index does cover some other column(s) in the predicate to allow some rows to be eliminated without a lookup).

This type of scenario is easy to reproduce as in the following example.

```<code>CREATE TABLE #temp(Id INT IDENTITY UNIQUE, OtherCol TINYINT)

INSERT INTO #temp(OtherCol)
SELECT TOP 10000000 CRYPT_GEN_RANDOM(1) + 0 AS OtherCol
FROM sys.all_objects o1, sys.all_objects o2, sys.all_objects o3;

SELECT *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC
OPTION (FAST 33);

SELECT *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC
OPTION (FAST 32);

SELECT TOP 32 *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC;

SELECT *
FROM #temp with (index = 2)
where OtherCol = 2
ORDER BY Id DESC;
</code>```

Execution Plans FAST 32 vs FAST 33

The estimated plan costs for the four queries are below

```<code>+----------------------------+---------------------+
|           Query            | Estimated plan cost |
+----------------------------+---------------------+
| FAST 33                    |             22.1202 |
| FAST 32                    |              21.754 |
| TOP 32                     |             21.7579 |
| Scan + Lookups whole table |             1682.01 |
+----------------------------+---------------------+
</code>```

Observations

The TOP 32 and FAST 32 plans are costed basically the same - the TOP can stop executing once the 32nd matching row is found. The FAST plan must carry on executing and return the entire result but this extra cost is ignored

Query 4 shows the estimated cost of performing this plan whilst taking into account the complete number of lookups that the  FAST 32 plan will perform. So the FAST 32 plan is costed at only 1.29% of its "true" cost.

Query 1 and 2 have very close estimated costs, this is the tipping point between the two plans where the estimated costs of performing the required lookups to deliver the first 33 rows would exceed that of just reading the whole table and sorting the matching results.

In this case the tipping point is quite low as the where OtherCol = 2 predicate is fairly selective (1/256). This means the expected number of lookups needed before finding 32 matching rows is around 32 * 256 = 8,192 (SQL Server assumes that rows matching the condition will be distributed evenly throughout the table) and conversely the amount of data to sort is estimated as relatively low at 10000000/256 rows. If the predicate is made less selective the tipping point will be higher.

Body:
What is the reason behind this behavior for a table with ~300,000,000 rows

Following query execution takes 1 sec to complete:

SELECT * FROM "DB_NAME"."dbo"."TABLE"
WHERE (("G_L Account No_"= 11200)) AND
(("Posting Date">= '2001-02-01 00:00:00.000' AND
"Posting Date"<='2020-02-27 00:00:00.000')) AND
(("Gen_ Prod_ Posting Group"= '3475')) AND
(("Global Dimension 1 Code"= '8204' )) and
"Entry No_"< 298815528
ORDER BY "Entry No_" DESC OPTION (FAST 1270)

And the same query with only change in last option of FAST to 1269 takes 5 min to complete.

SELECT * FROM "DB_NAME"."dbo"."TABLE"
WHERE (("G_L Account No_"= 11200)) AND
(("Posting Date">= '2001-02-01 00:00:00.000' AND
"Posting Date"<='2020-02-27 00:00:00.000')) AND
(("Gen_ Prod_ Posting Group"= '3475')) AND
(("Global Dimension 1 Code"= '8204' )) and
"Entry No_"< 298815528
ORDER BY "Entry No_" DESC OPTION (FAST 1269)

I found there is a different plan chosen for both but I can't understand why the plan changes due to number of rows to return with FAST. Original query from application has OPTION (FAST 100) but by testing I found the breakpoint is at 1270 when the query changes the execution plan.

Body:
OPTION (FAST N) sets a "row goal".

Smaller values of N encourage choices like nested loops that potentially can start streaming rows quicker and discourage blocking choices like sort merge joins or hash joins.

In your case I imagine the query optimiser has to choose between two different plans.

Seeking into a non covering index on Entry No_ = 298,815,528 then scanning it in descending order and doing lookups to get the remaining columns and evaluate the other predicates in the WHERE clause.

Scan the table (clustered index or heap), evaluate the predicates and then sort all matching rows.

As option 1 does not require an initial step of identifying and sorting all rows that match the WHERE clause before delivering even the first row this has the potential to be faster to deliver a small number of rows. However this will lead to catastrophically bad overall performance as execution plan 1 will have to do in the order of 300 million look-ups before it stops executing and delivers the complete result (5 mins to execute this amount of lookups would be pretty quick so maybe the index does cover some other column(s) in the predicate to allow some rows to be eliminated without a lookup).

This type of scenario is easy to reproduce as in the following example.

CREATE TABLE #temp(Id INT IDENTITY UNIQUE, OtherCol TINYINT)

INSERT INTO #temp(OtherCol)
SELECT TOP 10000000 CRYPT_GEN_RANDOM(1) + 0 AS OtherCol
FROM sys.all_objects o1, sys.all_objects o2, sys.all_objects o3;

SELECT *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC
OPTION (FAST 33);

SELECT *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC
OPTION (FAST 32);

SELECT TOP 32 *
FROM #temp
where OtherCol = 2
ORDER BY Id DESC;

SELECT *
FROM #temp with (index = 2)
where OtherCol = 2
ORDER BY Id DESC;

Execution Plans FAST 32 vs FAST 33

The estimated plan costs for the four queries are below

+----------------------------+---------------------+
|           Query            | Estimated plan cost |
+----------------------------+---------------------+
| FAST 33                    |             22.1202 |
| FAST 32                    |              21.754 |
| TOP 32                     |             21.7579 |
| Scan + Lookups whole table |             1682.01 |
+----------------------------+---------------------+

Observations

The TOP 32 and FAST 32 plans are costed basically the same - the TOP can stop executing once the 32nd matching row is found. The FAST plan must carry on executing and return the entire result but this extra cost is ignored

Query 4 shows the estimated cost of performing this plan whilst taking into account the complete number of lookups that the  FAST 32 plan will perform. So the FAST 32 plan is costed at only 1.29% of its "true" cost.

Query 1 and 2 have very close estimated costs, this is the tipping point between the two plans where the estimated costs of performing the required lookups to deliver the first 33 rows would exceed that of just reading the whole table and sorting the matching results.

In this case the tipping point is quite low as the where OtherCol = 2 predicate is fairly selective (1/256). This means the expected number of lookups needed before finding 32 matching rows is around 32 * 256 = 8,192 (SQL Server assumes that rows matching the condition will be distributed evenly throughout the table) and conversely the amount of data to sort is estimated as relatively low at 10000000/256 rows. If the predicate is made less selective the tipping point will be higher.


问:
Call model from another plugin in Strapi
I have a Notification model which belongsToMany users from users-permissions plugin.

I have another model called Profile which belongsToOne user.

Now, I want to populate the notification with related user and their profile ...

I have tried:

```<code> await strapi.query("user", "users-permissions").find({_id: `model id`}).populate('profile')
</code>```

Throwing Impossible to find the plugin where strapi.query has been called. at me.

Also tried:

```<code>notification.user.populate('profile')
</code>```

No luck either

I also tried strapi.plugins["users-permissions"].models.user got undefined!

答:
I am having the same problem here.
All of these are undefined:

```<code>strapi.query
strapi.plugins
</code>```

The global strapi object exists, just doesn't provide the properties listed above...
Am I missing something? I have read the docs at least three times... no luck.

Body:
I have a Notification model which belongsToMany users from users-permissions plugin.

I have another model called Profile which belongsToOne user.

Now, I want to populate the notification with related user and their profile ...

I have tried:

 await strapi.query("user", "users-permissions").find({_id: `model id`}).populate('profile')

Throwing Impossible to find the plugin where strapi.query has been called. at me.

Also tried:

notification.user.populate('profile')

No luck either

I also tried strapi.plugins["users-permissions"].models.user got undefined!

Body:
I am having the same problem here.
All of these are undefined:

strapi.query
strapi.plugins

The global strapi object exists, just doesn't provide the properties listed above...
Am I missing something? I have read the docs at least three times... no luck.


问:
How indent this Objective-C code?
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

```<code>    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];
</code>```

One solution was

```<code>    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];
</code>```

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

```<code>NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:
</code>```

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

答:
I'd do something like:</p>

```<code>NSString *count = [[NSString alloc] initWithString:
    [sTemp substringFromIndex:
         [sTemp rangeOfString:@"count="].location
       + [sTemp rangeOfString:@"count="].length]];
</code>```

Title: How indent this Objective-C code?

Body:
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];

One solution was

    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

Body:
I'd do something like:

NSString *count = [[NSString alloc] initWithString:
    [sTemp substringFromIndex:
         [sTemp rangeOfString:@"count="].location
       + [sTemp rangeOfString:@"count="].length]];


问:
Multiple dropzones on same page cause bugs to appear
I have multiple dropzones (dynamic, each product represents a product that is added in a basket in my webshop).

Every image upload an ajax call is made that returns info of the uploaded image and displays it in the previewtemplate (thumbnail block of the uploaded image). Info like the dimensions, DPI and filename.

The problem is that info is always displayed only in the last dropzone, in the last previewtemplate.

For example:

```<code>When I have two dropzones.
I upload an image of 20DPI in the first one, result: no information is shown in the preview.

I upload an image of 20DPI in the second one, result: the preview is shown with 20 DPI as information which is correct.

I upload two images at the same time in the second dropzone, the first image with 20DPI the second one with 72DPI, result: the first preview is empty and the last preview briefly shows 20DPI before it is overwritten with 72DPI.
</code>```

This means the information is received correctly, it's just not placed correctly in the previewtemplates.

This is my dropzone code, it loops through all .dropzone classes:

```<code>$('.dropzone').each(function(index){
    $maxfiles = $(this).attr('maxfiles');
    $inputquantity = $(this).find('input').val();
    $thisdropzone = $(this);
    $(this).dropzone({
        paramName: 'postedFile',
        addRemoveLinks: true,
        dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
        dictRemoveFile: 'Verwijder',
        dictCancelUpload: 'Annuleren',
        dictInvalidFileType: 'Dit type bestand is niet toegestaan',
        dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
        dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
        maxFiles: $maxfiles,
        acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
        thumbnailWidth: '205',
        thumbnailHeight: '140',
        thumbnailMethod: 'crop',
        previewTemplate: $(".hiddendiv").html(),
        sending: function (file) {

        },
        // File contains dropzone file object, response contains ajax response from php file
        success: function (file, response) {
            var obj = JSON.parse(response);
            $($thisdropzone).find('.dz-preview:last .bestandnaam').text('Bestandsnaam: ' + obj[0].filename);
            $($thisdropzone).find('.dz-preview:last .resolutie').text('Resolutie: ' + obj[0].dpi + ' DPI');
            $($thisdropzone).find('.dz-preview:last .formaat').text('Formaat: ' + obj[0].heightcm + ' x ' + obj[0].widthcm + 'cm');
        },
    })
});
</code>```

And this is my html with in this example two dropzones (the forms):

```<code><table class="table upload-table">
   <tbody>
      <tr>
         <td class="plantmore-product-thumbnail uploadimg" width="100">
            <a href=""><img src="assets/images/noimg.jpg" alt=""></a>
         </td>
         <td class="plantmore-product-name" width="200">
            <div class="prodinfocheckout">
               <a class="prodname" href="">
               Monomeer
               </a>
               <span id="togglespecscheckout" class="prodspecscheckout noselect">
               <i class="fas fa-chevron-down"></i> Specificaties
               </span>
               <div class="togglespecscheckout">
                  Hoogte : 20cm
                  <br>
                  Breedte : 20cm
                  <br>
                  uploaden : 1
                  <br>
                  Lijmlaag : Wit
                  <br>
                  Laminaat : Anti-slip laminaat
                  <br>
                  Afwerking : Contoursnijden
                  <br>
               </div>
            </div>
         </td>
         <td class="plantmore-product-quantity" width="190">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">
            Benodigd formaat:<br>
            <span class="benodigd">20 x 20cm</span>
            </span>
            </span>
         </td>
         <td class="plantmore-product-quantity" width="185">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">10</span></span>
            </span>
         </td>
         <td class="plantmore-product-quantity">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 10</span></span>
            </span>
         </td>
         <td class="plantmore-product-quantity" valign="top">
            <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
         </td>
      </tr>
      <tr class="newrow">
         <td colspan="6">
            <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="10" id="dropzone1">
               <input type="hidden" value="Monomeer" name="productnaam">
               <input type="hidden" value="Twan" name="klantnaam">
               <input type="hidden" value="20" name="hoogte">
               <input type="hidden" value="20" name="breedte">
               <div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
            </form>
         </td>
      </tr>
      <tr>
         <td class="plantmore-product-thumbnail uploadimg" width="100">
            <a href=""><img src="assets/images/noimg.jpg" alt=""></a>
         </td>
         <td class="plantmore-product-name" width="200">
            <div class="prodinfocheckout">
               <a class="prodname" href="">
               Monomeer
               </a>
               <span id="togglespecscheckout" class="prodspecscheckout noselect">
               <i class="fas fa-chevron-down"></i> Specificaties
               </span>
               <div class="togglespecscheckout">
                  Hoogte : 90cm
                  <br>
                  Breedte : 90cm
                  <br>
                  uploaden : 1
                  <br>
                  Lijmlaag : Wit
                  <br>
                  Laminaat : Anti-slip laminaat
                  <br>
                  Afwerking : Contoursnijden
                  <br>
               </div>
            </div>
         </td>
         <td class="plantmore-product-quantity" width="190">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">
            Benodigd formaat:<br>
            <span class="benodigd">90 x 90cm</span>
            </span>
            </span>
         </td>
         <td class="plantmore-product-quantity" width="185">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">1</span></span>
            </span>
         </td>
         <td class="plantmore-product-quantity">
            <span class="centervertical">
            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
            </button>
            <span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 1</span></span>
            </span>
         </td>
         <td class="plantmore-product-quantity" valign="top">
            <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
         </td>
      </tr>
      <tr class="newrow">
         <td colspan="6">
            <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="1" id="dropzone4">
               <input type="hidden" value="Monomeer" name="productnaam">
               <input type="hidden" value="Twan" name="klantnaam">
               <input type="hidden" value="90" name="hoogte">
               <input type="hidden" value="90" name="breedte">
               <div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
            </form>
         </td>
      </tr>
   </tbody>
</table>
</code>```

What can be causing the bugs? I tried removing the :last parts and only upload one image in the first one and one in the second. But the first preview still doesn't have any information in it.

This is my custom previewelement inside .hiddendiv it's beneath the dropzones in my DOM:

```<code>  <div class="hiddendiv">

    <div class="dz-preview dz-file-preview">
      <div class="dz-image"><img data-dz-thumbnail /></div>
      <div class="dz-details">
          <div class="dz-size"><span data-dz-size></span></div>
          <div class="dz-filename"><span data-dz-name></span></div>
      </div>
      <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
      <div class="dz-error-message"><span data-dz-errormessage></span></div>
            <span class="infoline">
                <span class="infospan bestandnaam">Bestandnaam:</span>
                <!-- <i class="fas fa-times-circle afgekeurd"></i> -->
            </span>
      <span class="infoline">
                <span class="infospan resolutie">Resolutie:</span>
                <!-- <i class="fas fa-check-circle goedgekeurd"></i> -->
            </span>
      <span class="infoline">
                <span class="infospan formaat">Formaat:</span>
                <!-- <i class="fas fa-times-circle afgekeurd"></i> -->
            </span>
            <div class="foutformaat">
                <span>Bestand heeft niet het benodigde formaat.</span>
                <span class="uploadinfobox">
                    <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
                        <i class="fas fa-info-circle"></i>
                    </button>
                </span>
            </div>
      <button class="yellowbtn btn vrijgevenbtn" type="button">Bestand vrijgeven</button>
            <hr class="uploadline">
            <span class="toewijzen">Aantal</span>
      <div class="uploadcontent">
        <input type="text" class="fileinput">
        <button class="plusminupload" id="minupload">−</button>
        <button class="plusminupload" id="plusupload">+</button>
      </div>
    </div>
  </div>
</code>```

Updated code from answer below:

```<code>$('.dropzone').each(function(index, element){
    let $el = $(element);
    let $maxfiles = $el.attr('maxfiles');
    let $inputquantity = $el.find('input').val();
    let $thispreview = $el.find('.hiddendiv');
    let $thisdropzone = $el;
    // $maxfiles = $(this).attr('maxfiles');
    // $inputquantity = $(this).find('input').val();
    // $thisdropzone = $(this);
    // $thispreview = $(this).find('.hiddendiv');

    $(this).dropzone({
        // clickable: ".uploadbutton, .dropzoneform",
        paramName: 'postedFile',
        addRemoveLinks: true,
        dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
        dictRemoveFile: 'Verwijder',
        dictCancelUpload: 'Annuleren',
        dictInvalidFileType: 'Dit type bestand is niet toegestaan',
        dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
        dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
        maxFiles: $maxfiles,
        acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
        thumbnailWidth: '205',
        thumbnailHeight: '140',
        thumbnailMethod: 'crop',
        previewTemplate: $thispreview.html(),
        processing: function (file) {

        },
        // File contains dropzone file object, response contains ajax response from php file
        success: function (file, response) {
            // alert('test');
            let file_meta = JSON.parse(response);
            let $preview = $thisdropzone.find('.dz-preview:last');
            if(file_meta[0].status == 'success'){

            }else if(file_meta[0].status == 'error'){
                $preview.find('.vrijgevenbtn').show();
                $preview.find('.foutformaat').show();
            }
            $preview.find('.bestandnaam').text('Bestandsnaam: ' + file_meta[0].filename);
            $preview.find('.resolutie').text('Resolutie: ' + file_meta[0].dpi + ' DPI');
            $preview.find('.formaat').text('Formaat: ' + file_meta[0].heightcm + ' x ' + file_meta[0].widthcm + 'cm');
        },
    })
});
</code>```

This is what happens when I upload multiple images in one selection:
Selecting three images from my computer:

Three previews in the dropzone with only the last one having data:

Every image returns a json string which in this example are:

```<code>[{"status":"error","filename":"instablok.jpg","filesize":22822,"tmp_name":"\/tmp\/phpI6ov6y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]

[{"status":"error","filename":"fbblok.jpg","filesize":17349,"tmp_name":"\/tmp\/phpBzh40y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]

[{"status":"error","filename":"logo-dark.png","filesize":21137,"tmp_name":"\/tmp\/phpCHGGZg","height":154,"width":881,"heightcm":"5,43","widthcm":"31,08","tifwidth":null,"dpi":"72"}]
</code>```

All of them are returned seperately. The strange thing is, all data is added to the last preview and overwritten by a newer one. So the last preview first contains data from the first returned json, then the second and finally the last correct one, while the first two remain empty.

You can test with these two links:

First add a product to your basket here: https://printzelf.nl/new/folie/monomeer
You Aantal means quantity and this will determine how many images can be uploaded in a dropzone so you need more than 1 to be able to see the bug.

When you are done clicking through the options you can add it Toevoegen. Then go to the dropzone page link which is: https://printzelf.nl/new/bestanden-uploaden

答:
```<code>let counterId = 0;
$('.dropzone').each(function(index){
        counterId++;
        $maxfiles = $(this).attr('maxfiles');
        $inputquantity = $(this).find('input').val();
        $thisdropzone = $(this);
        $(this).dropzone({
            autoProcessQueue:true,
            parallelUploads:1,
            paramName: 'postedFile',
            addRemoveLinks: true,
            dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
            dictRemoveFile: 'Verwijder',
            dictCancelUpload: 'Annuleren',
            dictInvalidFileType: 'Dit type bestand is niet toegestaan',
            dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
            dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
            maxFiles: $maxfiles,
            acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
            thumbnailWidth: '205',
            thumbnailHeight: '140',
            thumbnailMethod: 'crop',
            previewTemplate: $("#hiddendiv"+counterId).html(),
            sending: function (file) {

            },
            // File contains dropzone file object, response contains ajax response from php file
            success: function (file, response) {
                var obj = JSON.parse(response);
                $($thisdropzone).find('.dz-preview:last .bestandnaam').text('Bestandsnaam: ' + obj[0].filename);
                $($thisdropzone).find('.dz-preview:last .resolutie').text('Resolutie: ' + obj[0].dpi + ' DPI');
                $($thisdropzone).find('.dz-preview:last .formaat').text('Formaat: ' + obj[0].heightcm + ' x ' + obj[0].widthcm + 'cm');
            },
        })
    });
</code>```

<p>And rename your hiddenDiv to hiddenDiv1 and hiddenDiv2, If needed you could also add the hiddenDivs dynamically and use the counterId for the name. </p>

Body:
I have multiple dropzones (dynamic, each product represents a product that is added in a basket in my webshop).

Every image upload an ajax call is made that returns info of the uploaded image and displays it in the previewtemplate (thumbnail block of the uploaded image). Info like the dimensions, DPI and filename.

The problem is that info is always displayed only in the last dropzone, in the last previewtemplate.

For example:

When I have two dropzones.
I upload an image of 20DPI in the first one, result: no information is shown in the preview.

I upload an image of 20DPI in the second one, result: the preview is shown with 20 DPI as information which is correct.

I upload two images at the same time in the second dropzone, the first image with 20DPI the second one with 72DPI, result: the first preview is empty and the last preview briefly shows 20DPI before it is overwritten with 72DPI.

This means the information is received correctly, it's just not placed correctly in the previewtemplates.

This is my dropzone code, it loops through all .dropzone classes:

$('.dropzone').each(function(index){
    $maxfiles = $(this).attr('maxfiles');
    $inputquantity = $(this).find('input').val();
    $thisdropzone = $(this);
    $(this).dropzone({
        paramName: 'postedFile',
        addRemoveLinks: true,
        dictDefaultMessage: ' Upload je bestand(en)',
        dictRemoveFile: 'Verwijder',
        dictCancelUpload: 'Annuleren',
        dictInvalidFileType: 'Dit type bestand is niet toegestaan',
        dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
        dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
        maxFiles: $maxfiles,
        acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
        thumbnailWidth: '205',
        thumbnailHeight: '140',
        thumbnailMethod: 'crop',
        previewTemplate: $(".hiddendiv").html(),
        sending: function (file) {

        },
        // File contains dropzone file object, response contains ajax response from php file
        success: function (file, response) {
            var obj = JSON.parse(response);
            $($thisdropzone).find('.dz-preview:last .bestandnaam').text('Bestandsnaam: ' + obj[0].filename);
            $($thisdropzone).find('.dz-preview:last .resolutie').text('Resolutie: ' + obj[0].dpi + ' DPI');
            $($thisdropzone).find('.dz-preview:last .formaat').text('Formaat: ' + obj[0].heightcm + ' x ' + obj[0].widthcm + 'cm');
        },
    })
});

And this is my html with in this example two dropzones (the forms):

               Monomeer

                Specificaties

                  Hoogte : 20cm

                  Breedte : 20cm

                  uploaden : 1

                  Lijmlaag : Wit

                  Laminaat : Anti-slip laminaat

                  Afwerking : Contoursnijden

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>

            Benodigd formaat:

            20 x 20cm

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>
            Benodigde aantal
 bestanden: 10

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>
            Bestanden
toegewezen: 0 / 10

            <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>

            <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="10" id="dropzone1">
               <input type="hidden" value="Monomeer" name="productnaam">
               <input type="hidden" value="Twan" name="klantnaam">
               <input type="hidden" value="20" name="hoogte">
               <input type="hidden" value="20" name="breedte">

 Upload je bestand(en)

            </form>

               Monomeer

                Specificaties

                  Hoogte : 90cm

                  Breedte : 90cm

                  uploaden : 1

                  Lijmlaag : Wit

                  Laminaat : Anti-slip laminaat

                  Afwerking : Contoursnijden

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>

            Benodigd formaat:

            90 x 90cm

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>
            Benodigde aantal
 bestanden: 1

            <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

            </button>
            Bestanden
toegewezen: 0 / 1

            <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>

            <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="1" id="dropzone4">
               <input type="hidden" value="Monomeer" name="productnaam">
               <input type="hidden" value="Twan" name="klantnaam">
               <input type="hidden" value="90" name="hoogte">
               <input type="hidden" value="90" name="breedte">

 Upload je bestand(en)

            </form>

What can be causing the bugs? I tried removing the :last parts and only upload one image in the first one and one in the second. But the first preview still doesn't have any information in it.

This is my custom previewelement inside .hiddendiv it's beneath the dropzones in my DOM:

                Bestandnaam:

                Resolutie:

                Formaat:

                Bestand heeft niet het benodigde formaat.

                    <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">

                    </button>

      <button class="yellowbtn btn vrijgevenbtn" type="button">Bestand vrijgeven</button>

            Aantal

        <input type="text" class="fileinput">
        <button class="plusminupload" id="minupload">−</button>
        <button class="plusminupload" id="plusupload">+</button>

Updated code from answer below:

$('.dropzone').each(function(index, element){
    let $el = $(element);
    let $maxfiles = $el.attr('maxfiles');
    let $inputquantity = $el.find('input').val();
    let $thispreview = $el.find('.hiddendiv');
    let $thisdropzone = $el;
    // $maxfiles = $(this).attr('maxfiles');
    // $inputquantity = $(this).find('input').val();
    // $thisdropzone = $(this);
    // $thispreview = $(this).find('.hiddendiv');

    $(this).dropzone({
        // clickable: ".uploadbutton, .dropzoneform",
        paramName: 'postedFile',
        addRemoveLinks: true,
        dictDefaultMessage: ' Upload je bestand(en)',
        dictRemoveFile: 'Verwijder',
        dictCancelUpload: 'Annuleren',
        dictInvalidFileType: 'Dit type bestand is niet toegestaan',
        dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
        dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
        maxFiles: $maxfiles,
        acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
        thumbnailWidth: '205',
        thumbnailHeight: '140',
        thumbnailMethod: 'crop',
        previewTemplate: $thispreview.html(),
        processing: function (file) {

        },
        // File contains dropzone file object, response contains ajax response from php file
        success: function (file, response) {
            // alert('test');
            let file_meta = JSON.parse(response);
            let $preview = $thisdropzone.find('.dz-preview:last');
            if(file_meta[0].status == 'success'){

            }else if(file_meta[0].status == 'error'){
                $preview.find('.vrijgevenbtn').show();
                $preview.find('.foutformaat').show();
            }
            $preview.find('.bestandnaam').text('Bestandsnaam: ' + file_meta[0].filename);
            $preview.find('.resolutie').text('Resolutie: ' + file_meta[0].dpi + ' DPI');
            $preview.find('.formaat').text('Formaat: ' + file_meta[0].heightcm + ' x ' + file_meta[0].widthcm + 'cm');
        },
    })
});

This is what happens when I upload multiple images in one selection:
Selecting three images from my computer:

Three previews in the dropzone with only the last one having data:

Every image returns a json string which in this example are:

[{"status":"error","filename":"instablok.jpg","filesize":22822,"tmp_name":"\/tmp\/phpI6ov6y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]

[{"status":"error","filename":"fbblok.jpg","filesize":17349,"tmp_name":"\/tmp\/phpBzh40y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]

[{"status":"error","filename":"logo-dark.png","filesize":21137,"tmp_name":"\/tmp\/phpCHGGZg","height":154,"width":881,"heightcm":"5,43","widthcm":"31,08","tifwidth":null,"dpi":"72"}]

All of them are returned seperately. The strange thing is, all data is added to the last preview and overwritten by a newer one. So the last preview first contains data from the first returned json, then the second and finally the last correct one, while the first two remain empty.

You can test with these two links:

First add a product to your basket here: https://printzelf.nl/new/folie/monomeer
You Aantal means quantity and this will determine how many images can be uploaded in a dropzone so you need more than 1 to be able to see the bug.

When you are done clicking through the options you can add it Toevoegen. Then go to the dropzone page link which is: https://printzelf.nl/new/bestanden-uploaden

Body:
let counterId = 0;
$('.dropzone').each(function(index){
        counterId++;
        $maxfiles = $(this).attr('maxfiles');
        $inputquantity = $(this).find('input').val();
        $thisdropzone = $(this);
        $(this).dropzone({
            autoProcessQueue:true,
            parallelUploads:1,
            paramName: 'postedFile',
            addRemoveLinks: true,
            dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
            dictRemoveFile: 'Verwijder',
            dictCancelUpload: 'Annuleren',
            dictInvalidFileType: 'Dit type bestand is niet toegestaan',
            dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
            dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
            maxFiles: $maxfiles,
            acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
            thumbnailWidth: '205',
            thumbnailHeight: '140',
            thumbnailMethod: 'crop',
            previewTemplate: $("#hiddendiv"+counterId).html(),
            sending: function (file) {

            },
            // File contains dropzone file object, response contains ajax response from php file
            success: function (file, response) {
                var obj = JSON.parse(response);
                $($thisdropzone).find('.dz-preview:last .bestandnaam').text('Bestandsnaam: ' + obj[0].filename);
                $($thisdropzone).find('.dz-preview:last .resolutie').text('Resolutie: ' + obj[0].dpi + ' DPI');
                $($thisdropzone).find('.dz-preview:last .formaat').text('Formaat: ' + obj[0].heightcm + ' x ' + obj[0].widthcm + 'cm');
            },
        })
    });

And rename your hiddenDiv to hiddenDiv1 and hiddenDiv2, If needed you could also add the hiddenDivs dynamically and use the counterId for the name.


问:
How to make a button destroy itself?
How do I make the destroy button destroy itself with the destroy() function, and still be able to make a new destroy button with the create button?</p>

```<code>from tkinter import Button, Tk

def create():
    b2 = Button(root, text='Destroy', command=destroy)
    b2.pack()

def destroy():
    b2.destroy()

root = Tk()

b1 = Button(root, text='Create', command=create)
b1.pack()

root.mainloop()
</code>```

答:
Try this:

```<code>from tkinter import *

def create():
    b = Button(root, text='Destroy')
    b.config(command=destroy(b))
    b.pack()

def destroy(button):
    def inner():
        button.destroy()
    return inner

root = Tk()

b1 = Button(root, text='Create', command=create)
b1.pack()

root.mainloop()
</code>```

We create a different callback for each new button, so we don't have to worry about scopes, and we can have more than destroy-able button.

Title: How to make a button destroy itself?

Body:
How do I make the destroy button destroy itself with the destroy() function, and still be able to make a new destroy button with the create button?

from tkinter import Button, Tk

def create():
    b2 = Button(root, text='Destroy', command=destroy)
    b2.pack()

def destroy():
    b2.destroy()

root = Tk()

b1 = Button(root, text='Create', command=create)
b1.pack()

root.mainloop()

Body:
Try this:

from tkinter import *

def create():
    b = Button(root, text='Destroy')
    b.config(command=destroy(b))
    b.pack()

def destroy(button):
    def inner():
        button.destroy()
    return inner

root = Tk()

b1 = Button(root, text='Create', command=create)
b1.pack()

root.mainloop()

We create a different callback for each new button, so we don't have to worry about scopes, and we can have more than destroy-able button.


问:
Is there any way to implement Quick Filter in server-side model ag-grid?
I have implemented server-side model in ag-grid with javascript, I tried with setQuickFilter function to implement global search but its not working for me. Is there any way to implement this stuff?

I tried with below code but its not working in server side model.

In HTML file:

```<code><input type="text" id="filter-text-box" placeholder="Filter..." oninput="onFilterTextBoxChanged()"/>
</code>```

In JS file:

```<code>function onFilterTextBoxChanged() {
    gridOptions.api.setQuickFilter(document.getElementById('filter-text-box').value);
}
</code>```

reference : https://www.ag-grid.com/javascript-grid-filter-quick/

答: No, Quick filter works only with client side data model.</p>

Body:
I have implemented server-side model in ag-grid with javascript, I tried with setQuickFilter function to implement global search but its not working for me. Is there any way to implement this stuff?

I tried with below code but its not working in server side model.

In HTML file:

<input type="text" id="filter-text-box" placeholder="Filter..." oninput="onFilterTextBoxChanged()"/>

In JS file:

function onFilterTextBoxChanged() {
    gridOptions.api.setQuickFilter(document.getElementById('filter-text-box').value);
}

reference : https://www.ag-grid.com/javascript-grid-filter-quick/


问:
how to copy and paste values and formatting
I have the following code that will copy my data to a blank row.  However, I cant figure out how to copy the values and formatting.</p>

```<code>Sub PasteValues()

  Worksheets("Summary").Range("A1:P12").Copy
  Worksheets("Summary").Cells(Rows.Count, 1).End(xlUp).Offset(2, 0).PasteSpecial xlPasteValuesAndNumberFormats

  Application.CutCopyMode = False

End Sub
</code>```

答:
You need to paste in values and formatting seperately, as per the below:

```<code>Sub PasteValues()

Worksheets("Sheet1").Range("A1").Copy
Worksheets("Sheet1").Range("A2").PasteSpecial xlValues
Worksheets("Sheet1").Range("A2").PasteSpecial xlFormats

Application.CutCopyMode = False

End Sub
</code>```

You'll obviously need to adapt to your own code, but it shows the principle.

Body:
I have the following code that will copy my data to a blank row.  However, I cant figure out how to copy the values and formatting.

Sub PasteValues()

  Worksheets("Summary").Range("A1:P12").Copy
  Worksheets("Summary").Cells(Rows.Count, 1).End(xlUp).Offset(2, 0).PasteSpecial xlPasteValuesAndNumberFormats

  Application.CutCopyMode = False

End Sub

Body:
You need to paste in values and formatting seperately, as per the below:

Sub PasteValues()

Worksheets("Sheet1").Range("A1").Copy
Worksheets("Sheet1").Range("A2").PasteSpecial xlValues
Worksheets("Sheet1").Range("A2").PasteSpecial xlFormats

Application.CutCopyMode = False

End Sub

You'll obviously need to adapt to your own code, but it shows the principle.


问:
how do I get cursor:pointer on an embedded object?
1) I am trying to place a transparent image over an embedded object. I am missing positions, relative and absolute, somewhere. But where?

I am actually placing the transparent image because I cannot use cursor:pointer for the object embed. So my idea was to place a transparent image and use cursor:pointer.

2) Why doesn't onclick work in IE? It works fine in Firefox and Chrome.

```<code><div id="divmarquee" runat="server" >
     <img id="imgtrans" runat="server" src= "/images/480x75-blank-transparent" title="Click Here" style="position:relative" />
           <object width="475px" height="75px" onclick="window.location='http://www.google.com'; return false;">
                 <embed src="merchant_images/The_Marquee_Dealn.swf" type="application/x-shockwave-flash" style="z-index: 0; cursor:pointer" wmode="transparent" width="475px" height="75px">
                 </embed>
            </object>
  </div>
</code>```

Thanks in advance!

答: In your code above you added cursor: pointer to the embed-tag. Try moving it to the image tag instead.</p>

Body:
1) I am trying to place a transparent image over an embedded object. I am missing positions, relative and absolute, somewhere. But where?

I am actually placing the transparent image because I cannot use cursor:pointer for the object embed. So my idea was to place a transparent image and use cursor:pointer.

2) Why doesn't onclick work in IE? It works fine in Firefox and Chrome.

           <object width="475px" height="75px" onclick="window.location='http://www.google.com'; return false;">
                 <embed src="merchant_images/The_Marquee_Dealn.swf" type="application/x-shockwave-flash" style="z-index: 0; cursor:pointer" wmode="transparent" width="475px" height="75px">
                 </embed>
            </object>

Thanks in advance!