问:
webworker and module import from fast-png does not work
I need 16 bit greyscale images because of the detail accuracy for depth information. I use fast-png and am very happy with it. After the import, I only have to use the decode command to get the image information. What confuses me now is that when I import fast-png in the main program or anywhere else with this command

import {decode} from 'fast-png';

then that works. I can decode images and then read out the information. Now I would like to do this with a web worker and the import doesn't work there. I can call every module in the web worker with import but unfortunately not fast-png and I don't understand that. Does anyone understand?

```<code>//**********thread-manager-class*******************

import {decode} from 'fast-png';    // here it works but i don't need it here

export const texture_loader_threaded = (function() {

  class _TextureLoader_Threaded {
    constructor(params) {

      this.TextureLoaderWorker = new Worker('src/texture-loader-threaded-worker.js', {type: 'module'});
      this.TextureLoaderWorker.onmessage = (e) => {
        this.result = e.data;
      };
    }//end constructor

  }//end class

  return {
    TextureLoader_Threaded: _TextureLoader_Threaded
  }
})();

//****************texture-loader-threaded-worker.js**********************

//import { decode } from 'fast-png';
//But importing fast-png here causes the worker to stop working.
//I can import all other modules from the project here without any problems.
//But I don't need any of the other modules here, I need fast-png

async function imageLoader() {

    const arrayBuffer = await(await fetch('./resources/textures/png/native.png')).arrayBuffer();

    //const data = await decode(arrayBuffer);   //I need this to decode the arrayBuffer and get the data from the image

    postMessage(arrayBuffer);   //just a test, it works. But i don't need to return the arrayBuffer.
//I neet to return the decoded data array
//As soon as I import fast-png in the worker above, the return value of the postMessage becomes "undefined",
//even though I haven't changed anything else, just by importing fast-png

}

imageLoader();

</code>```

this is the link to fast-png.

https://github.com/image-js/fast-png

unfortunately there is no javascript module to import there, that is typescript. I installed fast-png with npm.

Body:
I need 16 bit greyscale images because of the detail accuracy for depth information. I use fast-png and am very happy with it. After the import, I only have to use the decode command to get the image information. What confuses me now is that when I import fast-png in the main program or anywhere else with this command

import {decode} from 'fast-png';

then that works. I can decode images and then read out the information. Now I would like to do this with a web worker and the import doesn't work there. I can call every module in the web worker with import but unfortunately not fast-png and I don't understand that. Does anyone understand?

//**********thread-manager-class*******************

import {decode} from 'fast-png';    // here it works but i don't need it here

export const texture_loader_threaded = (function() {

  class _TextureLoader_Threaded {
    constructor(params) {

      this.TextureLoaderWorker = new Worker('src/texture-loader-threaded-worker.js', {type: 'module'});
      this.TextureLoaderWorker.onmessage = (e) => {
        this.result = e.data;
      };
    }//end constructor

  }//end class

  return {
    TextureLoader_Threaded: _TextureLoader_Threaded
  }
})();

//****************texture-loader-threaded-worker.js**********************

//import { decode } from 'fast-png';
//But importing fast-png here causes the worker to stop working.
//I can import all other modules from the project here without any problems.
//But I don't need any of the other modules here, I need fast-png

async function imageLoader() {

    const arrayBuffer = await(await fetch('./resources/textures/png/native.png')).arrayBuffer();

    //const data = await decode(arrayBuffer);   //I need this to decode the arrayBuffer and get the data from the image

    postMessage(arrayBuffer);   //just a test, it works. But i don't need to return the arrayBuffer.
//I neet to return the decoded data array
//As soon as I import fast-png in the worker above, the return value of the postMessage becomes "undefined",
//even though I haven't changed anything else, just by importing fast-png

}

imageLoader();

this is the link to fast-png.

https://github.com/image-js/fast-png

unfortunately there is no javascript module to import there, that is typescript. I installed fast-png with npm.


来源: stackexchange

问:
Can't see folders that end with lib in Visual Studio cmake solution
I have a cmake project with some sub-folders. When I open it with VS 2019 I can see all the sub-folders except those which end with lib (e.g. MyProj_Lib). I could not find any way to control this filter.
Any idea?</p>

ContentLicense: CC BY-SA 4.0


问:
Anylogic - Parameter Variation Experiment - Varying Number of Replications - Distribution and Error percent
I am trying to use a parameter variation experiment to perform replications with a variable number based on the confidence interval. I have some problems understanding the calculation basis behind this feature and understanding the final number of replications that result here.

On which distribution is the calculation based (normal or t-distribution)? I couldn't find anything online regarding this question. Also, when I calculate the intervals manually (both with normal and t-distribution), I sometimes get a higher percentage error than specified. Can you tell me on which calculation basis the number of replications is determined? Is it possible that the "Error percent" value does not have to be given in percent?


问:
Neo4J: "Database in use: false" after loading dump + migrate
I'm running a Neo4J 5.3.0 community edition and tried to load the dump from https://github.com/neo4j-graph-examples/twitch. I managed to load the dump and migrate the database.

My question: how do I use the "twitch" database?

```<code>cosh@osmingestor:~$ sudo neo4j-admin database info
Database name:                neo4j
Database in use:              true
Last committed transaction id:-1
Store needs recovery:         true

Database name:                system
Database in use:              true
Last committed transaction id:-1
Store needs recovery:         true

Database name:                twitch
Database in use:              false
Store format version:         record-aligned-1.1
Store format introduced in:   5.0.0
Last committed transaction id:62742
Store needs recovery:         false

</code>```

show databases doesn't show it for my user "neo4j":

```<code>neo4j@neo4j> show databases;
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| name     | type       | aliases | access       | address          | role      | writer | requestedStatus | currentStatus | statusMessage | default | home  | constituents |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| "neo4j"  | "standard" | []      | "read-write" | "localhost:7687" | "primary" | TRUE   | "online"        | "online"      | ""            | TRUE    | TRUE  | []           |
| "system" | "system"   | []      | "read-write" | "localhost:7687" | "primary" | TRUE   | "online"        | "online"      | ""            | FALSE   | FALSE | []           |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

</code>```

I tried to grant access to the database by executing:

```<code>neo4j@neo4j> grant all database PRIVILEGES ON DATABASES * TO neo4j;
Unsupported administration command: grant all database PRIVILEGES ON DATABASES * TO neo4j
</code>```

Adding "neo4j" as the default admin did not help as well (was working though):

```<code>neo4j-admin dbms set-default-admin neo4j
</code>```

Body:
I'm running a Neo4J 5.3.0 community edition and tried to load the dump from https://github.com/neo4j-graph-examples/twitch. I managed to load the dump and migrate the database.

My question: how do I use the "twitch" database?

cosh@osmingestor:~$ sudo neo4j-admin database info
Database name:                neo4j
Database in use:              true
Last committed transaction id:-1
Store needs recovery:         true

Database name:                system
Database in use:              true
Last committed transaction id:-1
Store needs recovery:         true

Database name:                twitch
Database in use:              false
Store format version:         record-aligned-1.1
Store format introduced in:   5.0.0
Last committed transaction id:62742
Store needs recovery:         false

show databases doesn't show it for my user "neo4j":

neo4j@neo4j> show databases;
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| name     | type       | aliases | access       | address          | role      | writer | requestedStatus | currentStatus | statusMessage | default | home  | constituents |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| "neo4j"  | "standard" | []      | "read-write" | "localhost:7687" | "primary" | TRUE   | "online"        | "online"      | ""            | TRUE    | TRUE  | []           |
| "system" | "system"   | []      | "read-write" | "localhost:7687" | "primary" | TRUE   | "online"        | "online"      | ""            | FALSE   | FALSE | []           |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

I tried to grant access to the database by executing:

neo4j@neo4j> grant all database PRIVILEGES ON DATABASES * TO neo4j;
Unsupported administration command: grant all database PRIVILEGES ON DATABASES * TO neo4j

Adding "neo4j" as the default admin did not help as well (was working though):

neo4j-admin dbms set-default-admin neo4j


问:
I wanted to merge 2 pdf files into one pdf in reactjs, how should I proceed?
Merge 2 pdf files into 1 pdf

I tried to do it with 'jsPdf', but 2nd file is not getting added to the end of 1st file.

tried with 'pdf-actions' getting fileDoc.getPageIndices() is not a function.

for 'pdf-actions' I followed this: Merge created PDF with existing local PDF in ReactJS


问:
Can't sent nginx basic auth on server with Strapi
I want to setup nginx basic auth for my server that contains Strapi (we are using this server to query it with GraphQL for static content) to prevent unauthorised visitors while product is in development.

Strapi is located on port 1337, so I can access it via 127.0.0.1:1337 and see here starting page of Strapi that has button to redirect forward to the admin portal login (127.0.0.1:1337/admin that afterwards redirects to 127.0.0.1:1337/admin/auth/login).

If I'm adding basic auth in nginx (successfuly added it on other servers for the project), it works for the first page on root domain, but after going to /admin to the admin panel I spotted 2 different behaviours (depending on the browser)
Chrome constantly asks for basic auth on /admin and refreshes after every input, it's simply not letting me further
Safari bypasses the basic auth prompt, but when I try to login in /admin it just refreshes without any errors and not letting me further.

P.S. I'm not a DevOps guy, I'm project manager but currently our project is not having dedicated DevOps person to solve issues like that, so have to do everything by myself. Don't blame for dooing something wrong here :)

This is how I tried setting up nginx, all I did is generated the .httpasswd file with login and pass and added following code to the /etc/nginx/sites-available/default

```<code>        location / {

                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
                proxy_pass http://localhost:1337;
                proxy_http_version 1.1;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Server $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $http_host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
                proxy_pass_request_headers on;
                auth_basic "Login here!";
                auth_basic_user_file /etc/nginx/.htpasswd;
        }
</code>```

header parameters taken from here https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/deployment/optional-software/nginx-proxy.html#nginx-virtual-host

Also tried same configuration as works on other server that had NextJS app running under basic auth

```<code>        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;

                proxy_pass http://localhost:1337;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                auth_basic "Login here!";
                auth_basic_user_file /etc/nginx/.htpasswd;
        }
</code>```

Both now working, any ideas why?

Body:
I want to setup nginx basic auth for my server that contains Strapi (we are using this server to query it with GraphQL for static content) to prevent unauthorised visitors while product is in development.

Strapi is located on port 1337, so I can access it via 127.0.0.1:1337 and see here starting page of Strapi that has button to redirect forward to the admin portal login (127.0.0.1:1337/admin that afterwards redirects to 127.0.0.1:1337/admin/auth/login).

If I'm adding basic auth in nginx (successfuly added it on other servers for the project), it works for the first page on root domain, but after going to /admin to the admin panel I spotted 2 different behaviours (depending on the browser)
Chrome constantly asks for basic auth on /admin and refreshes after every input, it's simply not letting me further
Safari bypasses the basic auth prompt, but when I try to login in /admin it just refreshes without any errors and not letting me further.

P.S. I'm not a DevOps guy, I'm project manager but currently our project is not having dedicated DevOps person to solve issues like that, so have to do everything by myself. Don't blame for dooing something wrong here :)

This is how I tried setting up nginx, all I did is generated the .httpasswd file with login and pass and added following code to the /etc/nginx/sites-available/default

        location / {

                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;
                proxy_pass http://localhost:1337;
                proxy_http_version 1.1;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Server $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Host $http_host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
                proxy_pass_request_headers on;
                auth_basic "Login here!";
                auth_basic_user_file /etc/nginx/.htpasswd;
        }

header parameters taken from here https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/deployment/optional-software/nginx-proxy.html#nginx-virtual-host

Also tried same configuration as works on other server that had NextJS app running under basic auth

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                #try_files $uri $uri/ =404;

                proxy_pass http://localhost:1337;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                auth_basic "Login here!";
                auth_basic_user_file /etc/nginx/.htpasswd;
        }

Both now working, any ideas why?


问:
Reading logs from remote server over ssh
I am trying to ssh to a particular port on a server and read the logs but the ssh connection to server closed after authentication immediately when we try to execute it through python subprocess.

I am using following command to read the logs:

sshpass -p xxxx ssh -tt -v root@xxx.xxx.xxx.xx -p 2200 | tee -i -a remoteserver.log

Trace log:

```<code>debug1: Authentication succeeded (password).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: tty_make_modes: no fd or tio
debug1: Sending environment.
debug1: Sending env LANG = en_US
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
debug1: fd 0 clearing O_NONBLOCK
debug1: fd 1 clearing O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Connection to xxx.xxx.xxx.x closed.
Transferred: sent 1808, received 1440 bytes, in 0.0 seconds
Bytes per second: sent 36560.7, received 29119.1
debug1: Exit status 0
</code>```

PS: This command works fine when we execute it directly on terminal.

Anyone has faced similar issue?

Body:
I am trying to ssh to a particular port on a server and read the logs but the ssh connection to server closed after authentication immediately when we try to execute it through python subprocess.

I am using following command to read the logs:

sshpass -p xxxx ssh -tt -v root@xxx.xxx.xxx.xx -p 2200 | tee -i -a remoteserver.log

Trace log:

debug1: Authentication succeeded (password).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: tty_make_modes: no fd or tio
debug1: Sending environment.
debug1: Sending env LANG = en_US
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
debug1: fd 0 clearing O_NONBLOCK
debug1: fd 1 clearing O_NONBLOCK
debug1: fd 2 clearing O_NONBLOCK
Connection to xxx.xxx.xxx.x closed.
Transferred: sent 1808, received 1440 bytes, in 0.0 seconds
Bytes per second: sent 36560.7, received 29119.1
debug1: Exit status 0

PS: This command works fine when we execute it directly on terminal.

Anyone has faced similar issue?


问:
Compiling Nuklear project works with gcc but not g++
I tried to complile the main.c in Nuklear/demo/d3d11/ (https://github.com/Immediate-Mode-UI/Nuklear/tree/master/demo/d3d11) with gcc on the commend prompt, namely using

```<code>gcc main.c -luser32 -ldxguid -ld3d11
</code>```

It works perfectly.

It works using the "build.bat" too.

However, when I tried to use any of these (also changed the file name to main.cpp if needed)

```<code>g++ main.c -luser32 -ldxguid -ld3d11
gcc main.cpp -luser32 -ldxguid -ld3d11
g++ main.cpp -luser32 -ldxguid -ld3d11
</code>```

It produced a huge amount of "was not declared in this scope" errors.

```<code>In file included from main.c:30:
nuklear_d3d11.h: In function 'void nk_d3d11_render(ID3D11DeviceContext*, nk_anti_aliasing)':
nuklear_d3d11.h:101:5: error: 'ID3D11DeviceContext_IASetInputLayout' was not declared in this scope
nuklear_d3d11.h:102:5: error: 'ID3D11DeviceContext_IASetVertexBuffers' was not declared in this scope
nuklear_d3d11.h:103:5: error: 'ID3D11DeviceContext_IASetIndexBuffer' was not declared in this scope
nuklear_d3d11.h:104:5: error: 'ID3D11DeviceContext_IASetPrimitiveTopology' was not declared in this scope
nuklear_d3d11.h:106:5: error: 'ID3D11DeviceContext_VSSetShader' was not declared in this scope
nuklear_d3d11.h:107:5: error: 'ID3D11DeviceContext_VSSetConstantBuffers' was not declared in this scope
nuklear_d3d11.h:109:5: error: 'ID3D11DeviceContext_PSSetShader' was not declared in this scope
nuklear_d3d11.h:110:5: error: 'ID3D11DeviceContext_PSSetSamplers' was not declared in this scope
nuklear_d3d11.h:112:5: error: 'ID3D11DeviceContext_OMSetBlendState' was not declared in this scope
nuklear_d3d11.h:113:5: error: 'ID3D11DeviceContext_RSSetState' was not declared in this scope
nuklear_d3d11.h:114:5: error: 'ID3D11DeviceContext_RSSetViewports' was not declared in this scope
nuklear_d3d11.h:124:10: error: 'ID3D11DeviceContext_Map' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:156:5: error: 'ID3D11DeviceContext_Unmap' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:171:9: error: 'ID3D11DeviceContext_PSSetShaderResources' was not declared in this scope
nuklear_d3d11.h:172:9: error: 'ID3D11DeviceContext_RSSetScissorRects' was not declared in this scope
nuklear_d3d11.h:173:9: error: 'ID3D11DeviceContext_DrawIndexed' was not declared in this scope
In file included from D:/OtherProgramFiles/msys64/mingw64/include/winbase.h:2682,
                 from D:/OtherProgramFiles/msys64/mingw64/include/windows.h:70,
                 from main.c:7:
nuklear_d3d11.h: In function 'void nk_d3d11_resize(ID3D11DeviceContext*, int, int)':
nuklear_d3d11.h:205:19: error: 'ID3D11DeviceContext_Map' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:208:9: error: 'ID3D11DeviceContext_Unmap' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h: In function 'nk_context* nk_d3d11_init(ID3D11Device*, int, int, unsigned int, unsigned int)':
nuklear_d3d11.h:444:5: error: 'ID3D11Device_AddRef' was not declared in this scope
nuklear_d3d11.h:466:10: error: 'ID3D11Device_CreateRasterizerState' was not declared in this scope
nuklear_d3d11.h:470:11: error: 'ID3D11Device_CreateVertexShader' was not declared in this scope
nuklear_d3d11.h:479:10: error: 'ID3D11Device_CreateInputLayout' was not declared in this scope
nuklear_d3d11.h:498:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:502:11: error: 'ID3D11Device_CreatePixelShader' was not declared in this scope
nuklear_d3d11.h:517:10: error: 'ID3D11Device_CreateBlendState' was not declared in this scope
nuklear_d3d11.h:528:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:538:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:552:10: error: 'ID3D11Device_CreateSamplerState' was not declared in this scope
nuklear_d3d11.h: In function 'void nk_d3d11_font_stash_end()':
nuklear_d3d11.h:600:10: error: 'ID3D11Device_CreateTexture2D' was not declared in this scope
nuklear_d3d11.h:609:10: error: 'ID3D11Device_CreateShaderResourceView' was not declared in this scope; did you mean 'ID3D11ShaderResourceView'?
nuklear_d3d11.h:611:5: error: 'ID3D11Texture2D_Release' was not declared in this scope; did you mean 'ID3D11Texture2D'?
nuklear_d3d11.h: In function 'void nk_d3d11_shutdown()':
nuklear_d3d11.h:625:5: error: 'ID3D11SamplerState_Release' was not declared in this scope; did you mean 'ID3D11SamplerState'?
nuklear_d3d11.h:626:5: error: 'ID3D11ShaderResourceView_Release' was not declared in this scope; did you mean 'ID3D11ShaderResourceView'?
nuklear_d3d11.h:627:5: error: 'ID3D11Buffer_Release' was not declared in this scope
nuklear_d3d11.h:629:5: error: 'ID3D11BlendState_Release' was not declared in this scope; did you mean 'ID3D11BlendState'?
nuklear_d3d11.h:630:5: error: 'ID3D11PixelShader_Release' was not declared in this scope; did you mean 'ID3D11PixelShader'?
nuklear_d3d11.h:632:5: error: 'ID3D11VertexShader_Release' was not declared in this scope; did you mean 'ID3D11VertexShader'?
nuklear_d3d11.h:633:5: error: 'ID3D11InputLayout_Release' was not declared in this scope; did you mean 'ID3D11InputLayout'?
nuklear_d3d11.h:634:5: error: 'ID3D11RasterizerState_Release' was not declared in this scope; did you mean 'ID3D11RasterizerState'?
nuklear_d3d11.h:635:5: error: 'ID3D11Device_Release' was not declared in this scope
main.c: In function 'void set_swap_chain_size(int, int)':
main.c:89:9: error: 'ID3D11RenderTargetView_Release' was not declared in this scope; did you mean 'ID3D11RenderTargetView'?
main.c:91:5: error: 'ID3D11DeviceContext_OMSetRenderTargets' was not declared in this scope
main.c:93:10: error: 'IDXGISwapChain_ResizeBuffers' was not declared in this scope
main.c:106:10: error: 'IDXGISwapChain_GetBuffer' was not declared in this scope
main.c:109:10: error: 'ID3D11Device_CreateRenderTargetView' was not declared in this scope
main.c:112:5: error: 'ID3D11Texture2D_Release' was not declared in this scope; did you mean 'ID3D11Texture2D'?
main.c: In function 'int main()':
main.c:294:9: error: 'ID3D11DeviceContext_ClearRenderTargetView' was not declared in this scope
main.c:295:9: error: 'ID3D11DeviceContext_OMSetRenderTargets' was not declared in this scope
main.c:297:14: error: 'IDXGISwapChain_Present' was not declared in this scope; did you mean 'IDXGISwapChain'?
main.c:309:5: error: 'ID3D11DeviceContext_ClearState' was not declared in this scope
main.c:311:5: error: 'ID3D11RenderTargetView_Release' was not declared in this scope; did you mean 'ID3D11RenderTargetView'?
main.c:312:5: error: 'ID3D11DeviceContext_Release' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
main.c:313:5: error: 'ID3D11Device_Release' was not declared in this scope
main.c:314:5: error: 'IDXGISwapChain_Release' was not declared in this scope; did you mean 'IDXGISwapChain'?
</code>```

All four commends work if I replace main.c/main.cpp with a simple hello world script (in C, also in C++ if I add "-lstdc++").

I think all of the errors come from things in msys64\mingw64\include\d3d11.h. It may be a linking problem. But the headers are included correctly otherwise "gcc main.c" won't works. I also tried to use "extern "C" {}", but it also didn't work.

I have tried to use Visual Studio commend prompt, Visual Studio Code and commend prompt in Windows. All have the same result.

As I want to use C++ with Nuklear, how can I do it with g++?

Body:
I tried to complile the main.c in Nuklear/demo/d3d11/ (https://github.com/Immediate-Mode-UI/Nuklear/tree/master/demo/d3d11) with gcc on the commend prompt, namely using

gcc main.c -luser32 -ldxguid -ld3d11

It works perfectly.

It works using the "build.bat" too.

However, when I tried to use any of these (also changed the file name to main.cpp if needed)

g++ main.c -luser32 -ldxguid -ld3d11
gcc main.cpp -luser32 -ldxguid -ld3d11
g++ main.cpp -luser32 -ldxguid -ld3d11

It produced a huge amount of "was not declared in this scope" errors.

In file included from main.c:30:
nuklear_d3d11.h: In function 'void nk_d3d11_render(ID3D11DeviceContext*, nk_anti_aliasing)':
nuklear_d3d11.h:101:5: error: 'ID3D11DeviceContext_IASetInputLayout' was not declared in this scope
nuklear_d3d11.h:102:5: error: 'ID3D11DeviceContext_IASetVertexBuffers' was not declared in this scope
nuklear_d3d11.h:103:5: error: 'ID3D11DeviceContext_IASetIndexBuffer' was not declared in this scope
nuklear_d3d11.h:104:5: error: 'ID3D11DeviceContext_IASetPrimitiveTopology' was not declared in this scope
nuklear_d3d11.h:106:5: error: 'ID3D11DeviceContext_VSSetShader' was not declared in this scope
nuklear_d3d11.h:107:5: error: 'ID3D11DeviceContext_VSSetConstantBuffers' was not declared in this scope
nuklear_d3d11.h:109:5: error: 'ID3D11DeviceContext_PSSetShader' was not declared in this scope
nuklear_d3d11.h:110:5: error: 'ID3D11DeviceContext_PSSetSamplers' was not declared in this scope
nuklear_d3d11.h:112:5: error: 'ID3D11DeviceContext_OMSetBlendState' was not declared in this scope
nuklear_d3d11.h:113:5: error: 'ID3D11DeviceContext_RSSetState' was not declared in this scope
nuklear_d3d11.h:114:5: error: 'ID3D11DeviceContext_RSSetViewports' was not declared in this scope
nuklear_d3d11.h:124:10: error: 'ID3D11DeviceContext_Map' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:156:5: error: 'ID3D11DeviceContext_Unmap' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:171:9: error: 'ID3D11DeviceContext_PSSetShaderResources' was not declared in this scope
nuklear_d3d11.h:172:9: error: 'ID3D11DeviceContext_RSSetScissorRects' was not declared in this scope
nuklear_d3d11.h:173:9: error: 'ID3D11DeviceContext_DrawIndexed' was not declared in this scope
In file included from D:/OtherProgramFiles/msys64/mingw64/include/winbase.h:2682,
                 from D:/OtherProgramFiles/msys64/mingw64/include/windows.h:70,
                 from main.c:7:
nuklear_d3d11.h: In function 'void nk_d3d11_resize(ID3D11DeviceContext*, int, int)':
nuklear_d3d11.h:205:19: error: 'ID3D11DeviceContext_Map' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h:208:9: error: 'ID3D11DeviceContext_Unmap' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
nuklear_d3d11.h: In function 'nk_context* nk_d3d11_init(ID3D11Device*, int, int, unsigned int, unsigned int)':
nuklear_d3d11.h:444:5: error: 'ID3D11Device_AddRef' was not declared in this scope
nuklear_d3d11.h:466:10: error: 'ID3D11Device_CreateRasterizerState' was not declared in this scope
nuklear_d3d11.h:470:11: error: 'ID3D11Device_CreateVertexShader' was not declared in this scope
nuklear_d3d11.h:479:10: error: 'ID3D11Device_CreateInputLayout' was not declared in this scope
nuklear_d3d11.h:498:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:502:11: error: 'ID3D11Device_CreatePixelShader' was not declared in this scope
nuklear_d3d11.h:517:10: error: 'ID3D11Device_CreateBlendState' was not declared in this scope
nuklear_d3d11.h:528:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:538:10: error: 'ID3D11Device_CreateBuffer' was not declared in this scope
nuklear_d3d11.h:552:10: error: 'ID3D11Device_CreateSamplerState' was not declared in this scope
nuklear_d3d11.h: In function 'void nk_d3d11_font_stash_end()':
nuklear_d3d11.h:600:10: error: 'ID3D11Device_CreateTexture2D' was not declared in this scope
nuklear_d3d11.h:609:10: error: 'ID3D11Device_CreateShaderResourceView' was not declared in this scope; did you mean 'ID3D11ShaderResourceView'?
nuklear_d3d11.h:611:5: error: 'ID3D11Texture2D_Release' was not declared in this scope; did you mean 'ID3D11Texture2D'?
nuklear_d3d11.h: In function 'void nk_d3d11_shutdown()':
nuklear_d3d11.h:625:5: error: 'ID3D11SamplerState_Release' was not declared in this scope; did you mean 'ID3D11SamplerState'?
nuklear_d3d11.h:626:5: error: 'ID3D11ShaderResourceView_Release' was not declared in this scope; did you mean 'ID3D11ShaderResourceView'?
nuklear_d3d11.h:627:5: error: 'ID3D11Buffer_Release' was not declared in this scope
nuklear_d3d11.h:629:5: error: 'ID3D11BlendState_Release' was not declared in this scope; did you mean 'ID3D11BlendState'?
nuklear_d3d11.h:630:5: error: 'ID3D11PixelShader_Release' was not declared in this scope; did you mean 'ID3D11PixelShader'?
nuklear_d3d11.h:632:5: error: 'ID3D11VertexShader_Release' was not declared in this scope; did you mean 'ID3D11VertexShader'?
nuklear_d3d11.h:633:5: error: 'ID3D11InputLayout_Release' was not declared in this scope; did you mean 'ID3D11InputLayout'?
nuklear_d3d11.h:634:5: error: 'ID3D11RasterizerState_Release' was not declared in this scope; did you mean 'ID3D11RasterizerState'?
nuklear_d3d11.h:635:5: error: 'ID3D11Device_Release' was not declared in this scope
main.c: In function 'void set_swap_chain_size(int, int)':
main.c:89:9: error: 'ID3D11RenderTargetView_Release' was not declared in this scope; did you mean 'ID3D11RenderTargetView'?
main.c:91:5: error: 'ID3D11DeviceContext_OMSetRenderTargets' was not declared in this scope
main.c:93:10: error: 'IDXGISwapChain_ResizeBuffers' was not declared in this scope
main.c:106:10: error: 'IDXGISwapChain_GetBuffer' was not declared in this scope
main.c:109:10: error: 'ID3D11Device_CreateRenderTargetView' was not declared in this scope
main.c:112:5: error: 'ID3D11Texture2D_Release' was not declared in this scope; did you mean 'ID3D11Texture2D'?
main.c: In function 'int main()':
main.c:294:9: error: 'ID3D11DeviceContext_ClearRenderTargetView' was not declared in this scope
main.c:295:9: error: 'ID3D11DeviceContext_OMSetRenderTargets' was not declared in this scope
main.c:297:14: error: 'IDXGISwapChain_Present' was not declared in this scope; did you mean 'IDXGISwapChain'?
main.c:309:5: error: 'ID3D11DeviceContext_ClearState' was not declared in this scope
main.c:311:5: error: 'ID3D11RenderTargetView_Release' was not declared in this scope; did you mean 'ID3D11RenderTargetView'?
main.c:312:5: error: 'ID3D11DeviceContext_Release' was not declared in this scope; did you mean 'ID3D11DeviceContext'?
main.c:313:5: error: 'ID3D11Device_Release' was not declared in this scope
main.c:314:5: error: 'IDXGISwapChain_Release' was not declared in this scope; did you mean 'IDXGISwapChain'?

All four commends work if I replace main.c/main.cpp with a simple hello world script (in C, also in C++ if I add "-lstdc++").

I think all of the errors come from things in msys64\mingw64\include\d3d11.h. It may be a linking problem. But the headers are included correctly otherwise "gcc main.c" won't works. I also tried to use "extern "C" {}", but it also didn't work.

I have tried to use Visual Studio commend prompt, Visual Studio Code and commend prompt in Windows. All have the same result.

As I want to use C++ with Nuklear, how can I do it with g++?


问:
Cannot create 3 different subplots using Python Matplotlib Subplots functions
I am conducting a survey. The sheet consists of responses of the 12 questions from q1-q12. My purpose is to create pie charts, explain them by parts, and export the content as reports.

Therefore, I would like to have three different subplots, 4X2 for the first 8 questions, then 1X2 for the second and third parts. Before the subplots I want to add text for explaination.

I am using Jupyter Notebook, and below is my code:

```<code>
    import pandas as pd
    import matplotlib.pyplot as plt

    # Read in the survey data using pandas
    df = pd.read_excel('survey_responses.xlsx', sheet_name='econ2011')
    df2 = df.drop(df.columns[0], axis=1)

    # Create a dictionary with the titles for each question
    titles = {
        'q1': '''A1. Increasing my learning motivation''',
        'q2': '''A2. Increasing my level of engagement
        with the use of multimedia''',
        'q3': '''A3. Helping me remember and recall
        the course content''',
        'q4': '''A4. Increasing my level of interest
        in the course overall''',
        'q5': '''A5. Increasing my level of understanding
        of the course content overall''',
        'q6': '''A6. Solving doubts/questions I had
        about the course content overall''',
        'q7': '''A7. Building/sustaining a
        teacher-student relationship''',
        'q8': '''A8. Building a collaborative experience with
        other classmates, e.g. discussion of literature or group project''',
        'q9': '''B1. The software used in this course are easy
        to learn and we got familiar with them fast''',
        'q10': '''B2. We have enough technical support to adapt
        to the usage of the software''',
        'q11': '''C. Would you like to continue the usage of
        these software for this course in the future?''',
        'q12': '''D. Would you like to see the use of these
        software in your other major courses?'''
    }

    # Create a dictionary to map integer values to Likert scale labels
    likert_labels_q1_10 = {
        1: 'Strongly Disagree',
        2: 'Disagree',
        3: 'Uncertain',
        4: 'Agree',
        5: 'Strongly Agree'
    }
    likert_labels_q11_12 = {
        1: 'Very Likely',
        2: 'Likely',
        3: 'Unlikely',
        4: 'Very Unlikely'
    }

    def autopct_format(counts):
        def my_format(pct):
            total = sum(counts)
            val = int(round(pct*total/100.0))
            return '''{:.1f}%
({v:d})'''.format(pct, v=val)
        return my_format

    explode = [0]  # default value for explode

    def plot_part(df, start, end, likert_labels, fig, ax):
        # Plot the questions as pie charts
        for i, col in enumerate(df.columns[start:end]):
            counts = df[col].value_counts()
            if counts.size > 1:
                explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
                explode[0] = 0.1
            labels = counts.index.map(lambda x: likert_labels[x])
            ax[i // 2, i % 2].pie(counts, explode=explode, labels=labels, autopct=autopct_format(counts))
            ax[i // 2, i % 2].set_title(titles[col])

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 16))
    plot_part(df2, 0, 8, likert_labels_q1_10, fig, ax)

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
    plot_part(df2, 8, 10, likert_labels_q1_10, fig, ax)

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
    plot_part(df2, 10, 12, likert_labels_q11_12, fig, ax)

    # Tighten the layout
    plt.tight_layout()

    # Save the figure
    plt.savefig('survey_results_econ2011.png')

    # Show the figure
    plt.show()

</code>```

It results in this error:

```<code>---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-44-64873c28ab36> in <module>
     76 # Create a subplot with pie charts for each question
     77 fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
---> 78 plot_part(df2, 8, 10, likert_labels_q1_10, fig, ax)
     79
     80 # Create a subplot with pie charts for each question

<ipython-input-44-64873c28ab36> in plot_part(df, start, end, likert_labels, fig, ax)
     67             explode[0] = 0.1
     68         labels = counts.index.map(lambda x: likert_labels[x])
---> 69         ax[i // 2, i % 2].pie(counts, explode=explode, labels=labels, autopct=autopct_format(counts))
     70         ax[i // 2, i % 2].set_title(titles[col])
     71

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
</code>```

and there was other error like:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-5c941bea455f> in <module>
     76 # Create a subplot with pie charts for each question
     77 fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 16))
---> 78 plot_part(df2, 0, 8, likert_labels_q1_10, ax)
     79
     80 # Create a subplot with pie charts for each question

<ipython-input-38-5c941bea455f> in plot_part(df, start, end, likert_labels, ax)
     70             explode[0] = 0.1
     71         labels = counts.index.map(lambda x: likert_labels[x])
---> 72         a.pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
     73         a.set_title(titles[col])
     74

AttributeError: 'numpy.ndarray' object has no attribute 'pie'
</code>```

I know for the AttributeError, The ax parameter is a numpy array with shape (4, 2), but in the function, it is being treated as a single axis object (Should be the case?). Then I switch ax to ax[i // 2, i % 2]. And then it show the first error.

Please let me know if there's anything I can do.

I don't know my old code does work in some sense: it shows all 12 charts inside the subplot. But I hope if I can break it into three part for explanation.

```<code>    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=6, ncols=2, figsize=(10, 24))

    # Plot the first 8 questions as pie charts
    for i, col in enumerate(df2.columns[:8]):
        # Set the explode value for all unique values in the column
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q1_10[x])
        ax[i // 2][i % 2].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[i // 2][i % 2].set_title(titles[col])

    # Plot the next 2 questions as pie charts
    for i, col in enumerate(df2.columns[8:10]):
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q1_10[x])
        ax[4][i].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[4][i].set_title(titles[col])

    # Plot the last 2 questions as pie charts
    for i, col in enumerate(df2.columns[10:12]):
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q11_12[x])
        ax[5][i].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[5][i].set_title(titles[col])
</code>```

Body:
I am conducting a survey. The sheet consists of responses of the 12 questions from q1-q12. My purpose is to create pie charts, explain them by parts, and export the content as reports.

Therefore, I would like to have three different subplots, 4X2 for the first 8 questions, then 1X2 for the second and third parts. Before the subplots I want to add text for explaination.

I am using Jupyter Notebook, and below is my code:

    import pandas as pd
    import matplotlib.pyplot as plt

    # Read in the survey data using pandas
    df = pd.read_excel('survey_responses.xlsx', sheet_name='econ2011')
    df2 = df.drop(df.columns[0], axis=1)

    # Create a dictionary with the titles for each question
    titles = {
        'q1': '''A1. Increasing my learning motivation''',
        'q2': '''A2. Increasing my level of engagement
        with the use of multimedia''',
        'q3': '''A3. Helping me remember and recall
        the course content''',
        'q4': '''A4. Increasing my level of interest
        in the course overall''',
        'q5': '''A5. Increasing my level of understanding
        of the course content overall''',
        'q6': '''A6. Solving doubts/questions I had
        about the course content overall''',
        'q7': '''A7. Building/sustaining a
        teacher-student relationship''',
        'q8': '''A8. Building a collaborative experience with
        other classmates, e.g. discussion of literature or group project''',
        'q9': '''B1. The software used in this course are easy
        to learn and we got familiar with them fast''',
        'q10': '''B2. We have enough technical support to adapt
        to the usage of the software''',
        'q11': '''C. Would you like to continue the usage of
        these software for this course in the future?''',
        'q12': '''D. Would you like to see the use of these
        software in your other major courses?'''
    }

    # Create a dictionary to map integer values to Likert scale labels
    likert_labels_q1_10 = {
        1: 'Strongly Disagree',
        2: 'Disagree',
        3: 'Uncertain',
        4: 'Agree',
        5: 'Strongly Agree'
    }
    likert_labels_q11_12 = {
        1: 'Very Likely',
        2: 'Likely',
        3: 'Unlikely',
        4: 'Very Unlikely'
    }

    def autopct_format(counts):
        def my_format(pct):
            total = sum(counts)
            val = int(round(pct*total/100.0))
            return '''{:.1f}%
({v:d})'''.format(pct, v=val)
        return my_format

    explode = [0]  # default value for explode

    def plot_part(df, start, end, likert_labels, fig, ax):
        # Plot the questions as pie charts
        for i, col in enumerate(df.columns[start:end]):
            counts = df[col].value_counts()
            if counts.size > 1:
                explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
                explode[0] = 0.1
            labels = counts.index.map(lambda x: likert_labels[x])
            ax[i // 2, i % 2].pie(counts, explode=explode, labels=labels, autopct=autopct_format(counts))
            ax[i // 2, i % 2].set_title(titles[col])

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 16))
    plot_part(df2, 0, 8, likert_labels_q1_10, fig, ax)

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
    plot_part(df2, 8, 10, likert_labels_q1_10, fig, ax)

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
    plot_part(df2, 10, 12, likert_labels_q11_12, fig, ax)

    # Tighten the layout
    plt.tight_layout()

    # Save the figure
    plt.savefig('survey_results_econ2011.png')

    # Show the figure
    plt.show()

It results in this error:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-44-64873c28ab36> in <module>
     76 # Create a subplot with pie charts for each question
     77 fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
---> 78 plot_part(df2, 8, 10, likert_labels_q1_10, fig, ax)
     79
     80 # Create a subplot with pie charts for each question

<ipython-input-44-64873c28ab36> in plot_part(df, start, end, likert_labels, fig, ax)
     67             explode[0] = 0.1
     68         labels = counts.index.map(lambda x: likert_labels[x])
---> 69         ax[i // 2, i % 2].pie(counts, explode=explode, labels=labels, autopct=autopct_format(counts))
     70         ax[i // 2, i % 2].set_title(titles[col])
     71

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

and there was other error like:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-5c941bea455f> in <module>
     76 # Create a subplot with pie charts for each question
     77 fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 16))
---> 78 plot_part(df2, 0, 8, likert_labels_q1_10, ax)
     79
     80 # Create a subplot with pie charts for each question

<ipython-input-38-5c941bea455f> in plot_part(df, start, end, likert_labels, ax)
     70             explode[0] = 0.1
     71         labels = counts.index.map(lambda x: likert_labels[x])
---> 72         a.pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
     73         a.set_title(titles[col])
     74

AttributeError: 'numpy.ndarray' object has no attribute 'pie'

I know for the AttributeError, The ax parameter is a numpy array with shape (4, 2), but in the function, it is being treated as a single axis object (Should be the case?). Then I switch ax to ax[i // 2, i % 2]. And then it show the first error.

Please let me know if there's anything I can do.

I don't know my old code does work in some sense: it shows all 12 charts inside the subplot. But I hope if I can break it into three part for explanation.

    # Create a subplot with pie charts for each question
    fig, ax = plt.subplots(nrows=6, ncols=2, figsize=(10, 24))

    # Plot the first 8 questions as pie charts
    for i, col in enumerate(df2.columns[:8]):
        # Set the explode value for all unique values in the column
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q1_10[x])
        ax[i // 2][i % 2].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[i // 2][i % 2].set_title(titles[col])

    # Plot the next 2 questions as pie charts
    for i, col in enumerate(df2.columns[8:10]):
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q1_10[x])
        ax[4][i].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[4][i].set_title(titles[col])

    # Plot the last 2 questions as pie charts
    for i, col in enumerate(df2.columns[10:12]):
        counts = df2[col].value_counts()
        if counts.size > 1:
            explode = [0.05 for _ in range(counts.size)]  # assign new value to explode
            explode[0] = 0.1
        labels = counts.index.map(lambda x: likert_labels_q11_12[x])
        ax[5][i].pie(counts, explode =explode, labels=labels, autopct=autopct_format(counts))
        ax[5][i].set_title(titles[col])


问:
Add response headers if a request was served via proxy with `http-server`
How can I add a specific response header when the response was served via the proxy instead of directly?
The reason for adding the response header is basically just that I want to find out whether the response came via proxy or it came directly.

This is how I'm creating the server currently:

const httpServer = require('http-server');
const server = httpServer.createServer({
    gzip: true,
    proxy: 'https://proxy.target.url',
    https: {
        key: './key.pem',
        cert: './cert.pem'
    },
});
```

This will create a server so it proxies all requests which can't be resolved locally to the given URL.

How can I have the server mark the proxied responses(i.e. responses that were received through https://proxy.target.url)?

Body:
How can I add a specific response header when the response was served via the proxy instead of directly?
The reason for adding the response header is basically just that I want to find out whether the response came via proxy or it came directly.

This is how I'm creating the server currently:

const httpServer = require('http-server');
const server = httpServer.createServer({
    gzip: true,
    proxy: 'https://proxy.target.url',
    https: {
        key: './key.pem',
        cert: './cert.pem'
    },
});

This will create a server so it proxies all requests which can't be resolved locally to the given URL.

How can I have the server mark the proxied responses(i.e. responses that were received through https://proxy.target.url)?


问:
Compose Lazy grid cells to have equal size
I have a LazyVerticalGrid with two columns, What I want is to make all my items to have the same size. The widths of all the items take the same size which is good but I cannot make the height of the items to be the same (take all the available height). Here is my code.

```<code> LazyVerticalGrid(
    columns = GridCells.Fixed(2),
    modifier = modifier,
    contentPadding = PaddingValues(dimensionResource(id = R.dimen.margin_large)),
    verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_medium)),
    horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_large))
) {
    items(days,
        key = { day -> day.startDate }) { day ->
                DayItem(
                    day = day,
                    modifier = Modifier,
                    onClicked = { onItemClicked(day.startDate) }
                )

    }
}

    @Composable
fun DayItem(
    day: Day, modifier: Modifier = Modifier, onClicked: () -> Unit = {}
) {
    ElevatedCard(
        onClick = onClicked, modifier = modifier
    ) {
        if (day.actions.isEmpty())
            NewDayComponent()
        else
            Column(
                modifier = modifier.padding(dimensionResource(id = R.dimen.margin_large)),
                verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_medium))
            ) {
                day.feelingDuration.keys.toList().forEach { item ->
                    Row(
                        modifier = Modifier,
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_small))
                    ) {
                        Box(
                            modifier = modifier
                                .size(
                                    dimensionResource(id = R.dimen.icon_width),
                                    dimensionResource(id = R.dimen.icon_height)
                                )
                                .clip(RoundedCornerShape(dimensionResource(id = R.dimen.margin_small)))
                                .background(FeelingTypeColors[item] ?: Color.Gray)
                        )
                        Text(
                            text = day.getTypeDurationLabel(LocalContext.current, item)
                        )
                    }

                }
            }
    }
}

@Composable
fun NewDayComponent(modifier: Modifier = Modifier, onClicked: () -> Unit = {}) {
        Box(modifier = modifier.fillMaxSize()
            .clickable { onClicked() }
            .background(MaterialTheme.colorScheme.primary)) {
            Image(
                imageVector = Icons.Filled.Add,
                contentDescription = "Add Actions",
                modifier = Modifier.align(Alignment.Center)
            )
        }
}
</code>```

So the NewDayComponent needs to take the same max height which it does not. I tried setting IntrinsicHeight to the Card but it did not fix the issue.

Body:
I have a LazyVerticalGrid with two columns, What I want is to make all my items to have the same size. The widths of all the items take the same size which is good but I cannot make the height of the items to be the same (take all the available height). Here is my code.

 LazyVerticalGrid(
    columns = GridCells.Fixed(2),
    modifier = modifier,
    contentPadding = PaddingValues(dimensionResource(id = R.dimen.margin_large)),
    verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_medium)),
    horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_large))
) {
    items(days,
        key = { day -> day.startDate }) { day ->
                DayItem(
                    day = day,
                    modifier = Modifier,
                    onClicked = { onItemClicked(day.startDate) }
                )

    }
}

    @Composable
fun DayItem(
    day: Day, modifier: Modifier = Modifier, onClicked: () -> Unit = {}
) {
    ElevatedCard(
        onClick = onClicked, modifier = modifier
    ) {
        if (day.actions.isEmpty())
            NewDayComponent()
        else
            Column(
                modifier = modifier.padding(dimensionResource(id = R.dimen.margin_large)),
                verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_medium))
            ) {
                day.feelingDuration.keys.toList().forEach { item ->
                    Row(
                        modifier = Modifier,
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.margin_small))
                    ) {
                        Box(
                            modifier = modifier
                                .size(
                                    dimensionResource(id = R.dimen.icon_width),
                                    dimensionResource(id = R.dimen.icon_height)
                                )
                                .clip(RoundedCornerShape(dimensionResource(id = R.dimen.margin_small)))
                                .background(FeelingTypeColors[item] ?: Color.Gray)
                        )
                        Text(
                            text = day.getTypeDurationLabel(LocalContext.current, item)
                        )
                    }

                }
            }
    }
}

@Composable
fun NewDayComponent(modifier: Modifier = Modifier, onClicked: () -> Unit = {}) {
        Box(modifier = modifier.fillMaxSize()
            .clickable { onClicked() }
            .background(MaterialTheme.colorScheme.primary)) {
            Image(
                imageVector = Icons.Filled.Add,
                contentDescription = "Add Actions",
                modifier = Modifier.align(Alignment.Center)
            )
        }
}

So the NewDayComponent needs to take the same max height which it does not. I tried setting IntrinsicHeight to the Card but it did not fix the issue.


问:
Image Carousel behaviour
I created a sliding image carousel that works on mouse and touch interactions. The behavior of the carousel is as inteded and works perfectly.

However, the slider stops when you lift your finger or the mouse up.

What I want to achieve is to make the carousel stop with dynamic position based on how fast you are dragging. To create a better experience when dragging the images on mobile.

The following code is the HTML part of this section:

```<code><div class="Product-custom-slider product__slides" style="--default-ratio: {{ 1 | divided_by: product.media[0].aspect_ratio | times: 100 | at_most: 100 }}%">
          <div class="Product-custom-slider-inner "
            >

          {% if product.media.size > 0 %}
            {% for media in product.media %}
             <div class="Product-custom-slider-image">
              <div class="Product-contains-card">
                <img  class="srcset"

              alt="{{ media.alt | strip_html | escape }}"
              srcset="{%- if media.preview_image.width >= 550 -%}{{ media.preview_image | img_url: '550x' }} 550w,{%- endif -%}
                      {%- if media.preview_image.width >= 1100 -%}{{ media.preview_image | img_url: '1100x' }} 1100w,{%- endif -%}
                      {%- if media.preview_image.width >= 1680 -%}{{ media.preview_image | img_url: '1680x' }} 1680w,{%- endif -%}
                      {%- if media.preview_image.width >= 2048 -%}{{ media.preview_image | img_url: '2048x' }} 2048w,{%- endif -%}
                      {%- if media.preview_image.width >= 4096 -%}{{ media.preview_image | img_url: '4096x' }} 4096w
                      {%- else -%}{{ media.preview_image | img_url: 'master' }} {{ media.preview_image.width | append: 'w' }}{%- endif -%}"
              sizes="(min-width: 768px), 50vw,
                     100vw"
              src="{{ media.preview_image | img_url: '1100x' }}"
              loading="eager"
              width="1180"
              >

               </div>
            </div>
              {% endfor %}
            </div>
          {% else %}
            <div class="product__image__placeholder"></div>
          {% endif %}

        </div>
</code>```

The following is the CSS :

```<code>.Product-custom-slider {
  position: absolute !important;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
}
.Product-custom-slider-inner {
  position: absolute !important;
  top: 0;
  left: 0;
  height: 100%;
  width: fit-content;
  display: flex;

  pointer-events: none;
  scroll-behavior: smooth;

}
.Product-custom-slider-image {
  height: 100%;
  width: 85vw;
}

</code>```

And following is the JS code:

```<code>
<script>
  let ProductSlider = document.querySelector(".Product-custom-slider");
  let ProductSliderinner = document.querySelector(".Product-custom-slider-inner");
  let pressedx = false;
  let startX;
  let X;

  ProductSlider.addEventListener('mousedown', (e) => {
    pressedx = true;
    startX = e.offsetX - ProductSliderinner.offsetLeft;
    ProductSlider.style.cursor= 'grabbing';

  });
   ProductSlider.addEventListener('touchstart', (e) => {
    pressedx = true;

    startX = (e.touches[0].pageX - e.touches[0].target.offsetLeft) - ProductSliderinner.offsetLeft;

  });
  ProductSlider.addEventListener('mouseenter', () => {
    ProductSlider.style.cursor= 'grab';

  });
  ProductSlider.addEventListener('mouseleave', () => {
    ProductSlider.style.cursor= 'default';

  });
  ProductSlider.addEventListener('mouseup', () => {
    ProductSlider.style.cursor= 'grab';

  });

  window.addEventListener('mouseup', () => {
    pressedx = false;

  });
   window.addEventListener('touchend', () => {
    pressedx = false;

  });

  ProductSlider.addEventListener('mousemove', (e) => {

    if (!pressedx) return;
    e.preventDefault();
    X = e.offsetX;

    ProductSliderinner.style.left = (X - startX) + "pX";
    checkBoundariesProduct();
  });
   ProductSlider.addEventListener('touchmove', (e) => {

    if (!pressedx) return;

    X = (e.touches[0].pageX - e.touches[0].target.offsetLeft);

     ProductSliderinner.style.left = (X - startX) + "pX";

    checkBoundariesProduct();
  });

  function checkBoundariesProduct() {
    let ProductOuter = ProductSlider.getBoundingClientRect();
    let ProductInner = ProductSliderinner.getBoundingClientRect();

    if (parseInt(ProductSliderinner.style.left) > 0) {
      ProductSliderinner.style.left = '0pX';
    }
    else if (ProductInner.right < ProductOuter.right) {
      ProductSliderinner.style.left = -(ProductInner.width - ProductOuter.width) + "pX";
    }

  }
</script>

</code>```

I want to achieve the same effect here (Link
However, implementing the code into my website didnt seem to work.

Any help on how to achieve the same effect as the link via editing my current codes ?

https://codepen.io/loxks/pen/KKpVvVW

I tried the code from the previous link, it didnt seem to work

Title: Image Carousel behaviour

Body:
I created a sliding image carousel that works on mouse and touch interactions. The behavior of the carousel is as inteded and works perfectly.

However, the slider stops when you lift your finger or the mouse up.

What I want to achieve is to make the carousel stop with dynamic position based on how fast you are dragging. To create a better experience when dragging the images on mobile.

The following code is the HTML part of this section:

          {% if product.media.size > 0 %}
            {% for media in product.media %}

                = 550 -%}{{ media.preview_image | img_url: '550x' }} 550w,{%- endif -%}
                      {%- if media.preview_image.width >= 1100 -%}{{ media.preview_image | img_url: '1100x' }} 1100w,{%- endif -%}
                      {%- if media.preview_image.width >= 1680 -%}{{ media.preview_image | img_url: '1680x' }} 1680w,{%- endif -%}
                      {%- if media.preview_image.width >= 2048 -%}{{ media.preview_image | img_url: '2048x' }} 2048w,{%- endif -%}
                      {%- if media.preview_image.width >= 4096 -%}{{ media.preview_image | img_url: '4096x' }} 4096w
                      {%- else -%}{{ media.preview_image | img_url: 'master' }} {{ media.preview_image.width | append: 'w' }}{%- endif -%}"
              sizes="(min-width: 768px), 50vw,
                     100vw"
              src="{{ media.preview_image | img_url: '1100x' }}"
              loading="eager"
              width="1180"
              >

              {% endfor %}

          {% else %}

          {% endif %}

The following is the CSS :

.Product-custom-slider {
  position: absolute !important;
  width: 100%;
  height: 100%;
  overflow: hidden;
  top: 0;
}
.Product-custom-slider-inner {
  position: absolute !important;
  top: 0;
  left: 0;
  height: 100%;
  width: fit-content;
  display: flex;

  pointer-events: none;
  scroll-behavior: smooth;

}
.Product-custom-slider-image {
  height: 100%;
  width: 85vw;
}

And following is the JS code:

I want to achieve the same effect here (Link
However, implementing the code into my website didnt seem to work.

Any help on how to achieve the same effect as the link via editing my current codes ?

https://codepen.io/loxks/pen/KKpVvVW

I tried the code from the previous link, it didnt seem to work


问:
WDIO-test reads the file incorrectly
I am writing a test that needs to read a file. I wrote the following function:

```<code>upload_file = (file_name, input_class) ->
  await browser.executeScript("window.document.getElementsByClassName('" +
    input_class + "')[0].style.display = 'block'", [])
  file_path = path.join(FILE_PATH, file_name)
  await $('input.' + input_class).then((res) ->
    return res.setValue(file_path)
  )
</code>```

However, the test fails to test the script

In the code that is executed after the file is uploaded to the site, I output the file that was read. All information is correct except file size which is 0

Please help me

Title: WDIO-test reads the file incorrectly

Body:
I am writing a test that needs to read a file. I wrote the following function:

upload_file = (file_name, input_class) ->
  await browser.executeScript("window.document.getElementsByClassName('" +
    input_class + "')[0].style.display = 'block'", [])
  file_path = path.join(FILE_PATH, file_name)
  await $('input.' + input_class).then((res) ->
    return res.setValue(file_path)
  )

However, the test fails to test the script

In the code that is executed after the file is uploaded to the site, I output the file that was read. All information is correct except file size which is 0

Please help me


问:
How to import jars from a directory for JShell in Mac OS terminal?
I'm wondering if there is a bug with Jshell.
I have tried all forms of importing the commons lang jar into the classpath trying:

1 - This solution

2 - Also followed this solution too.

I even launched jshell from the directory where the jar itself resides and when I execute a System.getProperty("user.dir") I get the correct path so it is confirmed that I am in the right directory, but I am unable to import the commons lang jar for use in jshell.

At this point I'm wondering if this is a bug.

Relevant system info are:

JDK - Java 17

OS - macOS Monterey (M1 Pro)


Title: Logstash - read and parse a string with multiple records on same line

Body:
Below is my config file,

input {
file{
    path => "/Users/.../Work/Projects/ELK/Logstash/Input/*.txt"
    start_position => beginning
    codec => "json"
    type => "data"
    sincedb_path => "NUL"
   }
}

filter {
    grok { match => { "message" => "<%{NUMBER}>%{SYSLOGTIMESTAMP} %{IPV4} %{HOSTNAME:nodeName}: %{NUMBER} %{WORD} \[%{DATA}\]: %{GREEDYDATA:[anotherField]} \n" } }
        # Create array of strings
        mutate { split => { "[anotherField]" => "| " } }
        # Create a separate event for each array entry
        split { field => "[anotherField]" }
    }

output {
stdout{}
 file {
   path => "/Users/...../Work/Projects/ELK/Logstash/test.csv"
   codec => line { format => "%{nodeName},%{anotherField}"}
 }
}

Input to the above is:

{"@timestamp":"2022-12-01T13:30:00.004Z","message":"<190>Dec  1 14:29:59 10.62.161.199 AA-AMG3U: 0950198238 NN [MDA 8/4]: LN44 SA 2022 Dec  1 14:29:59:87 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467000XXXX1_35292011220XXXXX_string1 | LN44 SD 2022 Dec  1 14:29:59:89 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467000XXXX1_35292011220XXXXX_string2 | LN44 SA 2022 Dec  1 14:29:59:87 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467679XXXX2_35292011220XXXXX_string1 \n","@version":"1","host":"100.62.161.XXX"}

Current output is:

AA-AMG3U,LN44 SA 2022 Dec  1 14:29:59:87 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467000XXXX1_35292011220XXXXX_string1
AA-AMG3U,LN44 SD 2022 Dec  1 14:29:59:89 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467000XXXX1_35292011220XXXXX_string2
AA-AMG3U,LN44 SA 2022 Dec  1 14:29:59:87 CET 17 4001 10.XX.133.XX 56560 401 91.235.10.25 15179 2400160261XXXXX_467679XXXX2_35292011220XXXXX_string1

How do I change to get the output as:

AA-AMG3U,LN44,SA,2022 Dec  1 14:29:59:87 CET,17,4001,10.XX.133.XX 56560,401 91.235.10.25 15179,2400160261XXXXX,467000XXXX1,35292011220XXXXX,string1
AA-AMG3U,LN44,SD,2022 Dec  1 14:29:59:87 CET,17,4001,10.XX.133.XX 56560,401 91.235.10.25 15179,2400160261XXXXX,467000XXXX1,35292011220XXXXX,string1
AA-AMG3U,LN44,SA,2022 Dec  1 14:29:59:87 CET,17,4001,10.XX.133.XX 56560,401 91.235.10.25 15179,2400160261XXXXX,467000XXXX2,35292011220XXXXX,string1

I am not sure how to iterate through arrays that are inside a specific string?


问:
How to mock 'cross-fetch' GET POST & PUT methods
I have my code as

```<code>import fetch from 'cross-fetch'

const headers = {
      Authorization: `Bearer abcdEFGH1234`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }

const getData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey', {
        method: 'GET',
        headers: headers,
      })
// convert the API Call response to Json
const getDataJson = await getData.json()

const putData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/comments', {
        method: 'PUT',
        headers: headers,
        body: {message: "comment"},
      })
// convert the API Call response to Json
const putDataJson = await putData.json()
</code>```

cross-fetch does not seem to have methods directly like fetch.get or fetch.PUT, so the methods have to be passed via options.

The problem I am facing is how to mock these methods during testing with Jest.

I tried as below but it does not work

```<code>const mockFetchGet = jest.fn((arg1, arg2) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})
const mockFetchPost = jest.fn((arg1, arg2, arg3) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})
const mockFetchPut = jest.fn((arg1, arg2, arg3) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})

jest.mock('cross-fetch', () => {
  return {
    fetch: jest.fn().mockImplementation(() => {
      return {
        get: mockFetchGet,
        post: mockFetchPost,
        put: mockFetchPut,
      }
    }),
  }
})
</code>```

I get the error like below. Can anyone help? ANY GUIDANCE IN THIS IS HIGHLY APPRECIATED

```<code>TypeError: (0 , cross_fetch_1.default) is not a function

      75 |   )
      76 |
    > 77 |   const mergePullRequest = await fetch(
         |                                       ^
      78 |     `https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/merge`,
      79 |     {
      80 |       method: 'POST',
</code>```

Body:
I have my code as

import fetch from 'cross-fetch'

const headers = {
      Authorization: `Bearer abcdEFGH1234`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }

const getData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey', {
        method: 'GET',
        headers: headers,
      })
// convert the API Call response to Json
const getDataJson = await getData.json()

const putData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/comments', {
        method: 'PUT',
        headers: headers,
        body: {message: "comment"},
      })
// convert the API Call response to Json
const putDataJson = await putData.json()

cross-fetch does not seem to have methods directly like fetch.get or fetch.PUT, so the methods have to be passed via options.

The problem I am facing is how to mock these methods during testing with Jest.

I tried as below but it does not work

const mockFetchGet = jest.fn((arg1, arg2) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})
const mockFetchPost = jest.fn((arg1, arg2, arg3) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})
const mockFetchPut = jest.fn((arg1, arg2, arg3) => {
  return new Promise((resolve) => {
    resolve(true)
  })
})

jest.mock('cross-fetch', () => {
  return {
    fetch: jest.fn().mockImplementation(() => {
      return {
        get: mockFetchGet,
        post: mockFetchPost,
        put: mockFetchPut,
      }
    }),
  }
})

I get the error like below. Can anyone help? ANY GUIDANCE IN THIS IS HIGHLY APPRECIATED

TypeError: (0 , cross_fetch_1.default) is not a function

      75 |   )
      76 |
    > 77 |   const mergePullRequest = await fetch(
         |                                       ^
      78 |     `https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/merge`,
      79 |     {
      80 |       method: 'POST',


问:
How can I attach a file where path and file name are cell values?
I want to create an email with an attachment.

It will be used by multiple users so the path is different. Users will enter the path in a cell. Same goes for the file name. Users will enter it in a cell.

My current code:

Private Sub CommandButton1_Click()

    Dim strbody As String
    Dim xStrFile As String
    Dim xFilePath As String
    Dim xFileDlg As FileDialog
    Dim xFileDlgItem As Variant
    Dim xOutApp As Outlook.Application
    Dim xMailOut As Outlook.MailItem
    Application.ScreenUpdating = False

    Set xOutApp = CreateObject("Outlook.Application")
    Set xMailOut = xOutApp.CreateItem(olMailItem)
    Set xFileDlg = Application.FileDialog(msoFileDialogFilePicker)

    If xFileDlg.Show = -1 Then
        With xMailOut
            .To = ""
            .CC = Rows(2).Columns(4).Value
            .BCC = Rows(2).Columns(3).Value
            .Subject = Rows(2).Columns(5).Value
            .Body = Rows(2).Columns(6).Value
            For Each xFileDlgItem In xFileDlg.SelectedItems
                .Attachments.Add xFileDlgItem
            Next xFileDlgItem
            .Display
        End With
    End If
    Set xMailOut = Nothing
    Set xOutApp = Nothing
    Application.ScreenUpdating = True
End Sub
```


问:
Access not given while integrating cypress dashboard with bitbucket
I tried integrating cypress dashboard with bitbucket and when i click the button below

It redirects me to this page instead of linking it up with the bitbucket even though i have right and correct access to the bitbucket.

Just to be sure, I tried creating new project in cypress dashboard and integrate it with bitbucket as an owner of the repo but still I face the same issue.

PS: I was trying to implement parallelization for end to end testing integrating cypress dashboard with bitbucket.

Can you guys please help me out. Been stuck to this for days now.


问:
AWS API Gateway: Unauthorized request is giving response with error.response.status value of 0 instead of 401
I am using AWS API Gateway with Cognito for the server side.

On the frontend side, I am using ReactJS with Axios to send requests.

When the access token expires, the Axios request will fail and a response is recevied.

I use Axios Interceptor mechanism to catch the failed response and refresh the token and retry the request, as following code:

```<code>axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    console.log(`error.response.status: ${error.response.status}`);

    if (!error.response || error.response.status === 401) {

      const currentSession = await Auth.currentSession();

      setStoredAuthToken(currentSession.idToken.jwtToken);
      setStoredAccessToken(currentSession.accessToken.jwtToken);

      originalRequest.headers.authorization = getStoredAuthToken();
    }

    if (originalRequest.retryCount) {
      originalRequest.retryCount++;
    } else {
      originalRequest.retryCount = 1;
    }
    if (originalRequest.retryCount > 3) {
      return Promise.reject(error);
    }

    await sleep(2 ** originalRequest.retryCount * 1000);
    return axios.request(originalRequest);
  }
);

</code>```

It has been working very well for a long time.
But recently, the token-refreshing mechanism has failed.

After some debugging, I found that the error.response.status value is no longer 401, as it has always been before.
Instead, it is now giving a value of 0.

Why?

Any ideas?

Body:
I am using AWS API Gateway with Cognito for the server side.

On the frontend side, I am using ReactJS with Axios to send requests.

When the access token expires, the Axios request will fail and a response is recevied.

I use Axios Interceptor mechanism to catch the failed response and refresh the token and retry the request, as following code:

axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    console.log(`error.response.status: ${error.response.status}`);

    if (!error.response || error.response.status === 401) {

      const currentSession = await Auth.currentSession();

      setStoredAuthToken(currentSession.idToken.jwtToken);
      setStoredAccessToken(currentSession.accessToken.jwtToken);

      originalRequest.headers.authorization = getStoredAuthToken();
    }

    if (originalRequest.retryCount) {
      originalRequest.retryCount++;
    } else {
      originalRequest.retryCount = 1;
    }
    if (originalRequest.retryCount > 3) {
      return Promise.reject(error);
    }

    await sleep(2 ** originalRequest.retryCount * 1000);
    return axios.request(originalRequest);
  }
);

It has been working very well for a long time.
But recently, the token-refreshing mechanism has failed.

After some debugging, I found that the error.response.status value is no longer 401, as it has always been before.
Instead, it is now giving a value of 0.

Why?

Any ideas?


问:
How to test a setInterval inside useEffect with RTL?
Given this component:

```<code>const PromoBannerSlideShow: React.FC<PropTypes> = ({ data }) => {
const [index, setIndex] = useState<number>(0);

const { interval } = data!.fields;
const { containerBackgroundColor } = data!.fields;
const { components } = data!.fields?.elements;

useEffect(() => {
    if (!components?.length) return;
    const id = setInterval(() => {
        setIndex((prevIndex) => {
            if (prevIndex === components?.length - 1) {
                return 0;
            }
            return prevIndex + 1;
        });
    }, interval?.value);
    return () => clearInterval(id);
}, [components, interval?.value]);

if (!components) return null;

return (
    <StyledWrapper backgroundColor={containerBackgroundColor?.hex}>
        {components?.map((component: TBanner, i: number) => {
            return (
                <TextBanner
                    key={component?.fields?.message?.value + i}
                    colorBackground={
                        component?.fields?.colorBackground?.hex
                    }
                    colorText={component?.fields?.colorMessage?.hex}
                    title={component?.fields?.message?.value}
                    visible={index === i}
                />
            );
        })}
    </StyledWrapper>
);
</code>```

The test coverage lets setInterval lines uncovered. How could I test them with Jest and React Testing Library? I tried using jest timer functions, but I cannot manage to reach those lines for the test coverage.

Body:
Given this component:

const PromoBannerSlideShow: React.FC<PropTypes> = ({ data }) => {
const [index, setIndex] = useState<number>(0);

const { interval } = data!.fields;
const { containerBackgroundColor } = data!.fields;
const { components } = data!.fields?.elements;

useEffect(() => {
    if (!components?.length) return;
    const id = setInterval(() => {
        setIndex((prevIndex) => {
            if (prevIndex === components?.length - 1) {
                return 0;
            }
            return prevIndex + 1;
        });
    }, interval?.value);
    return () => clearInterval(id);
}, [components, interval?.value]);

if (!components) return null;

return (

);

The test coverage lets setInterval lines uncovered. How could I test them with Jest and React Testing Library? I tried using jest timer functions, but I cannot manage to reach those lines for the test coverage.


问:
How to prevent other Divs closing in collapsible Bootstrap 5
I have this code in bootstrap 5 and it works as expected.
when clicking the  tag the appropriate divs collapsed/hiden.
However i want to prevent the closing of other divs when you open the other one, how to prevent this in bootstrap 5?</p>
```<code>        <li class="nav-item">
            <a class="nav-link" data-bs-toggle="collapse" role="button" href="#ui-basic" aria-expanded="false" aria-controls="ui-basic">
                <i class="icon-layout menu-icon"></i>
                <span class="menu-title">Listing Management</span>
                <i class="menu-arrow"></i>
            </a>
            <div class="collapse" id="ui-basic">
                <ul class="nav flex-column sub-menu">
                    <li class="nav-item"> 1<li>
                    <li class="nav-item"> 2<li>
                    <li class="nav-item"> 3<li>
                </ul>
            </div>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-bs-toggle="collapse" role="button" href="#ui-enquiries" aria-expanded="false" aria-controls="ui-enquiries">
                <i class="icon-grid-2 menu-icon"></i>
                <span class="menu-title">Inquiries</span>
                <i class="menu-arrow"></i>
            </a>
            <div class="collapse" id="ui-enquiries">
                <ul class="nav flex-column sub-menu">
                    <li class="nav-item"> 1<li>
                    <li class="nav-item"> 2<li>
                    <li class="nav-item"> 3<li>
                </ul>
            </div>
        </li>
</code>```

Body:
I have this code in bootstrap 5 and it works as expected.
when clicking the  tag the appropriate divs collapsed/hiden.
However i want to prevent the closing of other divs when you open the other one, how to prevent this in bootstrap 5?

                Listing Management

 1

 2

 3

                Inquiries

 1

 2

 3


问:
Rolling back multi job pipeline to an environment in gitlab
I have a multi-job deployment to an environment in GitLab CI. When I do a rollback of the environment only the last job is executed but I need to execute all the jobs.

My stages are like this: 1) Build 2) Test 3) Build Docker image 4) Deploy docker image, in a rollback only the 4th stage is ran but this is not what I want, I want to re-build the app so the previous version is deployed. Is there some solution to this? Re-run all the pipeline or can I deploy a previous version of my docker image (I have all the previous version stored) with the environment feature in GitLab?

I tried to specify the same environment in all the jobs but 4 environments are created, not 1 environment with 3 jobs so I only can roll-back one job.


问:
winui3/uwp Is there anyway to force updating GUI during the code excute in UI thread
I want to progammly select a new created item in treeview (windowscommunitytoolkit), however, the TreeViewItem/TreeViewNode of that item will not been built till the GUI update, also will not been built till the rootnode expand (if the rootnode is in collapsed state, but itemsource change).

The tree structure is:

```<code>rootnode
--node1
----subnode1
----subnode2
--node2
</code>```

If I do something like that

```<code>rootnodeitem.NotifyPropertyChanged("ItemSouceBindData");      // It will update rootnode children.
treeview.Expand(rootnode);      // Try to make rootnode expand to make new TreeViewItem load
foreach(var node in rootnode.Children) treeview.Expand(node);
treeview.SelectedNode = treeview.NodefromContainer(treeview.ContainerfromItem(subnode1item));
</code>```

Line3 and line4 are all useless, for after the treeview.Expand(rootnode);, node1.Children.Count=0, So treeview.Expand(node) will do nothing and treeview.ContainerfromItem(subnode1item) or treeview.NodefromContainer(...) will all return null.

So I wonder if I can do something like that

```<code>rootnodeitem.NotifyPropertyChanged("ItemSouceBindData");      // It will update rootnode children.
FoceRefreshGUI();
treeview.Expand(rootnode);      // Try to make rootnode expand to make new TreeViewItem load
FoceRefreshGUI();
foreach(var node in rootnode.Children) treeview.Expand(node);
FoceRefreshGUI();
treeview.SelectedNode = treeview.NodefromContainer(treeview.ContainerfromItem(subnode1item));
</code>```

I try lots of things like use await Task.Run(async () => { await Task.Delay(10000); });, but it is hard to control the delay time and also it will not gurantee the GUI finish update during the delay time.

So I wonder is there anyway to force updating GUI during the code excute in UI thread?
Or Is there anyway to force treeview refresh to build all its new chilnodes?

Thank you very much if you have any idea

Updated the binding xaml:

```<code><Page.Resources>
        <DataTemplate x:Key="grouptemplate_"
                      x:DataType="local:ModelLeafItem">
            <TreeViewItem ItemsSource="{x:Bind ItemSouceBindData, Mode=OneWay}">
                <StackPanel Orientation="Horizontal">
                    <Image Width="10"
                           Source="{x:Bind ImageSrc}" />
                    <TextBlock Margin="0,0,10,0" />
                    <TextBlock Text="{x:Bind Name}" />
                </StackPanel>
            </TreeViewItem>
        </DataTemplate>
        <DataTemplate x:Key="itemtemplate_"
                      x:DataType="local:ModelLeafItem">
            <TreeViewItem>
                <StackPanel Orientation="Horizontal">
                    <Border Background="{x:Bind IconBrush}">
                        <Image Width="10"
                               Source="{x:Bind ImageSrc}" />
                    </Border>
                    <TextBlock Margin="0,0,10,0" />
                    <TextBlock Text="{x:Bind Name}" />
                </StackPanel>
            </TreeViewItem>
        </DataTemplate>
        <local:ModelItemTemplateSelector x:Key="modelitemtemplateselector_"
                                         GroupTemplate="{StaticResource grouptemplate_}"
                                         ItemTemplate="{StaticResource itemtemplate_}" />
    </Page.Resources>
<Grid>
        <TreeView x:Name="treeview_"
                  ItemsSource="{x:Bind ModelData, Mode=OneWay}"
                  ItemTemplateSelector="{StaticResource modelitemtemplateselector_}"
                  SelectionMode="Single">
        </TreeView>

    </Grid>
</code>```

Body:
I want to progammly select a new created item in treeview (windowscommunitytoolkit), however, the TreeViewItem/TreeViewNode of that item will not been built till the GUI update, also will not been built till the rootnode expand (if the rootnode is in collapsed state, but itemsource change).

The tree structure is:

rootnode
--node1
----subnode1
----subnode2
--node2

If I do something like that

rootnodeitem.NotifyPropertyChanged("ItemSouceBindData");      // It will update rootnode children.
treeview.Expand(rootnode);      // Try to make rootnode expand to make new TreeViewItem load
foreach(var node in rootnode.Children) treeview.Expand(node);
treeview.SelectedNode = treeview.NodefromContainer(treeview.ContainerfromItem(subnode1item));

Line3 and line4 are all useless, for after the treeview.Expand(rootnode);, node1.Children.Count=0, So treeview.Expand(node) will do nothing and treeview.ContainerfromItem(subnode1item) or treeview.NodefromContainer(...) will all return null.

So I wonder if I can do something like that

rootnodeitem.NotifyPropertyChanged("ItemSouceBindData");      // It will update rootnode children.
FoceRefreshGUI();
treeview.Expand(rootnode);      // Try to make rootnode expand to make new TreeViewItem load
FoceRefreshGUI();
foreach(var node in rootnode.Children) treeview.Expand(node);
FoceRefreshGUI();
treeview.SelectedNode = treeview.NodefromContainer(treeview.ContainerfromItem(subnode1item));

I try lots of things like use await Task.Run(async () => { await Task.Delay(10000); });, but it is hard to control the delay time and also it will not gurantee the GUI finish update during the delay time.

So I wonder is there anyway to force updating GUI during the code excute in UI thread?
Or Is there anyway to force treeview refresh to build all its new chilnodes?

Thank you very much if you have any idea

Updated the binding xaml:

<Page.Resources>
        <DataTemplate x:Key="grouptemplate_"
                      x:DataType="local:ModelLeafItem">
            <TreeViewItem ItemsSource="{x:Bind ItemSouceBindData, Mode=OneWay}">
                <StackPanel Orientation="Horizontal">
                    <Image Width="10"
                           Source="{x:Bind ImageSrc}" />
                    <TextBlock Margin="0,0,10,0" />
                    <TextBlock Text="{x:Bind Name}" />
                </StackPanel>
            </TreeViewItem>
        </DataTemplate>
        <DataTemplate x:Key="itemtemplate_"
                      x:DataType="local:ModelLeafItem">
            <TreeViewItem>
                <StackPanel Orientation="Horizontal">
                    <Border Background="{x:Bind IconBrush}">
                        <Image Width="10"
                               Source="{x:Bind ImageSrc}" />
                    </Border>
                    <TextBlock Margin="0,0,10,0" />
                    <TextBlock Text="{x:Bind Name}" />
                </StackPanel>
            </TreeViewItem>
        </DataTemplate>
        <local:ModelItemTemplateSelector x:Key="modelitemtemplateselector_"
                                         GroupTemplate="{StaticResource grouptemplate_}"
                                         ItemTemplate="{StaticResource itemtemplate_}" />
    </Page.Resources>
<Grid>
        <TreeView x:Name="treeview_"
                  ItemsSource="{x:Bind ModelData, Mode=OneWay}"
                  ItemTemplateSelector="{StaticResource modelitemtemplateselector_}"
                  SelectionMode="Single">
        </TreeView>

    </Grid>


问:
Python Tabula or Pandas - Skip linebreak at NaN values
I'm gonna get a wonderfull Dataframa from reading a PDF Table with Tabula. So far so good.

Is there any way to tell Tabula to wait with the Linebreak until the next Value in Row "AMTOSS/NDT No." comes up or alternate to do it with Pandas afterwards.

My current output looks as follow:
enter image description here

Finally the Data should be in one Cell as marked:
enter image description here

I tried it allready with groupby, skipna,.... FInally after 90 different trial i give up. ;-)

What i have so far (basically only read the pdf file):

```<code>    file1 = r"C:\Users\XXX\Desktop\XXX\XYZ.pdf"
output = tabula.read_pdf(file1, guess=True, pages='2-3',stream=True, multiple_tables=False)
df = pd.DataFrame(output[0])
#pd.set_option('display.expand_frame_repr', True)
#df2 = df1.notna() #--->shows all cells with True or False if there's a NaN Value
pd.set_option('display.max_colwidth', None)
df
</code>```

Body:
I'm gonna get a wonderfull Dataframa from reading a PDF Table with Tabula. So far so good.

Is there any way to tell Tabula to wait with the Linebreak until the next Value in Row "AMTOSS/NDT No." comes up or alternate to do it with Pandas afterwards.

My current output looks as follow:
enter image description here

Finally the Data should be in one Cell as marked:
enter image description here

I tried it allready with groupby, skipna,.... FInally after 90 different trial i give up. ;-)

What i have so far (basically only read the pdf file):

    file1 = r"C:\Users\XXX\Desktop\XXX\XYZ.pdf"
output = tabula.read_pdf(file1, guess=True, pages='2-3',stream=True, multiple_tables=False)
df = pd.DataFrame(output[0])
#pd.set_option('display.expand_frame_repr', True)
#df2 = df1.notna() #--->shows all cells with True or False if there's a NaN Value
pd.set_option('display.max_colwidth', None)
df


问:
Decode strings with special characters in JavaScript
When I was fetching some data through API, I have some Danish strings which came encoded like below:

Encoded
Original

Skæfte
Skæfte

sølv
sølv

Tried combinations of decodeURIComponent() and escape() but that doesn't help. Any ways to decode the string in native JS irrespective of the encoded language (Danish, in this case)?


问:
How to export js file in public-api.ts
I was trying to create a angular library and I have created one. Now I want to add my react project in it.
Then I am  exporting my files in public-api.ts file so that I can use it in my library But file with js extention is giving me a error.All with .ts extention alone is taking.How  can I resolve this

I am expecting I can bundle my react project in angular library.

Title: How to export js file in public-api.ts


问:
Panel VAR estimation using GMM on panelvar
I've been trying to estimate a pVAR using GMM on R using the package panelvar. I'm estimating a dynamic panel VAR with two-step GMM using first-differences.

I have a balanced panel with 378 with a group variable (id) and a time variable (year). I have 14 observations per group (unvaried) and 27 groups in total. In total, I have 120 instruments. I'm a bit concerned about the results of the Hansen J-test and I'm looking for some explanations: I have a Hansen J-test statistic of 0 with a p-value of 1. To my understanding, this would mean that the model is correctly specified. But the fact that the p-value is very high (1.000), it might mean that something deeper is going on.

In my estimation, I have 7 dependent variables, 2 exogenous variables, and I'm using 4 lagged instruments per dependent variable. Why is the p-value of the Hansen test very high?

Thanks in advance!


问:
Lost Clients PBI
I am trying to get the number of lost clients per month. The code I'm using for the measure is set forth next:

```<code>`LostClientsRunningTotal =
VAR currdate = MAX('Date'[Date])
VAR turnoverinperiod=[Turnover]
VAR clients=
ADDCOLUMNS(
    Client,
    "Turnover Until Now",
    CALCULATE([Turnover],
    DATESINPERIOD(
        'Date'[Date],
        currdate,
        -1,
        MONTH)),
        "Running Total Turnover",
        [RunningTotalTurnover]
)
VAR lostclients=
    FILTER(clients,
    [Running Total Turnover]>0 &&
    [Turnover Until Now]=0)
RETURN
    IF(turnoverinperiod>0,
    COUNTROWS(lostclients))`
</code>```

The problem is that I'm getting the running total and the result it returns is the following:
enter image description here

What I need is the lost clients per month so I tried to use the dateadd function to get the lost clients of the previous month and then subtract the current.

The desired result would be, for Nov-22 for instance, 629 (December running total) - 544 (November running total) = 85.

For some reason the **dateadd **function is not returning the desired result and I can't make head or tails of it.

Can you tell me how should I approach this issue please? Thank you in advance.

Title: Lost Clients PBI

Body:
I am trying to get the number of lost clients per month. The code I'm using for the measure is set forth next:

`LostClientsRunningTotal =
VAR currdate = MAX('Date'[Date])
VAR turnoverinperiod=[Turnover]
VAR clients=
ADDCOLUMNS(
    Client,
    "Turnover Until Now",
    CALCULATE([Turnover],
    DATESINPERIOD(
        'Date'[Date],
        currdate,
        -1,
        MONTH)),
        "Running Total Turnover",
        [RunningTotalTurnover]
)
VAR lostclients=
    FILTER(clients,
    [Running Total Turnover]>0 &&
    [Turnover Until Now]=0)
RETURN
    IF(turnoverinperiod>0,
    COUNTROWS(lostclients))`

The problem is that I'm getting the running total and the result it returns is the following:
enter image description here

What I need is the lost clients per month so I tried to use the dateadd function to get the lost clients of the previous month and then subtract the current.

The desired result would be, for Nov-22 for instance, 629 (December running total) - 544 (November running total) = 85.

For some reason the **dateadd **function is not returning the desired result and I can't make head or tails of it.

Can you tell me how should I approach this issue please? Thank you in advance.