问:
Rails ActiveStorage: ActiveStorage::FileNotFoundError
I'm seeing the following error when attempting to use .attach to upload an image to a model in my Rails application.

I'm trying to

```<code>@company.best_landing_page_screenshot.attach(
        params.require(:company).fetch(:best_landing_page_screenshot),
      )
</code>```

The issue is that the AnalyzeJob kicks in before the upload is completed.
Therefore, the AnalyzeJob (processed immediately in dev) fails.

The same issue is outlined here with no resolution: https://github.com/rails/rails/issues/39107

With Sidekiq inline testing turn off, it works fine:

```<code>@model.best_landing_page_screenshot.attach(
  params.require(:company).fetch(:best_landing_page_screenshot),
  ActiveStorage::Blob Load (7.9ms)  SELECT `active_storage_blobs`.* FROM `active_storage_blobs` INNER JOIN `active_storage_attachments` ON `active_storage_blobs`.`id` = `active_storage_attachments`.`blob_id` WHERE `active_storage_attachments`.`record_id` = 15352 AND `active_storage_attachments`.`record_type` = 'Company' AND `active_storage_attachments`.`name` = 'best_landing_page_screenshot' LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Attachment Load (4.4ms)  SELECT `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 15352 AND `active_storage_attachments`.`record_type` = 'Company' AND `active_storage_attachments`.`name` = 'best_landing_page_screenshot' LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (1.1ms)  BEGIN
  ActiveStorage::Attachment Destroy (1.6ms)  DELETE FROM `active_storage_attachments` WHERE `active_storage_attachments`.`id` = 1311
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Blob Create (5.0ms)  INSERT INTO `active_storage_blobs` (`key`, `filename`, `content_type`, `metadata`, `byte_size`, `checksum`, `created_at`, `service_name`) VALUES ('y19tkuk2xe6yqpbi404zq5nnuwp6', 'screely-1639331463764.png', 'image/png', '{\"identified\":true}', 1643856, 'ad3q6qj6AE7QVe5MvHUnig==', '2021-12-12 18:29:02', 'amazon')
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Attachment Create (6.0ms)  INSERT INTO `active_storage_attachments` (`name`, `record_type`, `record_id`, `blob_id`, `created_at`) VALUES ('best_landing_page_screenshot', 'Company', 15352, 220, '2021-12-12 18:29:02')
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (3.1ms)  COMMIT
  ActiveStorage::Blob Load (5.0ms)  SELECT `active_storage_blobs`.* FROM `active_storage_blobs` WHERE `active_storage_blobs`.`id` = 218 LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
[ActiveJob] Enqueued ActiveStorage::PurgeJob (Job ID: 715e6d4a-bbb6-4525-bf50-b2a9b6dbdf33) to Sidekiq(default) with arguments: #<GlobalID:0x00007fd807172aa0 @uri=#<URI::GID gid://sendapostcardonline/ActiveStorage::Blob/218>>
[ActiveJob] Enqueued ActiveStorage::AnalyzeJob (Job ID: 53410b6b-3eef-4803-9b48-f1bf3e2f9c5c) to Sidekiq(default) with arguments: #<GlobalID:0x00007fd7f3047590 @uri=#<URI::GID gid://sendapostcardonline/ActiveStorage::Blob/220>>
  TRANSACTION (90.9ms)  BEGIN
  Company Update (84.4ms)  UPDATE `companies` SET `companies`.`updated_at` = '2021-12-12 18:29:02.899300' WHERE `companies`.`id` = 15352
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (86.9ms)  COMMIT
  S3 Storage (1682.0ms) Uploaded file to key: xxxx (checksum: xxx==)
</code>```

Can anyone shed some light on this?

答:
In my case, what I noticed is that attaching attachments with ActiveStorage is not working properly when doing it inside a transaction. This applies to migrations, seeds or callbacks.

What I finally did to avoid my logic being wrapped inside a transaction is to run the logic inside a thread:

Thread.new do
  # your logic here
end.join
```

Body:
I'm seeing the following error when attempting to use .attach to upload an image to a model in my Rails application.

I'm trying to

@company.best_landing_page_screenshot.attach(
        params.require(:company).fetch(:best_landing_page_screenshot),
      )

The issue is that the AnalyzeJob kicks in before the upload is completed.
Therefore, the AnalyzeJob (processed immediately in dev) fails.

The same issue is outlined here with no resolution: https://github.com/rails/rails/issues/39107

With Sidekiq inline testing turn off, it works fine:

@model.best_landing_page_screenshot.attach(
  params.require(:company).fetch(:best_landing_page_screenshot),
  ActiveStorage::Blob Load (7.9ms)  SELECT `active_storage_blobs`.* FROM `active_storage_blobs` INNER JOIN `active_storage_attachments` ON `active_storage_blobs`.`id` = `active_storage_attachments`.`blob_id` WHERE `active_storage_attachments`.`record_id` = 15352 AND `active_storage_attachments`.`record_type` = 'Company' AND `active_storage_attachments`.`name` = 'best_landing_page_screenshot' LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Attachment Load (4.4ms)  SELECT `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 15352 AND `active_storage_attachments`.`record_type` = 'Company' AND `active_storage_attachments`.`name` = 'best_landing_page_screenshot' LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (1.1ms)  BEGIN
  ActiveStorage::Attachment Destroy (1.6ms)  DELETE FROM `active_storage_attachments` WHERE `active_storage_attachments`.`id` = 1311
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Blob Create (5.0ms)  INSERT INTO `active_storage_blobs` (`key`, `filename`, `content_type`, `metadata`, `byte_size`, `checksum`, `created_at`, `service_name`) VALUES ('y19tkuk2xe6yqpbi404zq5nnuwp6', 'screely-1639331463764.png', 'image/png', '{\"identified\":true}', 1643856, 'ad3q6qj6AE7QVe5MvHUnig==', '2021-12-12 18:29:02', 'amazon')
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  ActiveStorage::Attachment Create (6.0ms)  INSERT INTO `active_storage_attachments` (`name`, `record_type`, `record_id`, `blob_id`, `created_at`) VALUES ('best_landing_page_screenshot', 'Company', 15352, 220, '2021-12-12 18:29:02')
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (3.1ms)  COMMIT
  ActiveStorage::Blob Load (5.0ms)  SELECT `active_storage_blobs`.* FROM `active_storage_blobs` WHERE `active_storage_blobs`.`id` = 218 LIMIT 1
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
[ActiveJob] Enqueued ActiveStorage::PurgeJob (Job ID: 715e6d4a-bbb6-4525-bf50-b2a9b6dbdf33) to Sidekiq(default) with arguments: #<GlobalID:0x00007fd807172aa0 @uri=#<URI::GID gid://sendapostcardonline/ActiveStorage::Blob/218>>
[ActiveJob] Enqueued ActiveStorage::AnalyzeJob (Job ID: 53410b6b-3eef-4803-9b48-f1bf3e2f9c5c) to Sidekiq(default) with arguments: #<GlobalID:0x00007fd7f3047590 @uri=#<URI::GID gid://sendapostcardonline/ActiveStorage::Blob/220>>
  TRANSACTION (90.9ms)  BEGIN
  Company Update (84.4ms)  UPDATE `companies` SET `companies`.`updated_at` = '2021-12-12 18:29:02.899300' WHERE `companies`.`id` = 15352
Query Trace:
      app/controllers/admin/lead_enrichment_controller.rb:67:in `update'
  TRANSACTION (86.9ms)  COMMIT
  S3 Storage (1682.0ms) Uploaded file to key: xxxx (checksum: xxx==)

Can anyone shed some light on this?


来源: stackexchange

问:
Excel Conditional Formatting is incorrect when value is entered by VBA Code
i got some Question marks over my head with this problem and hope you can help me out with this.

In 2 Columns i got some Numbers formatted as text, for example "1.234". This values are entered after an Button click from the VBA Code. After this the first Cell also got some Conditional Formatting to show a red or green BG if the Values are equal to each other or not.

Conditional Formatting looks like:

```<code>With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(1).Font.Color = -16752384
    .FormatConditions(1).Interior.Color = 13561798
    .FormatConditions(1).StopIfTrue = True
End With
With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlNotEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(2).Font.Color = -16383844
    .FormatConditions(2).Interior.Color = 13551615
    .FormatConditions(2).StopIfTrue = True
End With
</code>```

So this works as expected, if its the same number e.g. 1.234 this Cell is green and if not its red.

If i change the cell value manually to anything else the BG color switches as expected between red and green. But the point of this is not to enter the end number manually, so i got this line of code for the calculation:

```<code>Cells(active_cell_row, find_column.Column) = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)
</code>```

This enters the right number to the cell, but the conditional Formatting is always red even if the values are the same. If i overwrite the same value manually the conditional formatting switches to green...

答:
Ok Never mind i fixed this by myself..

If anyone got this problem:

First declare the value as an string...

```<code>Dim txt As String: txt = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)
Cells(active_cell_row, find_column.Column) = txt
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i got some Question marks over my head with this problem and hope you can help me out with this.

In 2 Columns i got some Numbers formatted as text, for example "1.234". This values are entered after an Button click from the VBA Code. After this the first Cell also got some Conditional Formatting to show a red or green BG if the Values are equal to each other or not.

Conditional Formatting looks like:

With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(1).Font.Color = -16752384
    .FormatConditions(1).Interior.Color = 13561798
    .FormatConditions(1).StopIfTrue = True
End With
With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlNotEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(2).Font.Color = -16383844
    .FormatConditions(2).Interior.Color = 13551615
    .FormatConditions(2).StopIfTrue = True
End With

So this works as expected, if its the same number e.g. 1.234 this Cell is green and if not its red.

If i change the cell value manually to anything else the BG color switches as expected between red and green. But the point of this is not to enter the end number manually, so i got this line of code for the calculation:

Cells(active_cell_row, find_column.Column) = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)

This enters the right number to the cell, but the conditional Formatting is always red even if the values are the same. If i overwrite the same value manually the conditional formatting switches to green...

Body:
Ok Never mind i fixed this by myself..

If anyone got this problem:

First declare the value as an string...

Dim txt As String: txt = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)
Cells(active_cell_row, find_column.Column) = txt


问:
JavaFX and CSS: font wont't appear on Application
Yesterday, I tried to embedd a custom font and it worked somehow, unfortunately I destroyed the git project because of a wrong clean command. So today, I cloned the repo on a different location and tried it again the exact same way like yesterday. It does not work. So I tried both loading a font directly in the resources folder and one in another folder that's in the resources folder called fonts

Here my CSS-File main.css

```<code>@font-face {
    font-family: "Font";
    src: url("font-regular.ttf");
}

@font-face {
    font-family: "Fontnew";
    src: url("fonts/font.ttf");
}

.root {
    -fx-font-family: "Fontnew";
}
</code>```

I get this stylesheet by

```<code>scene.getStylesheets().add("main.css");
</code>```

And the application gets this stylesheet by 100% because other classes in the CSS-file that are responsible for hovering effects work and System.out.println(scene.getStylesheets().add("main.css")); says it's true in the console

答:
Try this in your Main.</p>
```<code>scene.getStylesheets().add(getClass().getResource("main.css").toExternalForm());
</code>```

Body:
Yesterday, I tried to embedd a custom font and it worked somehow, unfortunately I destroyed the git project because of a wrong clean command. So today, I cloned the repo on a different location and tried it again the exact same way like yesterday. It does not work. So I tried both loading a font directly in the resources folder and one in another folder that's in the resources folder called fonts

Here my CSS-File main.css

@font-face {
    font-family: "Font";
    src: url("font-regular.ttf");
}

@font-face {
    font-family: "Fontnew";
    src: url("fonts/font.ttf");
}

.root {
    -fx-font-family: "Fontnew";
}

I get this stylesheet by

scene.getStylesheets().add("main.css");

And the application gets this stylesheet by 100% because other classes in the CSS-file that are responsible for hovering effects work and System.out.println(scene.getStylesheets().add("main.css")); says it's true in the console

Body:
Try this in your Main.

scene.getStylesheets().add(getClass().getResource("main.css").toExternalForm());


问:
Take screenshot of a FMX form from another process, even if the form is not topmost / modal
I am currently trying to take a screenshot of a 2D Firemonkey (FMX) form from another process.

The following is using a well-known method based of GDI, using a BitBlt() to produce a bitmap, and WIC to save it to a PNG file.

{...}
uses
  system.UITypes,
  system.SysUtils,
  system.Hash,
  {$IF Defined(MSWINDOWS)}
  winapi.Windows,
  Winapi.Direct3D9,
  WinApi.D3DX9,
  Winapi.Wincodec,
  WinApi.ActiveX,
  {$ENDIF}
  { some internal units }
  path.types,
  path.utils,
  os.utils;

{...}

Type
  TWindowSnapshot = record
     window_handle: THandle;    // handle to window
     process_id: Cardinal;      // PID of the process
     window_rect: TRect;        // position of the window
     title: string;             // title
     file_path: string;         // path to the window's image file
  end;

  TWindowSnapshots = Tarray<TWindowSnapshot>;

procedure HRCHECK(r: HRESULT); inline;
begin
  if r <> S_OK then abort;
end;

function pad(s,g:integer): integer; inline;
begin
 dec(g);
 result := (s + g) and not g;
end;

function WICSavePixelsToPng(r: TRect; stride: cardinal; pixels: PByte; filePath: string): HRESULT;
var
  factory: IWICImagingFactory;
  encoder: IWICBitmapEncoder;
  frame: IWICBitmapFrameEncode;
  encoderOptions: IPropertyBag2;
  stream: IWICStream;
  pf: TGUID;
  coInit : HResult;

begin
  result := E_INVALIDARG;
  if not assigned(pixels) then exit;
  if (filepath = '')  then exit;
  coInit := CoInitialize(nil);
  pf := GUID_WICPixelFormat32bppBGRA;
  result := CoCreateInstance(CLSID_WICImagingFactory, nil, CLSCTX_INPROC_SERVER, IWICImagingFactory, factory);
  if result <> S_OK then exit;
  result := factory.CreateStream(&stream);
  if result <> S_OK then exit;
  result := stream.InitializeFromFilename(PWideChar(filePath), GENERIC_WRITE);
  if result <> S_OK then exit;
  result := factory.CreateEncoder(GUID_ContainerFormatPng, TGUID.Empty, encoder);
  if result <> S_OK then exit;
  result := encoder.Initialize(stream, WICBitmapEncoderNoCache);
  if result <> S_OK then exit;
  result := encoder.CreateNewFrame(frame, encoderOptions);
  if result <> S_OK then exit;
  result := frame.Initialize(nil);
  if result <> S_OK then exit;
  result := frame.SetSize(r.width, r.height);
  if result <> S_OK then exit;
  result := frame.SetPixelFormat(pf);
  if result <> S_OK then exit;
  if pf <> GUID_WICPixelFormat32bppBGRA then
  begin
    assert(false,'ToDo');
  end;
  inc(pixels,(r.Left*4) + r.Top * stride);
  result := frame.WritePixels(r.height, stride, stride * r.height, pixels);
  if result <> S_OK then exit;
  result := frame.Commit();
  if result <> S_OK then exit;
  result := encoder.Commit();
  if (coInit <> 0) then
    CoUninitialize();
end;

function take_window_snapshot_GDI(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
    var
      Wr: TRect;
      HdcSRC: HDC;
      hDCDest: HDC;
      hBmp: HBITMAP;
      hOld: HGDIOBJ;
      hFlags: Cardinal;
      l: integer;
      src_shot,dst_shot,lsrc,ldst: PByte;
      sr: PRGBTriple;
      dr: PRGBQuad;
      buff_size: cardinal;
      x,y, src_stride, dst_stride: integer;
      bi: tagBITMAPINFO;

    begin
      result := false;
      cs.window_handle := win_handle;
      cs.title := '';
      cs.window_rect := TRect.Empty;
      cs.process_id := 0;
      try
        hFlags := GetWindowLong(win_handle,GWL_STYLE);
        if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
        if (hFlags and WS_VISIBLE) = 0 then exit;
        GetWindowRect(win_handle,Wr);
        if (Wr.Width = 0) or (Wr.Height = 0) then exit;
        L := GetWindowTextLength(win_handle);
        if L > 0 then
        begin
          setlength(cs.title,L);
          GetWindowText(win_handle,pchar(cs.title),L+1);
        end;

        { reserve memory for bitmaps }
        src_stride := pad((wr.Width * 3),4);
        dst_stride := pad((wr.Width * 4),4);
        buff_size := src_stride * wr.Height;
        getmem(src_shot,buff_size);
        if not assigned(src_shot) then exit;
        getmem(dst_shot,dst_stride * wr.Height);
        if not assigned(src_shot) then
        begin
          freemem(src_shot);
          exit;
        end;
        try
          try
            HdcSRC := GetWindowDC(win_handle);
            HdcDest := CreateCompatibleDC(HdcSRC);
            SetStretchBltMode(HdcDest, COLORONCOLOR);
            HBmp := CreateCompatibleBitmap(HdcSRC,Wr.Width,wr.Height);
            hOld := SelectObject(hDCDest,hBmp);
            BitBlt(hDCDest,0,0,wr.width,wr.Height,HdcSRC,0,0,SRCCOPY);

            { target bitplane is 24 bits RGB }
            bi := default(tagBITMAPINFO);
            bi.bmiHeader.biSize := sizeof(TBitmapInfoHeader);
            bi.bmiHeader.biWidth := wr.Width;
            bi.bmiHeader.biHeight := wr.Height;
            bi.bmiHeader.biPlanes := 1;
            bi.bmiHeader.biBitCount := 24;
            bi.bmiHeader.biCompression := BI_RGB;
            GetDIBits(hDCDest,HBmp,0,wr.Height,src_shot,bi,DIB_RGB_COLORS);

            { now convert pixels to RGBA, in correct line order.
              On Windows, last line is first in bitmap }
            ldst := dst_shot;
            lsrc := src_shot + (src_stride * wr.Height);
            for y := 0 to wr.Height  - 1 do
            begin
              dec(lsrc,src_stride);
              sr := pointer(lsrc);
              dr := pointer(ldst);
              for x := 0 to wr.Width - 1 do
              begin
                dr.rgbBlue := sr.rgbtBlue;
                dr.rgbRed := sr.rgbtRed;
                dr.rgbGreen := sr.rgbtGreen;
                dr.rgbReserved := 255;
                inc(dr);
                inc(sr);
              end;
              inc(ldst,dst_stride);
            end;

            { save to PNG with WIC }
            var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
            wr.Offset(-wr.Left,-wr.top);
            if WICSavePixelsToPng(wr,dst_stride,dst_shot,tmp_name) = S_OK then
            begin
              result := true;
              { rename temp file name to new name if it doesn't exist already }
              var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
              if not TPath.FileExists(new_name) then
              begin
                if Tfile.Rename(tmp_name,new_name) then
                begin
                  cs.file_path := '';
                end else begin
                  cs.file_path := new_name;
                end;
              end else begin
                cs.file_path := new_name;
              end;
            end;
            Tfile.Delete(tmp_name);
            result := true;
          finally
            freemem(src_shot);
            freemem(dst_shot);
          end;
        finally
          SelectObject(hDCDest,hold);
          DeleteDC(hDCDest);
          ReleaseDC(win_handle,HdcSRC);
        end;
        except begin
          result := false;
        end;
      end;
    end;
```
<p>This method is working for Delphi forms using VCL, however with forms using Firemonkey (FMX)  2D, it only produces bitmaps filled with BLACK (0) pixels.</p>
<p>I have tried an alternative using Direct3D9, that is working for Firemonkey form, however with a limitation I'll explain after the code snippet</p>
<pre class="lang-delphi prettyprint-override"><code>function Take_window_snapshot_D3D(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
var
  D3D: IDirect3D9;
  D3DDevice: IDirect3DDevice9;
  mode: D3DDISPLAYMODE;
  device: IDirect3DDevice9;
  surface: IDirect3DSurface9;
  parameters: D3DPRESENT_PARAMETERS;
  rc: D3DLOCKED_RECT;
  pitch: UINT;
  shot: PByte;
  shot_size: cardinal;
  adapter: cardinal;
  wr: TRect;
  hCurWnd: THandle;
  hCurThreadID: Cardinal;
  L: integer;
  hFlags: cardinal;
  hr: HRESULT;

begin
  result := false;
  cs := default(TWindowSnapshot);
  try
    { get the window type }
    hFlags := GetWindowLong(win_handle,GWL_STYLE);
    if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
    if (hFlags and WS_VISIBLE) = 0 then exit;
    { size }
    GetWindowRect(win_handle,Wr);
    if (Wr.Width = 0) or (Wr.Height = 0) then exit;
    { title }
    L := GetWindowTextLength(win_handle);
    if L > 0 then
    begin
      setlength(cs.title,L);
      GetWindowText(win_handle,pchar(cs.title),L+1);
    end;
    cs.window_handle := win_handle;
    cs.window_rect := wr;
    cs.process_id := PID;

    { Direct3D capture }
    adapter := D3DADAPTER_DEFAULT;
    D3D := Direct3DCreate9(D3D_SDK_VERSION);
    HRCHECK(D3D.GetAdapterDisplayMode(adapter,mode));
    parameters := default(D3DPRESENT_PARAMETERS);
    parameters.Windowed := TRUE;
    parameters.BackBufferCount := 1;
    parameters.BackBufferHeight := mode.Height;
    parameters.BackBufferWidth := mode.Width;
    parameters.SwapEffect := D3DSWAPEFFECT_DISCARD;
    parameters.hDeviceWindow := win_handle;

    { create device & capture surface }
    HRCHECK(d3d.CreateDevice(adapter, D3DDEVTYPE_HAL, win_handle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, @parameters, device));
    { create surface }
    HRCHECK(device.CreateOffscreenPlainSurface(mode.Width, mode.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &surface, nil));

    { bring our window to front }
    hCurWnd := GetForegroundWindow;
    hCurThreadID := GetCurrentThreadId;
    AttachThreadInput(PID,hCurThreadID,TRUE);
    SetWindowPos(win_handle,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE or SWP_NOMOVE);
    SetWindowPos(win_handle,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW or SWP_NOSIZE or SWP_NOMOVE);
    SetForegroundWindow(win_handle);
    SetFocus(win_handle);
    SetActiveWindow(win_handle);
    AttachThreadInput(PID,hCurThreadID,false);

    { Obtain stride value to allocate buffer }
    HRCHECK(surface.LockRect(rc,nil,0));
    pitch := rc.Pitch;
    HRCHECK(surface.UnlockRect());
    shot_size := pitch*mode.Height;
    getmem(shot,shot_size);
    if not assigned(shot) then abort;

    try
      { get surface data }
      HRCHECK(device.GetFrontBufferData(0, surface));
      { copy surface data }
      HRCHECK(surface.LockRect(rc,nil,0));
      move(rc.pBits^,shot^,shot_size);
      HRCHECK(surface.UnlockRect());

      { save snapshot to file using WIC, using a temporary file name first }
      var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
      if WICSavePixelsToPng(wr,pitch,shot,tmp_name) = S_OK then
      begin
        result := true;
        { rename temp file name to new name if it doesn't exist already }
        var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
        if not TPath.FileExists(new_name) then
        begin
          if Tfile.Rename(tmp_name,new_name) then
          begin
            cs.file_path := '';
          end else begin
            cs.file_path := new_name;
          end;
        end else begin
          cs.file_path := new_name;
        end;
      end;
      Tfile.Delete(tmp_name);
    finally
      FreeMem(shot);
    end;
    except
      result := false;
  end;
end;

</code>```

The limitation that I have with the D3D method is that in reality I don't take a snapshot of a specific window but I take a snapshot of the entire screen that I crop after to take only the window of my interest.
For that, I must bring first the target window to front, but in some case this may not be possible. For instance if the target form is behind a modal form, it might be partially or totally hidden, as one can see below

So, my question : Is it possible to take a snapshot / print a single Firemonkey 2D form from another process, even if the form is not modal / partially covered by another form.

答:
(Sorry for an answer here rather than a comment, which I can't do.)

I know little about working with different processes, but do you realise that FMX has a snapshot ability built in?
TControl.MakeScreenshot returns a bitmap of the control (with child controls).  So if you can call that from the other process and return the result, that might solve your problem.
However, this won't meet your needs if you literally need the whole form including the non-client area, as a form doesn't have that method.  If the contents of the form are all you need, and you have a control (e.g. a TLayout) filling the form and containing all the child controls, you could use the .MakeScreenshot of that bottom control.

And yes, .MakeScreeshot works even if something else is covering the form.

Body:
I am currently trying to take a screenshot of a 2D Firemonkey (FMX) form from another process.

The following is using a well-known method based of GDI, using a BitBlt() to produce a bitmap, and WIC to save it to a PNG file.

{...}
uses
  system.UITypes,
  system.SysUtils,
  system.Hash,
  {$IF Defined(MSWINDOWS)}
  winapi.Windows,
  Winapi.Direct3D9,
  WinApi.D3DX9,
  Winapi.Wincodec,
  WinApi.ActiveX,
  {$ENDIF}
  { some internal units }
  path.types,
  path.utils,
  os.utils;

{...}

Type
  TWindowSnapshot = record
     window_handle: THandle;    // handle to window
     process_id: Cardinal;      // PID of the process
     window_rect: TRect;        // position of the window
     title: string;             // title
     file_path: string;         // path to the window's image file
  end;

  TWindowSnapshots = Tarray<TWindowSnapshot>;

procedure HRCHECK(r: HRESULT); inline;
begin
  if r <> S_OK then abort;
end;

function pad(s,g:integer): integer; inline;
begin
 dec(g);
 result := (s + g) and not g;
end;

function WICSavePixelsToPng(r: TRect; stride: cardinal; pixels: PByte; filePath: string): HRESULT;
var
  factory: IWICImagingFactory;
  encoder: IWICBitmapEncoder;
  frame: IWICBitmapFrameEncode;
  encoderOptions: IPropertyBag2;
  stream: IWICStream;
  pf: TGUID;
  coInit : HResult;

begin
  result := E_INVALIDARG;
  if not assigned(pixels) then exit;
  if (filepath = '')  then exit;
  coInit := CoInitialize(nil);
  pf := GUID_WICPixelFormat32bppBGRA;
  result := CoCreateInstance(CLSID_WICImagingFactory, nil, CLSCTX_INPROC_SERVER, IWICImagingFactory, factory);
  if result <> S_OK then exit;
  result := factory.CreateStream(&stream);
  if result <> S_OK then exit;
  result := stream.InitializeFromFilename(PWideChar(filePath), GENERIC_WRITE);
  if result <> S_OK then exit;
  result := factory.CreateEncoder(GUID_ContainerFormatPng, TGUID.Empty, encoder);
  if result <> S_OK then exit;
  result := encoder.Initialize(stream, WICBitmapEncoderNoCache);
  if result <> S_OK then exit;
  result := encoder.CreateNewFrame(frame, encoderOptions);
  if result <> S_OK then exit;
  result := frame.Initialize(nil);
  if result <> S_OK then exit;
  result := frame.SetSize(r.width, r.height);
  if result <> S_OK then exit;
  result := frame.SetPixelFormat(pf);
  if result <> S_OK then exit;
  if pf <> GUID_WICPixelFormat32bppBGRA then
  begin
    assert(false,'ToDo');
  end;
  inc(pixels,(r.Left*4) + r.Top * stride);
  result := frame.WritePixels(r.height, stride, stride * r.height, pixels);
  if result <> S_OK then exit;
  result := frame.Commit();
  if result <> S_OK then exit;
  result := encoder.Commit();
  if (coInit <> 0) then
    CoUninitialize();
end;

function take_window_snapshot_GDI(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
    var
      Wr: TRect;
      HdcSRC: HDC;
      hDCDest: HDC;
      hBmp: HBITMAP;
      hOld: HGDIOBJ;
      hFlags: Cardinal;
      l: integer;
      src_shot,dst_shot,lsrc,ldst: PByte;
      sr: PRGBTriple;
      dr: PRGBQuad;
      buff_size: cardinal;
      x,y, src_stride, dst_stride: integer;
      bi: tagBITMAPINFO;

    begin
      result := false;
      cs.window_handle := win_handle;
      cs.title := '';
      cs.window_rect := TRect.Empty;
      cs.process_id := 0;
      try
        hFlags := GetWindowLong(win_handle,GWL_STYLE);
        if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
        if (hFlags and WS_VISIBLE) = 0 then exit;
        GetWindowRect(win_handle,Wr);
        if (Wr.Width = 0) or (Wr.Height = 0) then exit;
        L := GetWindowTextLength(win_handle);
        if L > 0 then
        begin
          setlength(cs.title,L);
          GetWindowText(win_handle,pchar(cs.title),L+1);
        end;

        { reserve memory for bitmaps }
        src_stride := pad((wr.Width * 3),4);
        dst_stride := pad((wr.Width * 4),4);
        buff_size := src_stride * wr.Height;
        getmem(src_shot,buff_size);
        if not assigned(src_shot) then exit;
        getmem(dst_shot,dst_stride * wr.Height);
        if not assigned(src_shot) then
        begin
          freemem(src_shot);
          exit;
        end;
        try
          try
            HdcSRC := GetWindowDC(win_handle);
            HdcDest := CreateCompatibleDC(HdcSRC);
            SetStretchBltMode(HdcDest, COLORONCOLOR);
            HBmp := CreateCompatibleBitmap(HdcSRC,Wr.Width,wr.Height);
            hOld := SelectObject(hDCDest,hBmp);
            BitBlt(hDCDest,0,0,wr.width,wr.Height,HdcSRC,0,0,SRCCOPY);

            { target bitplane is 24 bits RGB }
            bi := default(tagBITMAPINFO);
            bi.bmiHeader.biSize := sizeof(TBitmapInfoHeader);
            bi.bmiHeader.biWidth := wr.Width;
            bi.bmiHeader.biHeight := wr.Height;
            bi.bmiHeader.biPlanes := 1;
            bi.bmiHeader.biBitCount := 24;
            bi.bmiHeader.biCompression := BI_RGB;
            GetDIBits(hDCDest,HBmp,0,wr.Height,src_shot,bi,DIB_RGB_COLORS);

            { now convert pixels to RGBA, in correct line order.
              On Windows, last line is first in bitmap }
            ldst := dst_shot;
            lsrc := src_shot + (src_stride * wr.Height);
            for y := 0 to wr.Height  - 1 do
            begin
              dec(lsrc,src_stride);
              sr := pointer(lsrc);
              dr := pointer(ldst);
              for x := 0 to wr.Width - 1 do
              begin
                dr.rgbBlue := sr.rgbtBlue;
                dr.rgbRed := sr.rgbtRed;
                dr.rgbGreen := sr.rgbtGreen;
                dr.rgbReserved := 255;
                inc(dr);
                inc(sr);
              end;
              inc(ldst,dst_stride);
            end;

            { save to PNG with WIC }
            var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
            wr.Offset(-wr.Left,-wr.top);
            if WICSavePixelsToPng(wr,dst_stride,dst_shot,tmp_name) = S_OK then
            begin
              result := true;
              { rename temp file name to new name if it doesn't exist already }
              var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
              if not TPath.FileExists(new_name) then
              begin
                if Tfile.Rename(tmp_name,new_name) then
                begin
                  cs.file_path := '';
                end else begin
                  cs.file_path := new_name;
                end;
              end else begin
                cs.file_path := new_name;
              end;
            end;
            Tfile.Delete(tmp_name);
            result := true;
          finally
            freemem(src_shot);
            freemem(dst_shot);
          end;
        finally
          SelectObject(hDCDest,hold);
          DeleteDC(hDCDest);
          ReleaseDC(win_handle,HdcSRC);
        end;
        except begin
          result := false;
        end;
      end;
    end;

This method is working for Delphi forms using VCL, however with forms using Firemonkey (FMX)  2D, it only produces bitmaps filled with BLACK (0) pixels.

I have tried an alternative using Direct3D9, that is working for Firemonkey form, however with a limitation I'll explain after the code snippet

function Take_window_snapshot_D3D(win_handle: THandle; PID: Cardinal; out cs: TWindowSnapshot; const image_folder: string): boolean;
var
  D3D: IDirect3D9;
  D3DDevice: IDirect3DDevice9;
  mode: D3DDISPLAYMODE;
  device: IDirect3DDevice9;
  surface: IDirect3DSurface9;
  parameters: D3DPRESENT_PARAMETERS;
  rc: D3DLOCKED_RECT;
  pitch: UINT;
  shot: PByte;
  shot_size: cardinal;
  adapter: cardinal;
  wr: TRect;
  hCurWnd: THandle;
  hCurThreadID: Cardinal;
  L: integer;
  hFlags: cardinal;
  hr: HRESULT;

begin
  result := false;
  cs := default(TWindowSnapshot);
  try
    { get the window type }
    hFlags := GetWindowLong(win_handle,GWL_STYLE);
    if (hFlags and (WS_DLGFRAME or WS_POPUP)) = 0 then exit;
    if (hFlags and WS_VISIBLE) = 0 then exit;
    { size }
    GetWindowRect(win_handle,Wr);
    if (Wr.Width = 0) or (Wr.Height = 0) then exit;
    { title }
    L := GetWindowTextLength(win_handle);
    if L > 0 then
    begin
      setlength(cs.title,L);
      GetWindowText(win_handle,pchar(cs.title),L+1);
    end;
    cs.window_handle := win_handle;
    cs.window_rect := wr;
    cs.process_id := PID;

    { Direct3D capture }
    adapter := D3DADAPTER_DEFAULT;
    D3D := Direct3DCreate9(D3D_SDK_VERSION);
    HRCHECK(D3D.GetAdapterDisplayMode(adapter,mode));
    parameters := default(D3DPRESENT_PARAMETERS);
    parameters.Windowed := TRUE;
    parameters.BackBufferCount := 1;
    parameters.BackBufferHeight := mode.Height;
    parameters.BackBufferWidth := mode.Width;
    parameters.SwapEffect := D3DSWAPEFFECT_DISCARD;
    parameters.hDeviceWindow := win_handle;

    { create device & capture surface }
    HRCHECK(d3d.CreateDevice(adapter, D3DDEVTYPE_HAL, win_handle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, @parameters, device));
    { create surface }
    HRCHECK(device.CreateOffscreenPlainSurface(mode.Width, mode.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &surface, nil));

    { bring our window to front }
    hCurWnd := GetForegroundWindow;
    hCurThreadID := GetCurrentThreadId;
    AttachThreadInput(PID,hCurThreadID,TRUE);
    SetWindowPos(win_handle,HWND_TOPMOST,0,0,0,0,SWP_NOSIZE or SWP_NOMOVE);
    SetWindowPos(win_handle,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW or SWP_NOSIZE or SWP_NOMOVE);
    SetForegroundWindow(win_handle);
    SetFocus(win_handle);
    SetActiveWindow(win_handle);
    AttachThreadInput(PID,hCurThreadID,false);

    { Obtain stride value to allocate buffer }
    HRCHECK(surface.LockRect(rc,nil,0));
    pitch := rc.Pitch;
    HRCHECK(surface.UnlockRect());
    shot_size := pitch*mode.Height;
    getmem(shot,shot_size);
    if not assigned(shot) then abort;

    try
      { get surface data }
      HRCHECK(device.GetFrontBufferData(0, surface));
      { copy surface data }
      HRCHECK(surface.LockRect(rc,nil,0));
      move(rc.pBits^,shot^,shot_size);
      HRCHECK(surface.UnlockRect());

      { save snapshot to file using WIC, using a temporary file name first }
      var tmp_name := Tpath.GetTempFileName('png',false,image_folder);
      if WICSavePixelsToPng(wr,pitch,shot,tmp_name) = S_OK then
      begin
        result := true;
        { rename temp file name to new name if it doesn't exist already }
        var new_name := Tpath.ExtractDirectory(tmp_name) + THashSHA1.GetHashStringFromFile(tmp_name) + '.png';
        if not TPath.FileExists(new_name) then
        begin
          if Tfile.Rename(tmp_name,new_name) then
          begin
            cs.file_path := '';
          end else begin
            cs.file_path := new_name;
          end;
        end else begin
          cs.file_path := new_name;
        end;
      end;
      Tfile.Delete(tmp_name);
    finally
      FreeMem(shot);
    end;
    except
      result := false;
  end;
end;

The limitation that I have with the D3D method is that in reality I don't take a snapshot of a specific window but I take a snapshot of the entire screen that I crop after to take only the window of my interest.
For that, I must bring first the target window to front, but in some case this may not be possible. For instance if the target form is behind a modal form, it might be partially or totally hidden, as one can see below

So, my question : Is it possible to take a snapshot / print a single Firemonkey 2D form from another process, even if the form is not modal / partially covered by another form.


问:
Can't see the address when nginx processes the port and outputs 502 Bad Gateway
I encountered a problem when learning nginx. I have 2 servers on 2 different ports. I want a page with information stored on port 8000 to be returned when accessing "http://localhost/api/v1/clients/". Now I get error 502 Bad Gateway. В консоли: connect() failed (111: Connection refused) while connecting to upstream, client: 111.11.0.1, server: localhost, request: "GET /api/v1/clients/ HTTP/1.1", upstream: "http://111.11.0.2:80/api/v1/clients/", host: "localhost" If I go to the address: "http://localhost:8000/api/v1/clients/", everything is fine. What's my mistake?

nginx:

```<code>upstream backend {
    server 127.0.0.1:8000;
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name localhost;

    location /api/v1/clients/ {
        proxy_pass http://backend_client/api/v1/clients/;
    }
}
</code>```

docker:

```<code>services:
  backend_client:
    build: ./Client
    volumes:
      - ./Client/:/app
    ports:
      - "8000:8000"
    restart: always
    command:
      "gunicorn --bind=0.0.0.0:8000 django_app.wsgi"
  nginx:
    image: nginx:1.17
    container_name: ngx
    ports:
      - "80:80"
    volumes:
      - ./nginx:/etc/nginx/conf.d
    depends_on:
      - backend_client
</code>```

答:
Change your NGINX Configuration. Make sure you are reading some basic information about

NGINX config upstreams

NGINX config reverse proxy

Your backend will be available as backend_client in your nginx container. The upstream is backend. Your app is still listing on port 8000 and this information is important. So tell NGINX about it :).

upstream backend {
    server backend_client:8000;
}

server {
    listen 80;

    location /api/v1/clients/ {
        proxy_pass http://backend/;
    }
}

```

Body:
I encountered a problem when learning nginx. I have 2 servers on 2 different ports. I want a page with information stored on port 8000 to be returned when accessing "http://localhost/api/v1/clients/". Now I get error 502 Bad Gateway. В консоли: connect() failed (111: Connection refused) while connecting to upstream, client: 111.11.0.1, server: localhost, request: "GET /api/v1/clients/ HTTP/1.1", upstream: "http://111.11.0.2:80/api/v1/clients/", host: "localhost" If I go to the address: "http://localhost:8000/api/v1/clients/", everything is fine. What's my mistake?

nginx:

upstream backend {
    server 127.0.0.1:8000;
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name localhost;

    location /api/v1/clients/ {
        proxy_pass http://backend_client/api/v1/clients/;
    }
}

docker:

services:
  backend_client:
    build: ./Client
    volumes:
      - ./Client/:/app
    ports:
      - "8000:8000"
    restart: always
    command:
      "gunicorn --bind=0.0.0.0:8000 django_app.wsgi"
  nginx:
    image: nginx:1.17
    container_name: ngx
    ports:
      - "80:80"
    volumes:
      - ./nginx:/etc/nginx/conf.d
    depends_on:
      - backend_client


问:
Lock screen on Linux-based screens
Is there a lock screen on Linux-based systems?

When the screen is locked, the user should enter a PIN code to enter back. Like the PIN screen lock on an iPhone.

答:
Gnome Desktop:

```<code>gnome-screensaver-command -l
</code>```

What this actually does (source code) is call a DBUS Api that aims to be desktop-neutral. Read more about that on this page

Title: Lock screen on Linux-based screens

Body:
Gnome Desktop:

gnome-screensaver-command -l

What this actually does (source code) is call a DBUS Api that aims to be desktop-neutral. Read more about that on this page

ContentLicense: CC BY-SA 3.0


问:
writeBuffer of ExcelJS doesn't return Buffer type
I'm using exceljs with Typescript in my project. But writeBuffer() function returns ExcelJS.Buffer instead of Buffer type. And since ExcelJS.Buffer inherits from ArrayBuffer, converting ArrayBuffer to Buffer will break excel file. Does anyone have a solution to this problem?
Thanks in advance!

declare interface Buffer extends ArrayBuffer { }
```

<pre class="lang-js prettyprint-override"><code>let resultExcel: Buffer; // buffer
const tmpResultExcel: ExcelJS.Buffer = await tmpWorkBook.xlsx.writeBuffer(); // arraybuffer
resultExcel = Buffer.from(tmpResultExcel); // doesn't work well
</code>```

答:
I came across this one too and this is 2022 with exceljs' latest version (4.3.0 at time of writing).

As @Frédéric Lang stated it is indeed a typing problem. Moreover even though inspecting the provided types did not lead to a clear solution, as the workbook.xlsx.writeBuffer() function's signature tells us it returns a plain Buffer.

Instead of converting the dodgy exceljs.Buffer instance to any, you may just want to "cast" it to a proper Buffer after an await.

```<code>private async writeXlsxBuffer(data: BillingSummaryFileLine[]): Promise<Buffer> {
        const workbook = new exceljs.Workbook();
        await workbook.xlsx.readFile("my_model.xlsx");
        ...
        return await workbook.xlsx.writeBuffer() as Buffer;
    }
</code>```

You will have to make sure this is actually a Buffer though, as using the as keyword Typescript will assume you know what you are doing casting one object to another type.

Body:
I'm using exceljs with Typescript in my project. But writeBuffer() function returns ExcelJS.Buffer instead of Buffer type. And since ExcelJS.Buffer inherits from ArrayBuffer, converting ArrayBuffer to Buffer will break excel file. Does anyone have a solution to this problem?
Thanks in advance!

declare interface Buffer extends ArrayBuffer { }

let resultExcel: Buffer; // buffer
const tmpResultExcel: ExcelJS.Buffer = await tmpWorkBook.xlsx.writeBuffer(); // arraybuffer
resultExcel = Buffer.from(tmpResultExcel); // doesn't work well

Body:
I came across this one too and this is 2022 with exceljs' latest version (4.3.0 at time of writing).

As @Frédéric Lang stated it is indeed a typing problem. Moreover even though inspecting the provided types did not lead to a clear solution, as the workbook.xlsx.writeBuffer() function's signature tells us it returns a plain Buffer.

Instead of converting the dodgy exceljs.Buffer instance to any, you may just want to "cast" it to a proper Buffer after an await.

private async writeXlsxBuffer(data: BillingSummaryFileLine[]): Promise<Buffer> {
        const workbook = new exceljs.Workbook();
        await workbook.xlsx.readFile("my_model.xlsx");
        ...
        return await workbook.xlsx.writeBuffer() as Buffer;
    }

You will have to make sure this is actually a Buffer though, as using the as keyword Typescript will assume you know what you are doing casting one object to another type.


问:
Tkinter Python Execution Issue
I am trying to execute code using tkinter GUI. I am not able to execute output. However, When I try only subprocess method it works fine. Can you please let me know what is wrong here.

```<code>from tkinter import *
import subprocess

main_window = Tk()
Label(main_window, text="Name of Test").grid(row =0,column=0)
test = Entry(main_window, width=50, borderwidth=5).grid(row=0,column=1)
Def on_click():
    If test == "abc": subprocess.run(['python',r'C:\User\abc.py'], stdout=subprocess.PIPE)
Button(main_window, text='Run', command = on_click).grid(row=2, column=1)
main_window.mainloop()
</code>```

Also, how to exit GUI window once process is complete?

Thanks

答:
My guessing on what you were trying to achieve

from tkinter import *
import subprocess

main_window = Tk()
Label(main_window, text="Name of Test").grid(row=0, column=0)
entry = Entry(main_window, width=50, borderwidth=5)
entry.grid(row=0, column=1)

def on_click():
    entry_text_content = entry.get()

    if entry_text_content == "abc":
        subprocess.run(
            ['python',r'C:\User\abc.py'],
            stdout=subprocess.PIPE,
        )

Button(main_window, text='Run', command = on_click).grid(row=2, column=1)

main_window.mainloop()
```

Please pay attention to the comparison of the input: I'm not comparing entry with "abc", but I'm calling entry.get() at first to retrieve text from the entry, and then compare this text with "abc".

Title: Tkinter Python Execution Issue

Body:
I am trying to execute code using tkinter GUI. I am not able to execute output. However, When I try only subprocess method it works fine. Can you please let me know what is wrong here.

from tkinter import *
import subprocess

main_window = Tk()
Label(main_window, text="Name of Test").grid(row =0,column=0)
test = Entry(main_window, width=50, borderwidth=5).grid(row=0,column=1)
Def on_click():
    If test == "abc": subprocess.run(['python',r'C:\User\abc.py'], stdout=subprocess.PIPE)
Button(main_window, text='Run', command = on_click).grid(row=2, column=1)
main_window.mainloop()

Also, how to exit GUI window once process is complete?

Thanks

Body:
My guessing on what you were trying to achieve

from tkinter import *
import subprocess

main_window = Tk()
Label(main_window, text="Name of Test").grid(row=0, column=0)
entry = Entry(main_window, width=50, borderwidth=5)
entry.grid(row=0, column=1)

def on_click():
    entry_text_content = entry.get()

    if entry_text_content == "abc":
        subprocess.run(
            ['python',r'C:\User\abc.py'],
            stdout=subprocess.PIPE,
        )

Button(main_window, text='Run', command = on_click).grid(row=2, column=1)

main_window.mainloop()

Please pay attention to the comparison of the input: I'm not comparing entry with "abc", but I'm calling entry.get() at first to retrieve text from the entry, and then compare this text with "abc".


问:
Increase the number of partitions without repartition on Hadoop
I have a directory containing a bunch of deflate compressed CSV files that are around 500mb. I would like to split them into smaller deflate compressed CSV files. For example I have 3 500mb files and I would like them to become 15 100mb files after the write. I am currently doing something like this:

```<code>spark.read.csv("/input/path")
  .repartition(15)
  .write.option("compression", "deflate").csv("output/path")
</code>```

But this causes a whole unnecessary shuffle. Is there a way to get it to write 15 files without going through all this trouble?

答:
In short no.  There is an open feature request for this.  Spark uses spark internals and creating partitions is done via shuffle.  If you really want to split this file without shuffling uses some code that isn't spark to do it.  But really not worth the time.

Off topic but still valuable feedback -> @OneCricketeer is correct, you should consider a different file format that is more performant.(Parquet/Orc) It will vastly improve performance as the size of data increases and should be your first thought when it comes to file formats.

Body:
I have a directory containing a bunch of deflate compressed CSV files that are around 500mb. I would like to split them into smaller deflate compressed CSV files. For example I have 3 500mb files and I would like them to become 15 100mb files after the write. I am currently doing something like this:

spark.read.csv("/input/path")
  .repartition(15)
  .write.option("compression", "deflate").csv("output/path")

But this causes a whole unnecessary shuffle. Is there a way to get it to write 15 files without going through all this trouble?


问:
How to launch a function from a module so that it takes effect in the main program?
An example of what I want to get:

Main program:

```<code>from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():

    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=module.moduleFunction)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

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

Module:

```<code>from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction():

    child_window = Toplevel()

    def resetCanvasFromModule():

        # THE QUESTION!
        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)
</code>```

Obviously this doesn't work, since resetCanvas() isn't defined inside the module, but if I define it, it will try to destroy canvas, which isn't defined in the module, so it won't work either.

So, what would I have to do to get the effect I want?

P.S.: I have tried with 'global', without success.

答:
Thanks for your help guys.

Passing resetCanvas() as a parameter to moduleFunction(), and a lambda as button1 command, works fine.

This is my working example code(maybe in the future it can be useful to a newbie like me):

Main code:

```<code>from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)
    return
    canvas

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=lambda:[module.moduleFunction(resetCanvas)])
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

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

Module:

```<code>from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction(resetCanvas):

    child_window = Toplevel()

    def resetCanvasFromModule():

        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)
</code>```

Thanks a lot.

Body:
An example of what I want to get:

Main program:

from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():

    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=module.moduleFunction)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()

Module:

from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction():

    child_window = Toplevel()

    def resetCanvasFromModule():

        # THE QUESTION!
        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)

Obviously this doesn't work, since resetCanvas() isn't defined inside the module, but if I define it, it will try to destroy canvas, which isn't defined in the module, so it won't work either.

So, what would I have to do to get the effect I want?

P.S.: I have tried with 'global', without success.

Body:
Thanks for your help guys.

Passing resetCanvas() as a parameter to moduleFunction(), and a lambda as button1 command, works fine.

This is my working example code(maybe in the future it can be useful to a newbie like me):

Main code:

from tkinter import *
import tkinter  as tk
import module

main_window = Tk()

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)
    return
    canvas

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=lambda:[module.moduleFunction(resetCanvas)])
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()

Module:

from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction(resetCanvas):

    child_window = Toplevel()

    def resetCanvasFromModule():

        resetCanvas()

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)

Thanks a lot.


问:
Generic Type inference has a strange behavior
I hope someone can explain me a strange behavior from the C# type inference system, when attempting to "partially apply" functions.

Assume I have following code:

int Add(int a, int b) => a + b;
```
<p>Why can the inference system not infer the type of X if I declare it like following:</p>
<pre class="lang-cs prettyprint-override"><code>var add1 = (x) => Add(1, x); // does not work: CS8917: The delegate type could not be inferred.
var add1 = (int x) => Add(1, x); // does work

var add_1 = PartiallyApply(Add, 1);

Func<T1, T2, TResult> PartiallyApply<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 param) {
  return (p2) => func(param, p2);
}
</code>```

The second version makes sense, if the inference system runs from top to bottom, so you have to declare everything before you use it.
The type inference system of F# goes the other way around, and checks the usage of the function to infer the used types.

I would really appreciate some ideas and if I can overcome this issue somehow using !inline! declarations.
I know there are other ways to overcome this issue, by using explicit typing but that's not the route I want to take.

Thanks in adavance everyone

答: You must explicitly give the type of X , for this function to work properly !</p>

Body:
I hope someone can explain me a strange behavior from the C# type inference system, when attempting to "partially apply" functions.

Assume I have following code:

int Add(int a, int b) => a + b;

Why can the inference system not infer the type of X if I declare it like following:

var add1 = (x) => Add(1, x); // does not work: CS8917: The delegate type could not be inferred.
var add1 = (int x) => Add(1, x); // does work

var add_1 = PartiallyApply(Add, 1);

Func<T1, T2, TResult> PartiallyApply<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 param) {
  return (p2) => func(param, p2);
}

The second version makes sense, if the inference system runs from top to bottom, so you have to declare everything before you use it.
The type inference system of F# goes the other way around, and checks the usage of the function to infer the used types.

I would really appreciate some ideas and if I can overcome this issue somehow using !inline! declarations.
I know there are other ways to overcome this issue, by using explicit typing but that's not the route I want to take.

Thanks in adavance everyone


问:
Supervisord "exit status 1 not expected" running php script
I'm having issue try to configure supervisor to run a php script. Running supervisor in debug mode gives me this:

```<code>2015-03-09 08:53:06,342 INFO supervisord started with pid 2030
2015-03-09 08:53:06,358 INFO spawned: 'worker1' with pid 2031
2015-03-09 08:53:06,423 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:06,424 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:07,440 INFO spawned: 'worker1' with pid 2032
2015-03-09 08:53:07,587 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:07,589 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:09,604 INFO spawned: 'worker1' with pid 2033
2015-03-09 08:53:09,756 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:09,758 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:12,775 INFO spawned: 'worker1' with pid 2034
2015-03-09 08:53:12,973 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:12,974 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:13,976 INFO gave up: worker1 entered FATAL state, too many start retries too quickly
</code>```

The supervisord configuration:

```<code>[program:worker1]
command=php myScript.php
directory=/home/path/to/script/
user=root
autostart=true
autorestart=true
stderr_logfile=/var/log/worker1.err.log
stdout_logfile=/var/log/worker1.out.log
redirect_stderr=true
environment=PATH="/usr/bin"
</code>```

For this test myScript.php just print out echo "test".PHP_EOL;

There are no logs reporting errors from php, and if I run the script thru cli it works as expected. The supervisord log just report the same output as debuggin.

I've also tried using absolute paths like /usr/bin/php /home/path/to/script/myScript.php but nothing changes.

File permission for myScript.php are set to -rwxrwxr-x 1 root apache

Really don't know what else i could check. Thanks for support!

UPDATE_1

I've also tried to monitor other program like /bin/cat or a bash script and works like a charm. The problem seems to be limited to php.

UPDATE_2

As N.B. pointed out in the comments i've changed the test script to look more like long-running-job:

```<code>while(true){
    echo "test".PHP_EOL;
    sleep(10);
}
</code>```

Same as before, it enters in FATAL state.

答: If you run supervisor command like docker -it exec ... and got exit status 1; not expected you should try to remove -it. More here https://stackoverflow.com/a/43099210/3664772

Body:
I'm having issue try to configure supervisor to run a php script. Running supervisor in debug mode gives me this:

2015-03-09 08:53:06,342 INFO supervisord started with pid 2030
2015-03-09 08:53:06,358 INFO spawned: 'worker1' with pid 2031
2015-03-09 08:53:06,423 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:06,424 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:07,440 INFO spawned: 'worker1' with pid 2032
2015-03-09 08:53:07,587 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:07,589 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:09,604 INFO spawned: 'worker1' with pid 2033
2015-03-09 08:53:09,756 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:09,758 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:12,775 INFO spawned: 'worker1' with pid 2034
2015-03-09 08:53:12,973 INFO exited: worker1 (exit status 1; not expected)
2015-03-09 08:53:12,974 INFO received SIGCLD indicating a child quit
2015-03-09 08:53:13,976 INFO gave up: worker1 entered FATAL state, too many start retries too quickly

The supervisord configuration:

[program:worker1]
command=php myScript.php
directory=/home/path/to/script/
user=root
autostart=true
autorestart=true
stderr_logfile=/var/log/worker1.err.log
stdout_logfile=/var/log/worker1.out.log
redirect_stderr=true
environment=PATH="/usr/bin"

For this test myScript.php just print out echo "test".PHP_EOL;

There are no logs reporting errors from php, and if I run the script thru cli it works as expected. The supervisord log just report the same output as debuggin.

I've also tried using absolute paths like /usr/bin/php /home/path/to/script/myScript.php but nothing changes.

File permission for myScript.php are set to -rwxrwxr-x 1 root apache

Really don't know what else i could check. Thanks for support!

UPDATE_1

I've also tried to monitor other program like /bin/cat or a bash script and works like a charm. The problem seems to be limited to php.

UPDATE_2

As N.B. pointed out in the comments i've changed the test script to look more like long-running-job:

while(true){
    echo "test".PHP_EOL;
    sleep(10);
}

Same as before, it enters in FATAL state.


问:
Python: Installing and using Exscript module Windows x86
I have been banging my head against the wall trying to get Exscript installed. After multiple failed attempts at doing it manually, I installed ActivePython and had success running "pypm install Exscript" from the cmd prompt.

I am now going through the Exscript documentation (found here https://github.com/knipknap/exscript/wiki/Python-API-Tutorial) and if I run the first example script I get an error:

```<code>>>> from Exscript.util.interact import read_login

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    from Exscript.util.interact import read_login
ImportError: No module named interact
</code>```

So, I understand that this is saying that there is no module interact. How can I check this? Is there a way I can manually add this module? I would love to know WHY this module didnt come with the package, but that may be impossible to answer :)

Any and all help is greatly appreciated. Thank you

EDIT -

import Exscript.util works but if I try import Exscript.util.Interact I get the error. When I look in util.py I see an entry that says  "from FooLib import Interact". I first thought it may just be a capitalization error (Exscript.util.interact vs util.Interact) but neither of those work. I am not sure where to go from here... :(

EDIT -

I have posted this question on the developers forums, hopefully he will have an answer for us. https://github.com/knipknap/exscript/issues/15

EDIT -

The developer suggested that I was using an old version and told me to download the latest. I had struggled installing the module manually so I googled how to easily install py modules. I found a writeup on easy_install.exe. I ran "c:\Python26>easy_install C:\Users\support\Desktop\lou\knipknap-exscript-v2.1-70-gf5583f3.tar.gz" from the cmd prompt, the module was installed (no errors) and now when i run the script it works.

Next challenge will be how to get these scripts to run as stand-alone exe's on users computers without Python installed :)

THANK YOU to everyone to commented I truely appreciate your help.

Lou

答: One common way packages are installed is as directories.  So check your site-packages directory for an Exscript directory, and inside that there should be a util directory, and inside that there should be an interact.py file.  Look for similar spellings in case the tutorial misspelled something.

Body:
I have been banging my head against the wall trying to get Exscript installed. After multiple failed attempts at doing it manually, I installed ActivePython and had success running "pypm install Exscript" from the cmd prompt.

I am now going through the Exscript documentation (found here https://github.com/knipknap/exscript/wiki/Python-API-Tutorial) and if I run the first example script I get an error:

>>> from Exscript.util.interact import read_login

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    from Exscript.util.interact import read_login
ImportError: No module named interact

So, I understand that this is saying that there is no module interact. How can I check this? Is there a way I can manually add this module? I would love to know WHY this module didnt come with the package, but that may be impossible to answer :)

Any and all help is greatly appreciated. Thank you

EDIT -

import Exscript.util works but if I try import Exscript.util.Interact I get the error. When I look in util.py I see an entry that says  "from FooLib import Interact". I first thought it may just be a capitalization error (Exscript.util.interact vs util.Interact) but neither of those work. I am not sure where to go from here... :(

EDIT -

I have posted this question on the developers forums, hopefully he will have an answer for us. https://github.com/knipknap/exscript/issues/15

EDIT -

The developer suggested that I was using an old version and told me to download the latest. I had struggled installing the module manually so I googled how to easily install py modules. I found a writeup on easy_install.exe. I ran "c:\Python26>easy_install C:\Users\support\Desktop\lou\knipknap-exscript-v2.1-70-gf5583f3.tar.gz" from the cmd prompt, the module was installed (no errors) and now when i run the script it works.

Next challenge will be how to get these scripts to run as stand-alone exe's on users computers without Python installed :)

THANK YOU to everyone to commented I truely appreciate your help.

Lou


问:
Debezium source to Postgres sink DB- JDBC Sink connector issue
Getting below error with JDBC sync connector.

```<code> ERROR WorkerSinkTask{id=12sink-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted. Error: Cannot ALTER TABLE "new1501"."test"."patient3" to add missing field SinkRecordField{schema=Schema{io.debezium.connector.postgresql.Source:STRUCT}, name='source', isPrimaryKey=false}, as the field is not optional and does not have a default value (org.apache.kafka.connect.runtime.WorkerSinkTask)
org.apache.kafka.connect.errors.ConnectException: Cannot ALTER TABLE "new1501"."test"."patient3" to add missing field SinkRecordField{schema=Schema{io.debezium.connector.postgresql.Source:STRUCT}, name='source', isPrimaryKey=false}, as the field is not optional and does not have a default value
    at io.confluent.connect.jdbc.sink.DbStructure.amendIfNecessary(DbStructure.java:153)
    at io.confluent.connect.jdbc.sink.DbStructure.createOrAmendIfNecessary(DbStructure.java:75)
    at io.confluent.connect.jdbc.sink.BufferedRecords.add(BufferedRecords.java:123)
    at io.confluent.connect.jdbc.sink.JdbcDbWriter.write(JdbcDbWriter.java:66)
    at io.confluent.connect.jdbc.sink.JdbcSinkTask.put(JdbcSinkTask.java:74)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:601)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:333)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:234)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:203)
    at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:188)
    at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:243)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

My source connector config:

```<code>{
    "name": "150-connector-2",
    "config": {
        "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
        "tasks.max": "1",
        "plugin.name": "pgoutput",
        "database.hostname": "**",
        "database.port": "5432",
        "database.user": "postgres",
        "database.password": "***",
        "database.dbname": "kafka-source-test",
        "database.server.name": "new1501",
        "key.converter": "org.apache.kafka.connect.json.JsonConverter",
        "value.converter": "org.apache.kafka.connect.json.JsonConverter",
        "key.converter.schemas.enable": "true",
        "value.converter.schemas.enable": "true",
        "snapshot.mode": "always"
    }
}

</code>```

My sink connector config:

```<code>{
    "name": "12sink",
    "config": {
        "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
        "tasks.max": "1",
        "topics": "new1501.test.patient3",
        "connection.url": "jdbc:postgresql://<ip>:5432/db",
        "connection.user":"postgres",
    "connection.password":"**",
        "auto-evolve":"true" ,
        "auto-create":"true" ,
        "insert.mode": "insert",
        "delete.enabled": "true",
        "pk.fields": "home_id",
        "pk.mode": "record_key",
        "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "key.converter.schemas.enable":"true",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable":"true"

        }
}
</code>```

答:
As the error says, your sink table cannot add a "source" field, because there's no default schema value for it (nor should there be a default).

If you consume the source topic, you'll notice it likely doesn't match the columns of your database exactly (you'll want to create the table ahead of time). This is because you need to first extract the after state using a transform. https://debezium.io/documentation/reference/stable/transformations/event-flattening.html

Body:
Getting below error with JDBC sync connector.

 ERROR WorkerSinkTask{id=12sink-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted. Error: Cannot ALTER TABLE "new1501"."test"."patient3" to add missing field SinkRecordField{schema=Schema{io.debezium.connector.postgresql.Source:STRUCT}, name='source', isPrimaryKey=false}, as the field is not optional and does not have a default value (org.apache.kafka.connect.runtime.WorkerSinkTask)
org.apache.kafka.connect.errors.ConnectException: Cannot ALTER TABLE "new1501"."test"."patient3" to add missing field SinkRecordField{schema=Schema{io.debezium.connector.postgresql.Source:STRUCT}, name='source', isPrimaryKey=false}, as the field is not optional and does not have a default value
    at io.confluent.connect.jdbc.sink.DbStructure.amendIfNecessary(DbStructure.java:153)
    at io.confluent.connect.jdbc.sink.DbStructure.createOrAmendIfNecessary(DbStructure.java:75)
    at io.confluent.connect.jdbc.sink.BufferedRecords.add(BufferedRecords.java:123)
    at io.confluent.connect.jdbc.sink.JdbcDbWriter.write(JdbcDbWriter.java:66)
    at io.confluent.connect.jdbc.sink.JdbcSinkTask.put(JdbcSinkTask.java:74)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:601)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:333)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:234)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:203)
    at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:188)
    at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:243)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

My source connector config:

{
    "name": "150-connector-2",
    "config": {
        "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
        "tasks.max": "1",
        "plugin.name": "pgoutput",
        "database.hostname": "**",
        "database.port": "5432",
        "database.user": "postgres",
        "database.password": "***",
        "database.dbname": "kafka-source-test",
        "database.server.name": "new1501",
        "key.converter": "org.apache.kafka.connect.json.JsonConverter",
        "value.converter": "org.apache.kafka.connect.json.JsonConverter",
        "key.converter.schemas.enable": "true",
        "value.converter.schemas.enable": "true",
        "snapshot.mode": "always"
    }
}

My sink connector config:

{
    "name": "12sink",
    "config": {
        "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
        "tasks.max": "1",
        "topics": "new1501.test.patient3",
        "connection.url": "jdbc:postgresql://<ip>:5432/db",
        "connection.user":"postgres",
    "connection.password":"**",
        "auto-evolve":"true" ,
        "auto-create":"true" ,
        "insert.mode": "insert",
        "delete.enabled": "true",
        "pk.fields": "home_id",
        "pk.mode": "record_key",
        "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "key.converter.schemas.enable":"true",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable":"true"

        }
}


问:
ggplot not respectig order of colours in scale_fill_manual()?
I am creating some violin plots and want to colour them. It works for a matrix of dimension 9, as in my previous question

ggplot violin plot, specify different colours by group?

but when I increase the dimension to 15, the order of the colours are not respected. Why is this happening?

Here it works (9 columns):

```<code>library(ggplot2)
dat <- matrix(rnorm(250*9),ncol=9)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:9,250)))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) +
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),3))
pp
</code>```

Here it does not work (15 columns):

```<code>library(ggplot2)
dat <- matrix(rnorm(250*15),ncol=15)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:15,250)))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) +
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),5))
pp
</code>```

答:
You can also name the color vector. For example:</p>
```<code>my_values <- rep(c("red","green","blue"),5)
names(my_values) <- rep(c("Data1","Data2","Data3"),5)

... +
  scale_fill_manual(values=my_values)
</code>```

Body:
I am creating some violin plots and want to colour them. It works for a matrix of dimension 9, as in my previous question

ggplot violin plot, specify different colours by group?

but when I increase the dimension to 15, the order of the colours are not respected. Why is this happening?

Here it works (9 columns):

library(ggplot2)
dat <- matrix(rnorm(250*9),ncol=9)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:9,250)))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) +
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),3))
pp

Here it does not work (15 columns):

library(ggplot2)
dat <- matrix(rnorm(250*15),ncol=15)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- as.character(sort(rep(1:15,250)))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) +
  geom_violin(scale="width",adjust = 1,width = 0.5)  + scale_fill_manual(values=rep(c("red","green","blue"),5))
pp

Body:
You can also name the color vector. For example:

my_values <- rep(c("red","green","blue"),5)
names(my_values) <- rep(c("Data1","Data2","Data3"),5)

... +
  scale_fill_manual(values=my_values)


问:
pop up delete sweetalert2
i am trying to do pop up delete action with sweetalert2 in asp.net core project

it seems delete befor the pop up it self

but not working

JS:

```<code>jQueryAjaxDelete = form => {
    swal({
        title: "Are you sure to delete this  of ?",
        text: "Delete Confirmation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete",
        closeOnConfirm: false
    }, function () {
        $.ajax({
            type: 'POST',
            url: form.action,
            data: new FormData(form),
            contentType: false,
            processData: false,
            success: function (res) {
                $('#view-all').html(res.html);
            },
            error: function (err) {
                console.log(err)
            }
       })
  }  )
};
</code>```

in view

```<code>     <form asp-action="Delete" asp-route-id="@item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
                                                <input type="hidden" asp-for="@item.Id" />
                                                <input type="submit" value="Supprimer" class="btn btn-danger" />
 </form>

</code>```

答:
You need to handle the result from a promise, like this:</p>
```<code>jQueryAjaxDelete = form => {
    swal({
        title: "Are you sure to delete this  of ?",
        text: "Delete Confirmation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete",
        closeOnConfirm: false
    }).then(value) => {
        // also be aware you need to check the "value" variable
        // to see if the user answered YES
        $.ajax({
            type: 'POST',
            url: form.action,
            data: new FormData(form),
            contentType: false,
            processData: false,
            success: function (res) {
                $('#view-all').html(res.html);
            },
            error: function (err) {
                console.log(err)
            }
       });
  };
</code>```

Title: pop up delete sweetalert2

Body:
i am trying to do pop up delete action with sweetalert2 in asp.net core project

it seems delete befor the pop up it self

but not working

JS:

jQueryAjaxDelete = form => {
    swal({
        title: "Are you sure to delete this  of ?",
        text: "Delete Confirmation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete",
        closeOnConfirm: false
    }, function () {
        $.ajax({
            type: 'POST',
            url: form.action,
            data: new FormData(form),
            contentType: false,
            processData: false,
            success: function (res) {
                $('#view-all').html(res.html);
            },
            error: function (err) {
                console.log(err)
            }
       })
  }  )
};

in view

     <form asp-action="Delete" asp-route-id="@item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
                                                <input type="hidden" asp-for="@item.Id" />
                                                <input type="submit" value="Supprimer" class="btn btn-danger" />
 </form>

Body:
You need to handle the result from a promise, like this:

jQueryAjaxDelete = form => {
    swal({
        title: "Are you sure to delete this  of ?",
        text: "Delete Confirmation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete",
        closeOnConfirm: false
    }).then(value) => {
        // also be aware you need to check the "value" variable
        // to see if the user answered YES
        $.ajax({
            type: 'POST',
            url: form.action,
            data: new FormData(form),
            contentType: false,
            processData: false,
            success: function (res) {
                $('#view-all').html(res.html);
            },
            error: function (err) {
                console.log(err)
            }
       });
  };


问:
Django DetailView don't show data in template
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

```<code>class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
</code>```

urls.py:

```<code>  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]
</code>```

views.py:

```<code>class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'
</code>```

detail.html:

```<code>{% block content %}
    <h1>Site showing School Detail</h1>
    <div class="container">
        <div class="p-5 text-white bg-dark rounded-3 container">
            <p>Name: {{schooldetail.name}}</p>
            <p>Principal: {{schooldetail.principal}}</p>
            <p>Location: {{schooldetail.location}}</p>
            <h2>Student: </h2>
            {% for student in schooldetail.students.all %}
                <p>{{student.name}} who is {{student.age}} years old</p>
            {% endfor %}
        </div>
    </div>
{% endblock %}
</code>```

Thank you

答:
It's a typo. The code is not working because in the:

```<code>class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'
</code>```

I just missed a letter 't' in the context_object_name.

Body:
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

Here the code:

models.py:

class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

urls.py:

  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]

views.py:

class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'

detail.html:

{% block content %}

Site showing School Detail

Name: {{schooldetail.name}}

Principal: {{schooldetail.principal}}

Location: {{schooldetail.location}}

Student:

            {% for student in schooldetail.students.all %}

{{student.name}} who is {{student.age}} years old

            {% endfor %}

{% endblock %}

Thank you

Body:
It's a typo. The code is not working because in the:

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'

I just missed a letter 't' in the context_object_name.


问:
Accessing DDR memory address between (2GB-4Gb) through DSP DMA 64bit addressing
We are trying to access the DDR addresses of more than 2Gb to 4Gb through ShimDMA where it is more than 32 bits. Is DMA supports more than 32 bit addressing of physical memory ? We are using below api's for it OctSysDmaMemWrite, OctSysDmaMemRead.</p>

答: The hardware supports more than 32-bit. However, the DSP kernel APIs don't. We will try to add this to the next release (3.20).</p>


问:
Unable to resolve module ./list/ListItem from E:\socal project\social-app\node_modules\react-native-elements\dist\index.js:
I'm facing the error while using the react-native-elements (search bar)</p>

答:
Looking at your folder structure, it looks like you want to import ListItem from "./List".

You can learn more about the different types of imports on the React website: https://create-react-app.dev/docs/importing-a-component


问:
Padding between divider line and error text in TextInputLayout
How can I set the padding between the divider line and the error text (marked with the question mark in the image) in a TextInputLayout? I tried adding the padding in the style specified as  errorTextAppearance but it had no effect.

EDIT: Here's the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="test.textinputlayouttest.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        app:errorTextAppearance="@style/Error">

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter address"
            android:inputType="textEmailAddress"
            android:padding="26dp"/>
    </android.support.design.widget.TextInputLayout>

</android.support.constraint.ConstraintLayout>
</code>```

and the style:

```<code><style name="Error" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/red</item>
    <item name="android:paddingBottom">300dp</item>
</style>
</code>```

答:
Use android:layout_marginBottom="-10dp" in inner EditText

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/textInputLayout"
    style="@style/Widget.Design.TextInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    >
<com.google.android.material.textfield.TextInputEditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="-10dp"
    tools:text="Text"
    />
</com.google.android.material.textfield.TextInputLayout>
```

works for version: com.google.android.material:material:1.5.0

Body:
How can I set the padding between the divider line and the error text (marked with the question mark in the image) in a TextInputLayout? I tried adding the padding in the style specified as  errorTextAppearance but it had no effect.

EDIT: Here's the layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="test.textinputlayouttest.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        app:errorTextAppearance="@style/Error">

        <EditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter address"
            android:inputType="textEmailAddress"
            android:padding="26dp"/>
    </android.support.design.widget.TextInputLayout>

</android.support.constraint.ConstraintLayout>

and the style:

Body:
Use android:layout_marginBottom="-10dp" in inner EditText

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/textInputLayout"
    style="@style/Widget.Design.TextInputLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    >
<com.google.android.material.textfield.TextInputEditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="-10dp"
    tools:text="Text"
    />
</com.google.android.material.textfield.TextInputLayout>

works for version: com.google.android.material:material:1.5.0


问:
React render component only for few seconds
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

```<code>import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return <h2>found error</h2>;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;
</code>```

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

答:
Every time App renders, you create a brand new sampleData array. It may be an empty array each time, but it's a different empty array. Since it's different, the useEffect needs to rerun every time, which means that after every render, you set a timeout to go off in 1 second and show the component.

If this is just a mock array that will never change, then move it outside of App so it's only created once:

```<code>const sampleData = [];

function App() {
  // ...
}
</code>```

Or, you can turn it into a state value:

```<code>function App() {
  const [showComponent, setShowComponent] = useState(false);
  const [sampleData, setSampleData] = useState([]);
  // ...
}
</code>```

Body:
In my existing react component, I need to render another react component for a specific time period.
As soon as the parent component mounts/or data loads, the new-component (or child component) should be visible after 1-2 seconds and then after another few seconds, the new-component should be hidden. This needs to be done only if there is no data available.

This is what currently I've tried to achieve:

import React, { useState, useEffect } from "react";

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const sampleData = [];

  useEffect(() => {
    if (sampleData.length === 0) {
      setTimeout(() => {
        setShowComponent(true);
      }, 1000);
    }
  }, [sampleData]);

  useEffect(() => {
    setTimeout(() => {
      setShowComponent(false);
    }, 4000);
  }, []);

  const componentTwo = () => {
    return
found error
;
  };

  return <>First component mounted{showComponent && componentTwo()}</>;
}

export default App;

The current implementation is not working as expected. The new-component renders in a blink fashion.

Here is the working snippet attached:

Any help to resolve this is appreciated!

Body:
Every time App renders, you create a brand new sampleData array. It may be an empty array each time, but it's a different empty array. Since it's different, the useEffect needs to rerun every time, which means that after every render, you set a timeout to go off in 1 second and show the component.

If this is just a mock array that will never change, then move it outside of App so it's only created once:

const sampleData = [];

function App() {
  // ...
}

Or, you can turn it into a state value:

function App() {
  const [showComponent, setShowComponent] = useState(false);
  const [sampleData, setSampleData] = useState([]);
  // ...
}


问:
Module not found: Can't resolve '@mui/lab/AdapterDateFns'
I was using the Material UI Timepicker but after updating to Material UI 5 it is not working anymore. I updated everything to @next and @material-ui/core (version 5.0.0-beta.5) and @material-ui/lab (version: 5.0.0-alpha.44).

答:
I had the same issue. What I did was installing date-fns as well

```<code>  npm i date-fns
</code>```

I then stopped the localhost server and restart it again with npm start (I was using react)

```<code>npm start
</code>```

Body:
I had the same issue. What I did was installing date-fns as well

  npm i date-fns

I then stopped the localhost server and restart it again with npm start (I was using react)

npm start


问:
Angular - Apollo: Client has not been defined yet
I'm using apollo client for graphql. I set up the client in AppApolloModule that I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule. Although the service runs before the AppApolloModule runs and hence apollo is not initialized when the query is made and I get this error

```<code>Error: Client has not been defined yet
</code>```

AppApolloModule

```<code>imports ....

export class AppApolloModule {

    constructor(
        apollo: Apollo,
        httpLink: HttpLink,
        private userService: UserService
    ) {
        console.log("apollo module")
        apollo.create({
            link: httpLink.create({ uri: `${environment.apiBase}/graphql?${this.myService.token}`}),
            cache: new InMemoryCache()
        })
    }

}
</code>```

App Module

```<code>import { AppApolloModule } from './app.apollo.module';
import { MyService } from './services/my.service';

export class AppModule {
      constructor() {
        console.log("app module")
      }
}
</code>```

I don't get the two consoles app module and apollo module, since the service runs first, it doesn't find any initialized apollo app and thus breaks the code.

How can I make apollo run before the service or any services for that matter in an efficient and standard way?

答: What worked for me was deleting the .angular folder and serving the application again.

Body:
I'm using apollo client for graphql. I set up the client in AppApolloModule that I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule. Although the service runs before the AppApolloModule runs and hence apollo is not initialized when the query is made and I get this error

Error: Client has not been defined yet

AppApolloModule

imports ....

export class AppApolloModule {

    constructor(
        apollo: Apollo,
        httpLink: HttpLink,
        private userService: UserService
    ) {
        console.log("apollo module")
        apollo.create({
            link: httpLink.create({ uri: `${environment.apiBase}/graphql?${this.myService.token}`}),
            cache: new InMemoryCache()
        })
    }

}

App Module

import { AppApolloModule } from './app.apollo.module';
import { MyService } from './services/my.service';

export class AppModule {
      constructor() {
        console.log("app module")
      }
}

I don't get the two consoles app module and apollo module, since the service runs first, it doesn't find any initialized apollo app and thus breaks the code.

How can I make apollo run before the service or any services for that matter in an efficient and standard way?