问:
How to link descriptor table with multiple range to the compute shader
How to link one UAV descriptor table with a multiple ranges(u0,u1,u2) to the compute Shader

I can make a buffer for each of them and it would work but, I can't seem to figure out how to make it work using multiple ranges.

SetComputeRootDescriptorTable(RootParameterIndex,BaseDescriptor) Takes only these two inputs, This is how I attempted to compute it, so naturally I though I will link the three descriptors as commented below, but the app crash, so I commented the code that cause the crash.

```<code>ThrowIfFailed(m_pCommandAllocator->Reset());
    ThrowIfFailed(m_pCommandList->Reset(m_pCommandAllocator.Get(), m_pPipelineState["CSPSO"].Get()));

    m_pCommandList->SetComputeRootSignature(m_pCSRootSig.Get());
D3D12_GPU_DESCRIPTOR_HANDLE pComputeGPUHeapOffset= m_pCbvSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart();

ID3D12DescriptorHeap* ppHeaps[] = { m_pCbvSrvDescriptorHeap.Get() };
m_pCommandList->SetDescriptorHeaps(1, ppHeaps);

    CD3DX12_GPU_DESCRIPTOR_HANDLE desc=  CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 0, m_nCbvSrvDescriptorSize);
    m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    //uncommenting those causes crash even though each point to a different descriptor
    //desc =CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 1, m_nCbvSrvDescriptorSize);
    //m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    //desc = CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 2, m_nCbvSrvDescriptorSize);
    //m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    m_pCommandList->Dispatch(1, 1,1);
</code>```

Now This is written the rest of the code, First to define the descriptor table

```<code>CD3DX12_DESCRIPTOR_RANGE uavTable;
    uavTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
        3,
        0
);
CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(slotRootParameter.size(),
    slotRootParameter.data(),
    0,
    nullptr
    D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
slotRootParameter[0].InitAsDescriptorTable(1, &uavTable, D3D12_SHADER_VISIBILITY_ALL);
</code>```

Then to create the main buffer

```<code>ThrowIfFailed(m_pDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(paddedSize + sizeof(UINT),
            D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
        nullptr,
        __uuidof(ID3D12Resource),
        &MainBuffer
    ));
</code>```

and the description for each section of the buffer that I want to link to U0,U1,U2 defined in the descriptor table as

```<code>D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
    uavDesc.Format = DXGI_FORMAT_UNKNOWN;
    uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
    uavDesc.Buffer.FirstElement = 0;
    uavDesc.Buffer.NumElements = 3000;
    uavDesc.Buffer.CounterOffsetInBytes = paddedSize;//aligned to 4096
    uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
    uavDesc.Buffer.StructureByteStride = sizeof(Object1);
    CD3DX12_CPU_DESCRIPTOR_HANDLE hDescriptor(m_pCbvSrvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());

    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);

    uavDesc.Buffer.NumElements = 2000;
    uavDesc.Buffer.FirstElement = 3000;
    hDescriptor.Offset(1, m_nCbvSrvDescriptorSize);
    uavDesc.Buffer.StructureByteStride = sizeof(Object2);
    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);

    uavDesc.Buffer.FirstElement = 5000;
    hDescriptor.Offset(1, m_nCbvSrvDescriptorSize);

    uavDesc.Buffer.StructureByteStride = sizeof(float);
    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);
</code>```

The paddedSize is the aligned sum of objects sizes multiplied by their buffer length

and a shader that output any values  with structures like

```<code>RWStructuredBuffer <Object1> FirstBuffer:register(u0);
RWStructuredBuffer<Object2> SecondBuffer:register(u1);
RWStructuredBuffer<float> ThirdBuffer:register(u2);
</code>```

Well when I pass dummy data in the first buffer I can see that the buffer is empty and when I output anything from the buffer after the shader is done it is also empty.
So what am I doing wrong?

答:
CD3DX12_GPU_DESCRIPTOR_HANDLE desc=  CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 0, m_nCbvSrvDescriptorSize);
m_pCommandList->SetComputeRootDescriptorTable(0, desc);
//uncommenting those causes crash even though each point to a different descriptor
//desc =CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 1, m_nCbvSrvDescriptorSize);
//m_pCommandList->SetComputeRootDescriptorTable(1, desc);
//desc = CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 2, m_nCbvSrvDescriptorSize);
//m_pCommandList->SetComputeRootDescriptorTable(2, desc);
m_pCommandList->Dispatch(1, 1,1);

should give different indexes to root desc table enty in command list.

Body:
How to link one UAV descriptor table with a multiple ranges(u0,u1,u2) to the compute Shader

I can make a buffer for each of them and it would work but, I can't seem to figure out how to make it work using multiple ranges.

SetComputeRootDescriptorTable(RootParameterIndex,BaseDescriptor) Takes only these two inputs, This is how I attempted to compute it, so naturally I though I will link the three descriptors as commented below, but the app crash, so I commented the code that cause the crash.

ThrowIfFailed(m_pCommandAllocator->Reset());
    ThrowIfFailed(m_pCommandList->Reset(m_pCommandAllocator.Get(), m_pPipelineState["CSPSO"].Get()));

    m_pCommandList->SetComputeRootSignature(m_pCSRootSig.Get());
D3D12_GPU_DESCRIPTOR_HANDLE pComputeGPUHeapOffset= m_pCbvSrvDescriptorHeap->GetGPUDescriptorHandleForHeapStart();

ID3D12DescriptorHeap* ppHeaps[] = { m_pCbvSrvDescriptorHeap.Get() };
m_pCommandList->SetDescriptorHeaps(1, ppHeaps);

    CD3DX12_GPU_DESCRIPTOR_HANDLE desc=  CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 0, m_nCbvSrvDescriptorSize);
    m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    //uncommenting those causes crash even though each point to a different descriptor
    //desc =CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 1, m_nCbvSrvDescriptorSize);
    //m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    //desc = CD3DX12_GPU_DESCRIPTOR_HANDLE(pComputeGPUHeapOffset, 2, m_nCbvSrvDescriptorSize);
    //m_pCommandList->SetComputeRootDescriptorTable(0, desc);
    m_pCommandList->Dispatch(1, 1,1);

Now This is written the rest of the code, First to define the descriptor table

CD3DX12_DESCRIPTOR_RANGE uavTable;
    uavTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
        3,
        0
);
CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(slotRootParameter.size(),
    slotRootParameter.data(),
    0,
    nullptr
    D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
slotRootParameter[0].InitAsDescriptorTable(1, &uavTable, D3D12_SHADER_VISIBILITY_ALL);

Then to create the main buffer

ThrowIfFailed(m_pDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(paddedSize + sizeof(UINT),
            D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
        nullptr,
        __uuidof(ID3D12Resource),
        &MainBuffer
    ));

and the description for each section of the buffer that I want to link to U0,U1,U2 defined in the descriptor table as

D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
    uavDesc.Format = DXGI_FORMAT_UNKNOWN;
    uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
    uavDesc.Buffer.FirstElement = 0;
    uavDesc.Buffer.NumElements = 3000;
    uavDesc.Buffer.CounterOffsetInBytes = paddedSize;//aligned to 4096
    uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
    uavDesc.Buffer.StructureByteStride = sizeof(Object1);
    CD3DX12_CPU_DESCRIPTOR_HANDLE hDescriptor(m_pCbvSrvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());

    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);

    uavDesc.Buffer.NumElements = 2000;
    uavDesc.Buffer.FirstElement = 3000;
    hDescriptor.Offset(1, m_nCbvSrvDescriptorSize);
    uavDesc.Buffer.StructureByteStride = sizeof(Object2);
    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);

    uavDesc.Buffer.FirstElement = 5000;
    hDescriptor.Offset(1, m_nCbvSrvDescriptorSize);

    uavDesc.Buffer.StructureByteStride = sizeof(float);
    m_pDevice->CreateUnorderedAccessView(
        MainBuffer.Get(),
        MainBuffer.Get(),
        &uavDesc,
        hDescriptor);

The paddedSize is the aligned sum of objects sizes multiplied by their buffer length

and a shader that output any values  with structures like

RWStructuredBuffer <Object1> FirstBuffer:register(u0);
RWStructuredBuffer<Object2> SecondBuffer:register(u1);
RWStructuredBuffer<float> ThirdBuffer:register(u2);

Well when I pass dummy data in the first buffer I can see that the buffer is empty and when I output anything from the buffer after the shader is done it is also empty.
So what am I doing wrong?


来源: stackexchange

问:
Create a link in Existing PDF Using iText 5.5.13.2
How to add an external link in PDF and redirect to the webpage.
.
.
.

example image describe below

On click on Goolge,user should redirect to webpage https://www.google.com

here is my code

```<code>private void createPDFiText() {
        int margin = getResources().getDimensionPixelSize(R.dimen._5sdp);
        Document document = new Document(PageSize.A4, margin, margin, margin, margin);

        try {
            PdfWriter.getInstance(document, getOutputStream());
            document.open();

            for (int i = 12; i <= 17; i++) {

                Phrase phrase = new Phrase("Open ");
                Phrase phrase1 = new Phrase(" on Click On it.");

                Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 25);
                anchorFont.setColor(BaseColor.BLUE);
                anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

                Anchor anchor = new Anchor("Google", anchorFont);
                anchor.setReference("www.google.com");

                phrase.add(anchor);
                phrase.add(phrase1);

                document.add(phrase);

            }
            document.close();

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }

    }
</code>```

答:
I am referring to this answer. Have a look. Modifying existing pdf file using iText 5.5.13.2 is complicated. But the referred solution is more easier.
iText 7 has handier way to modify existing pdf.
There are several other ways. Like PdfStamper etc.

From referred answer, add following code to make an anchor.

```<code>Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");

Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");

phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);
</code>```

Change the font and colors based on your needs.

Full code:

```<code>try {
    PdfReader reader = new PdfReader("test.pdf"); //src pdf path (the pdf I need to modify)

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test2.pdf")); // destination pdf path
    document.open();

    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page = writer.getImportedPage(reader, 1);

    document.newPage();
    document.setPageSize(reader.getPageSize(1));

    cb.addTemplate(page, 0, 0);

    Phrase phrase = new Phrase("Open ");
    Phrase phrase1 = new Phrase(" on Click On it.");
    Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
    anchorFont.setColor(BaseColor.BLUE);
    anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

    Anchor anchor = new Anchor("Google", anchorFont);
    anchor.setReference("https://www.google.com");

    phrase.add(anchor);
    phrase.add(phrase1);
    document.add(phrase);

    document.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to add an external link in PDF and redirect to the webpage.
.
.
.

example image describe below

On click on Goolge,user should redirect to webpage https://www.google.com

here is my code

private void createPDFiText() {
        int margin = getResources().getDimensionPixelSize(R.dimen._5sdp);
        Document document = new Document(PageSize.A4, margin, margin, margin, margin);

        try {
            PdfWriter.getInstance(document, getOutputStream());
            document.open();

            for (int i = 12; i <= 17; i++) {

                Phrase phrase = new Phrase("Open ");
                Phrase phrase1 = new Phrase(" on Click On it.");

                Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 25);
                anchorFont.setColor(BaseColor.BLUE);
                anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

                Anchor anchor = new Anchor("Google", anchorFont);
                anchor.setReference("www.google.com");

                phrase.add(anchor);
                phrase.add(phrase1);

                document.add(phrase);

            }
            document.close();

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }

    }

Body:
I am referring to this answer. Have a look. Modifying existing pdf file using iText 5.5.13.2 is complicated. But the referred solution is more easier.
iText 7 has handier way to modify existing pdf.
There are several other ways. Like PdfStamper etc.

From referred answer, add following code to make an anchor.

Phrase phrase = new Phrase("Open ");
Phrase phrase1 = new Phrase(" on Click On it.");

Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
anchorFont.setColor(BaseColor.BLUE);
anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

Anchor anchor = new Anchor("Google", anchorFont);
anchor.setReference("www.google.com");

phrase.add(anchor);
phrase.add(phrase1);
document.add(phrase);

Change the font and colors based on your needs.

Full code:

try {
    PdfReader reader = new PdfReader("test.pdf"); //src pdf path (the pdf I need to modify)

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("test2.pdf")); // destination pdf path
    document.open();

    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page = writer.getImportedPage(reader, 1);

    document.newPage();
    document.setPageSize(reader.getPageSize(1));

    cb.addTemplate(page, 0, 0);

    Phrase phrase = new Phrase("Open ");
    Phrase phrase1 = new Phrase(" on Click On it.");
    Font anchorFont = new Font(Font.FontFamily.UNDEFINED, 11);
    anchorFont.setColor(BaseColor.BLUE);
    anchorFont.setStyle(Font.FontStyle.UNDERLINE.getValue());

    Anchor anchor = new Anchor("Google", anchorFont);
    anchor.setReference("https://www.google.com");

    phrase.add(anchor);
    phrase.add(phrase1);
    document.add(phrase);

    document.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}


问:
Where can I find custom UITabBarSystemItem icons?
Is there a resource out there some place that has custom UITabBarSystemItem icons that others can use. I know you get some from Apple to start, but I would imagine there are a lot more that are very common. I don't see a reason for each person to recreate the wheel for things like home, settings, etc... </p>

答:
Here is a list of some great resources I found. I have no connection with any of these sites just some resources I think are useful.

Collections:

Free:

App bits

The working group

Axialis Software

Free and paid:

Glyphish

PixelPress

Tabs Icons

Paid:

Kombine

eddit

app-icons.com

Icons Berlin

Create your own:

Icons Berlin Online Builder

speckyboy.com

Tutorial using Illustrator

Tutorial using Omnigraffle

Tutorial using Photoshop

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
MS Office Automation: Get notified (Event) when a macro runs
I'm developing an MS Office (Excel, Word, PowerPoint and Outlook) Add-in using C#/.NET, which tracks and logs some events when occurred as DocumentOpen, DocumentContentChange..etc However, and after days of searching, I'm unable to find a way (an event) to get notified when a macro is run on an Excel Workbook, Word Document.. etc

The hard way is to try to catch all the possible paths the user can follow to run a macro, using Mouse & Keyboard Hooking Win API, which are:

Using the "Macros" Dialog (using purely Win API for accessing the window): OnClick, If this is the ActiveWindow, and "Run" button has the
    focus, read the value in the TextBox under "Macro name:" label, but
    I found this approach to be very complex since there are some cases
    like: the user press ENTER and the focus is not on the "Run" button
    or if the user DoubleClick on an item in the list of macros which run the macro..

Pressing a combination of keys: ex a macro has a Ctrl+F8 key associated with it.

Click on a shape (mostly excel): check if this shape has a macro attached to it.

I can see that these approaches are very limited.

Have you got better suggestions?

答:
Please see the events logged under "application and service logs" (separate from "windows logs"), then "Microsoft Office alerts".

There are different types of alerts, including these related to macros - perhaps you will find there the information you seek.

Please let us know about the results. This is not very well documented event storage.


问:
One method in many Tasks async/await
Hi I have a case where I need to call the same method in multiple Tasks. I want to have a possibility to call this method one by one (sync) not in parallel mode. It looks like that:

```<code>var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}
</code>```

output:

Try to refresh: 1

Try to refresh: 2

my required output:

Try to refresh: 1 OR Try to refresh 2. Depends which task has been called as first one.

Any ideas?

答: Why do they need to be in seperate tasks if you don't want them to run in parallel, await means the code will no progress any further than after the task completes, because of cooperative threading the thread that initiated it may be used to do something else, like process more using interaction, or other tasks, in fact because you have them in seperate task you are asking for them to be run in parallel, its possible the block that contains them will enter the very bringing and you will have another two task, in which case you need to wait on a result from them container task saying they have completed, and the code that entered the block checks this to continue any further.</p>

Title: One method in many Tasks async/await

Body:
Hi I have a case where I need to call the same method in multiple Tasks. I want to have a possibility to call this method one by one (sync) not in parallel mode. It looks like that:

var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}

output:

Try to refresh: 1

Try to refresh: 2

my required output:

Try to refresh: 1 OR Try to refresh 2. Depends which task has been called as first one.

Any ideas?


问:
how to use mutiple login with java and database
I am fail on one section of an project given to me in which I have to create a one login for two different types of user which will display two different menus depending on which login is used. I am using NetBeans IDE and database

The two different types of user are manager and Worker and they must login using a username and password. The manager menu must have the following menu options after logging in:

1 Setup Worker files
2 View Worker files
3 Move Worker files
4 Add workers files
5 update workers files
The Worker menu must have the following menu options after logging in:

1 View workers files

And when the manager move or add or update the file automatically changed to the workers menu

答:
If you're using Java and want to work with databases, look at the Spring Framework suite (more specifically Spring Boot).

As for working with the login functionality, implementation will vary but never ever ever store plain text passwords in a database


问:
How do I change the perl regex for code formatting?
I am trying to understand the below code. But I am not getting it.
Basically, the below code currently checks for if condition in a c or cpp file.

```<code>if ($perl_version_ok &&
    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
    # Throw error
}
</code>```

where Constant is any macro or any constant value; LvalOrFunc is any variable or function call; Compare is the operations like !=, == ,&& , etc

The if checks for codes like this if(CONST_VALUE == x), where CONST_VALUE is some macros. In this case its true and goes inside if condition.

But I want to check for the opposite if(x == CONST_VALUE ), and then throw error.

Please help in understanding this piece of line and how to achieve the desired result.

Note:
The code is from linux kernel dir, available here: https://github.com/torvalds/linux/blob/master/scripts/checkpatch.pl

Line number of the code: 5483

答:
The code doesn't check for if(CONST_VALUE == x). As shown in the comments above the line in the source code

```<code># comparisons with a constant or upper case identifier on the left
#   avoid cases like "foo + BAR < baz"
#   only fix matches surrounded by parentheses to avoid incorrect
#   conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
</code>```

it checks for a plus sign followed by a CONSTANT_VALUE == x. The \+ in the regex matches a plus sign.

```<code>$line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/
      ^   ^ ^  ^  ^
      |   | |  |  |
binding   | |  |  word
operator  | |  |  boundary
      start |  |
  of string |  |
         plus  |
        anything
</code>```

Reverting the compared values should be easy:

```<code>($LvalOrFunc)\s*($Compare)\s*($Constant|[A-Z_][A-Z0-9_]*)
</code>```

Body:
I am trying to understand the below code. But I am not getting it.
Basically, the below code currently checks for if condition in a c or cpp file.

if ($perl_version_ok &&
    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
    # Throw error
}

where Constant is any macro or any constant value; LvalOrFunc is any variable or function call; Compare is the operations like !=, == ,&& , etc

The if checks for codes like this if(CONST_VALUE == x), where CONST_VALUE is some macros. In this case its true and goes inside if condition.

But I want to check for the opposite if(x == CONST_VALUE ), and then throw error.

Please help in understanding this piece of line and how to achieve the desired result.

Note:
The code is from linux kernel dir, available here: https://github.com/torvalds/linux/blob/master/scripts/checkpatch.pl

Line number of the code: 5483

Body:
The code doesn't check for if(CONST_VALUE == x). As shown in the comments above the line in the source code

# comparisons with a constant or upper case identifier on the left
#   avoid cases like "foo + BAR < baz"
#   only fix matches surrounded by parentheses to avoid incorrect
#   conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"

it checks for a plus sign followed by a CONSTANT_VALUE == x. The \+ in the regex matches a plus sign.

$line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/
      ^   ^ ^  ^  ^
      |   | |  |  |
binding   | |  |  word
operator  | |  |  boundary
      start |  |
  of string |  |
         plus  |
        anything

Reverting the compared values should be easy:

($LvalOrFunc)\s*($Compare)\s*($Constant|[A-Z_][A-Z0-9_]*)


问:
Flutter Gridview in Column. What's solution..?
I have a problem with gridview and column. In this case, i want put an image in upper of gridview. Please give me a solution..

```<code>return new Container(
  child: new Column(
    children: <Widget>[
      new Container(
        child: new Image.asset(
          "assets/promo.png",
          fit: BoxFit.cover,
        ),
      ),
      new Container(
        child: new GridView.count(
          crossAxisCount: 2,
          childAspectRatio: (itemWidth / itemHeight),
          controller: new ScrollController(keepScrollOffset: false),
          shrinkWrap: true,
          scrollDirection: Axis.vertical,
          children: new List<Widget>.generate(16, (index) {
            return new GridTile(
                header: new Container(
                  padding: const EdgeInsets.all(10.0),
                  alignment: Alignment.centerRight,
                  child: new Icon(
                    Icons.shopping_cart,
                    size: 20.0,
                    color: Colors.red,
                  ),
                ),
                child: new MyList(
                  nomor: '$index',
                ));
          }),
        ),
      ),
    ],
  ),
);
</code>```

and this is the result:
Flutter Gridview in Column

答:
Inside your Gridview make sure to add this 2 properties.</p>
```<code>physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
</code>```

Body:
I have a problem with gridview and column. In this case, i want put an image in upper of gridview. Please give me a solution..

return new Container(
  child: new Column(
    children: <Widget>[
      new Container(
        child: new Image.asset(
          "assets/promo.png",
          fit: BoxFit.cover,
        ),
      ),
      new Container(
        child: new GridView.count(
          crossAxisCount: 2,
          childAspectRatio: (itemWidth / itemHeight),
          controller: new ScrollController(keepScrollOffset: false),
          shrinkWrap: true,
          scrollDirection: Axis.vertical,
          children: new List<Widget>.generate(16, (index) {
            return new GridTile(
                header: new Container(
                  padding: const EdgeInsets.all(10.0),
                  alignment: Alignment.centerRight,
                  child: new Icon(
                    Icons.shopping_cart,
                    size: 20.0,
                    color: Colors.red,
                  ),
                ),
                child: new MyList(
                  nomor: '$index',
                ));
          }),
        ),
      ),
    ],
  ),
);

and this is the result:
Flutter Gridview in Column

Body:
Inside your Gridview make sure to add this 2 properties.

physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,


问:
Pass props in Link react-router
I am using react with react-router.
I am trying to pass property’s in a "Link" of react-router

```<code>var React  = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');

var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
  render : function(){
    return(
      <div>
        <Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
        <RouteHandler/>
      </div>
    );
  }
});

var routes = (
  <Route name="app" path="/" handler={App}>
    <Route name="ideas" handler={CreateIdeaView} />
    <DefaultRoute handler={Home} />
  </Route>
);

Router.run(routes, function(Handler) {

  React.render(<Handler />, document.getElementById('main'))
});
</code>```

The "Link" renders the page but does not pass the property to the new view.
Below is the view code

```<code>var React = require('react');
var Router = require('react-router');

var CreateIdeaView = React.createClass({
  render : function(){
    console.log('props form link',this.props,this)//props not recived
  return(
      <div>
        <h1>Create Post: </h1>
        <input type='text' ref='newIdeaTitle' placeholder='title'></input>
        <input type='text' ref='newIdeaBody' placeholder='body'></input>
      </div>
    );
  }
});

module.exports = CreateIdeaView;
</code>```

How can I pass data using "Link"?

答:
Inside your Link component do the state

```<code><Link to='register' state={{name:'zayne'}}>
</code>```

Now to access the item in the page you went to, import useLocation

```<code>import {useLocation} from 'react-router-dom';

const Register=()=>{

const location = useLocation()

//store the state in a variable if you want
//location.state then the property or object you want

const Name = location.state.name

return(
  <div>
    hello my name is {Name}
  </div>
)

}

</code>```

Title: Pass props in Link react-router

Body:
I am using react with react-router.
I am trying to pass property’s in a "Link" of react-router

var React  = require('react');
var Router = require('react-router');
var CreateIdeaView = require('./components/createIdeaView.jsx');

var Link = Router.Link;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
  render : function(){
    return(

        <Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
        <RouteHandler/>

    );
  }
});

var routes = (
  <Route name="app" path="/" handler={App}>
    <Route name="ideas" handler={CreateIdeaView} />
    <DefaultRoute handler={Home} />
  </Route>
);

Router.run(routes, function(Handler) {

  React.render(<Handler />, document.getElementById('main'))
});

The "Link" renders the page but does not pass the property to the new view.
Below is the view code

var React = require('react');
var Router = require('react-router');

var CreateIdeaView = React.createClass({
  render : function(){
    console.log('props form link',this.props,this)//props not recived
  return(

Create Post:

        <input type='text' ref='newIdeaTitle' placeholder='title'></input>
        <input type='text' ref='newIdeaBody' placeholder='body'></input>

    );
  }
});

module.exports = CreateIdeaView;

How can I pass data using "Link"?

Body:
Inside your Link component do the state

<Link to='register' state={{name:'zayne'}}>

Now to access the item in the page you went to, import useLocation

import {useLocation} from 'react-router-dom';

const Register=()=>{

const location = useLocation()

//store the state in a variable if you want
//location.state then the property or object you want

const Name = location.state.name

return(
  <div>
    hello my name is {Name}
  </div>
)

}


问:
C# Word OpenXml SDK - Adding text to a run trims spaces
I'm trying to add text runs to an existing paragraph in Word using the OpenXml SDK, but every time I do this it ends up "trimming" the text which I add.

For example

```<code> Run newRun = newRun();
 newRun.AppendChild(new Text("Hello "));
 paragraph.AppendChild(newRun);

 Run newRun = newRun();
 newRun.AppendChild(new Text(" World"));
 paragraph.AppendChild(newRun);

 // the resulting paragraph contains "HelloWorld" as the text

</code>```

I've also checked the XML of the resulting Run which gets generated, which clearly includes the "space" character:

```<code><w:t xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">Hello  </w:t>
</code>```

I've tried injecting '\u0020' unicode values, as well as an "empty" run which just contains a single space, but nothing seems to work.

Does anyone know the trick to this?

答:
Rolling my eyes at how typical that I find the answer 5 minutes after posting (having been trying for hours)

The answer is to add the XML xml:space="preserve" attribute to the Text element, otherwise spaces are trimmed.

```<code>newRun.InnerXml = $"<w:t xml:space=\"preserve\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">{text}</w:t>";
</code>```

Body:
I'm trying to add text runs to an existing paragraph in Word using the OpenXml SDK, but every time I do this it ends up "trimming" the text which I add.

For example

 Run newRun = newRun();
 newRun.AppendChild(new Text("Hello "));
 paragraph.AppendChild(newRun);

 Run newRun = newRun();
 newRun.AppendChild(new Text(" World"));
 paragraph.AppendChild(newRun);

 // the resulting paragraph contains "HelloWorld" as the text

I've also checked the XML of the resulting Run which gets generated, which clearly includes the "space" character:

<w:t xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">Hello  </w:t>

I've tried injecting '\u0020' unicode values, as well as an "empty" run which just contains a single space, but nothing seems to work.

Does anyone know the trick to this?

Body:
Rolling my eyes at how typical that I find the answer 5 minutes after posting (having been trying for hours)

The answer is to add the XML xml:space="preserve" attribute to the Text element, otherwise spaces are trimmed.

newRun.InnerXml = $"<w:t xml:space=\"preserve\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">{text}</w:t>";


问:
An array to vx_image
I would like to create a vx_image out of an array. Let us say i have 2D array:

```<code>unsigned char img_array[720][1280]={{..},{..}, ... }   // filled with values
</code>```

I would like to make it

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

so that i can perform various pixel level operations. Any other idea to do the same thing would also be fine.

答: You can use the method vxCreateImageFromHandle to create a vx_image from externally allocated memory: https://www.khronos.org/registry/OpenVX/specs/1.1/html/df/d09/group__group__image.html#ga5abb694617a79024621e3ba95237a109.

Title: An array to vx_image

Body:
I would like to create a vx_image out of an array. Let us say i have 2D array:

unsigned char img_array[720][1280]={{..},{..}, ... }   // filled with values

I would like to make it

vx_image

so that i can perform various pixel level operations. Any other idea to do the same thing would also be fine.


问:
Swift custom toggle style freezes UI
I would like to create a view with a list of checkboxes which I can select independently and keep track of these changes in an array. I have implemented some code to try and achieve this however Im experiencing weird behaviour where the screen freezes as a result of this code. Im still new to SwiftUI and reactive programming so I'm not sure if I am missusing reactive components.

When selecting the checkboxes the screen freezes and from there onwards I'm unable to click anything on the screen.

Entity

```<code>class Entity: Identifiable, Codable, Equatable {

    var id = UUID()
    let name: String
    var enabled: Bool

    init(name: String, enabled: Bool) {
        self.name = name
        self.enabled = enabled
    }

    static func == (lhs: Entity, rhs: Entity) -> Bool {
        lhs.id == rhs.id
    }
}

</code>```

MyToggleStyle1

```<code>struct MyToggleStyle1: ToggleStyle {
    func makeBody(configuration: Configuration) -> some View {
        return HStack {
            configuration.label
            Image(systemName: configuration.isOn ? "checkmark.square" : "square")
                .resizable()
                .foregroundColor(configuration.isOn ? .green : .red)
                .frame(width: 22, height: 22)
                .onTapGesture { configuration.isOn.toggle() }
        }
    }
}
</code>```

EntitySelectorView

```<code>struct EntitySelectorView: View {
    @State var customArray: [Entity] = [Entity(name: "All entities", enabled: false),
                                          Entity(name: "Boston Merchandising", enabled: false),
                                             Entity(name: "Canns & Co", enabled: false),
                                             Entity(name: "Sterling Auto Spares", enabled: false),
                                             Entity(name: "Compendia Bioscience Life Technologies", enabled: true),
                                             Entity(name: "Boston Consulting Group", enabled: false)]

    var body: some View {
        VStack(spacing: 0) {
            ScrollView(.vertical, showsIndicators: false) {
                    VStack{
                        ForEach($customArray) { $entity in
                            HStack {
                                Toggle(isOn: $entity.enabled) {
                                    Text(entity.name)
                                        .foregroundColor(Colors.darkTextColor.color)
                                        .font(.system(size: 16, weight: entity.name == "All entities" ? .bold : .regular, design: .default))
                                }
                                .toggleStyle(MyToggleStyle1())

                                Spacer()
                            }.padding(.top, 12)
                        }

                        Spacer()
                    }
                }

            Spacer()
        }.padding()
    }
}

</code>```

答:
It is about model: 1st - it must be value, and 2nd - equatable should depend on any changed property.

Here is fixed part. Tested with Xcode 13.2 / iOS 15.2

```<code>struct Entity: Identifiable, Codable, Equatable {   // << here !!

    var id = UUID()
    let name: String
    var enabled: Bool

    init(name: String, enabled: Bool) {
        self.name = name
        self.enabled = enabled
    }

    static func == (lhs: Entity, rhs: Entity) -> Bool {
        lhs.id == rhs.id && lhs.enabled == rhs.enabled   // << here !!
    }
}
</code>```

Title: Swift custom toggle style freezes UI

Body:
I would like to create a view with a list of checkboxes which I can select independently and keep track of these changes in an array. I have implemented some code to try and achieve this however Im experiencing weird behaviour where the screen freezes as a result of this code. Im still new to SwiftUI and reactive programming so I'm not sure if I am missusing reactive components.

When selecting the checkboxes the screen freezes and from there onwards I'm unable to click anything on the screen.

Entity

class Entity: Identifiable, Codable, Equatable {

    var id = UUID()
    let name: String
    var enabled: Bool

    init(name: String, enabled: Bool) {
        self.name = name
        self.enabled = enabled
    }

    static func == (lhs: Entity, rhs: Entity) -> Bool {
        lhs.id == rhs.id
    }
}

MyToggleStyle1

struct MyToggleStyle1: ToggleStyle {
    func makeBody(configuration: Configuration) -> some View {
        return HStack {
            configuration.label
            Image(systemName: configuration.isOn ? "checkmark.square" : "square")
                .resizable()
                .foregroundColor(configuration.isOn ? .green : .red)
                .frame(width: 22, height: 22)
                .onTapGesture { configuration.isOn.toggle() }
        }
    }
}

EntitySelectorView

struct EntitySelectorView: View {
    @State var customArray: [Entity] = [Entity(name: "All entities", enabled: false),
                                          Entity(name: "Boston Merchandising", enabled: false),
                                             Entity(name: "Canns & Co", enabled: false),
                                             Entity(name: "Sterling Auto Spares", enabled: false),
                                             Entity(name: "Compendia Bioscience Life Technologies", enabled: true),
                                             Entity(name: "Boston Consulting Group", enabled: false)]

    var body: some View {
        VStack(spacing: 0) {
            ScrollView(.vertical, showsIndicators: false) {
                    VStack{
                        ForEach($customArray) { $entity in
                            HStack {
                                Toggle(isOn: $entity.enabled) {
                                    Text(entity.name)
                                        .foregroundColor(Colors.darkTextColor.color)
                                        .font(.system(size: 16, weight: entity.name == "All entities" ? .bold : .regular, design: .default))
                                }
                                .toggleStyle(MyToggleStyle1())

                                Spacer()
                            }.padding(.top, 12)
                        }

                        Spacer()
                    }
                }

            Spacer()
        }.padding()
    }
}

Body:
It is about model: 1st - it must be value, and 2nd - equatable should depend on any changed property.

Here is fixed part. Tested with Xcode 13.2 / iOS 15.2

struct Entity: Identifiable, Codable, Equatable {   // << here !!

    var id = UUID()
    let name: String
    var enabled: Bool

    init(name: String, enabled: Bool) {
        self.name = name
        self.enabled = enabled
    }

    static func == (lhs: Entity, rhs: Entity) -> Bool {
        lhs.id == rhs.id && lhs.enabled == rhs.enabled   // << here !!
    }
}


问:
angular 5 chart.js datalabels plugin
I am having an issue getting the datalabels plugin to function correctly with my chart in my Angular 5 app.

The chart is displaying as expected with the exception of no labels are being created by the plugin.  No console errors are being generated either which seems odd.

my import section looks like:

```<code>import {Chart} from 'chart.js';
import 'chartjs-plugin-datalabels';
</code>```

My chart creation section looks like:

```<code>ngAfterViewInit() {
    this.canvas = document.getElementById(this.chartID);
    this.canvas.height = this.graphHeight;
    this.ctx = this.canvas.getContext('2d');

    this.myChart = new Chart(this.ctx, {
      type: 'horizontalBar',
      data: {
          labels: this.chartLabels,
          datasets: [{
              label: 'Percentage',
              data: this.chartValues,
              borderWidth: 1,
              backgroundColor: '#a32d31',
              datalabels: {
                align: 'end',
                anchor: 'start'
              }
          }]
      },
      options: {
        legend: {
          display: false
        },
        maintainAspectRatio: false,
        plugins: {
          datalabels: {
            color: 'white',
            font: {
              weight: 'bold'
            },
            formatter: Math.round
          }
        }
      }
    });

  }
</code>```

Is there a separate step needed at some point to register the plugin (the samples provided don't show that).  Any ideas or suggestions to get this working? The chart itself looks fine with the exception of the plugin output not being there.

答:
Ok, I'm using Angular V13 with chart.js v 3.7 and chartjs-plugin-datalabels v 2.
I struggled a lot trying to get things working. The problem was not errors, but the labels were just not appearing.
Turned out that I had to add .default to the plugin reference:

```<code>public chartPlugins = [pluginDataLabels.default];
</code>```

Now you can bind this chartPlugins variable to the canvas:

```<code> <canvas baseChart
 [data]="lineChartData"
 [options]="lineChartOptions"
 [type]="lineChartType"
 [plugins]="chartPlugins"
 (chartHover)="chartHovered($event)"
 (chartClick)="chartClicked($event)"></canvas>
</code>```

And then it works!

Title: angular 5 chart.js datalabels plugin

Body:
I am having an issue getting the datalabels plugin to function correctly with my chart in my Angular 5 app.

The chart is displaying as expected with the exception of no labels are being created by the plugin.  No console errors are being generated either which seems odd.

my import section looks like:

import {Chart} from 'chart.js';
import 'chartjs-plugin-datalabels';

My chart creation section looks like:

ngAfterViewInit() {
    this.canvas = document.getElementById(this.chartID);
    this.canvas.height = this.graphHeight;
    this.ctx = this.canvas.getContext('2d');

    this.myChart = new Chart(this.ctx, {
      type: 'horizontalBar',
      data: {
          labels: this.chartLabels,
          datasets: [{
              label: 'Percentage',
              data: this.chartValues,
              borderWidth: 1,
              backgroundColor: '#a32d31',
              datalabels: {
                align: 'end',
                anchor: 'start'
              }
          }]
      },
      options: {
        legend: {
          display: false
        },
        maintainAspectRatio: false,
        plugins: {
          datalabels: {
            color: 'white',
            font: {
              weight: 'bold'
            },
            formatter: Math.round
          }
        }
      }
    });

  }

Is there a separate step needed at some point to register the plugin (the samples provided don't show that).  Any ideas or suggestions to get this working? The chart itself looks fine with the exception of the plugin output not being there.

Body:
Ok, I'm using Angular V13 with chart.js v 3.7 and chartjs-plugin-datalabels v 2.
I struggled a lot trying to get things working. The problem was not errors, but the labels were just not appearing.
Turned out that I had to add .default to the plugin reference:

public chartPlugins = [pluginDataLabels.default];

Now you can bind this chartPlugins variable to the canvas:

 <canvas baseChart
 [data]="lineChartData"
 [options]="lineChartOptions"
 [type]="lineChartType"
 [plugins]="chartPlugins"
 (chartHover)="chartHovered($event)"
 (chartClick)="chartClicked($event)"></canvas>

And then it works!


问:
Gradle add native library dir to java.library.path (not for test but for run)
Maybe someone here can help me.
I have a Java Project in which I use Gradle and process the whole thing in IntelliJ. (Specs down below)

In my project I use JNI and write my own C++ library (.so file) which I put in a directory in my project e.g. ./native/build/lib/main/debug/libnative.so.

Now, when running my program normally in IntelliJ, I want the VM to add the path of my .so-library to the java.library.path and use it accordingly.
At the moment I have to do this for each main class individually by going to Edit Configurations and under Modify Options > Add VM Options add -Djava.library.path=...../native/build/lib/main/debug. But somehow it must be possible to set this globally for all classes in gradle, or not ?

I know you can add in gradle.build the java.library.path for tests like follows

```<code>test {
    systemProperty 'java.library.path','path/to/directory'
}
</code>```

but I don't need this for the tests but for the normal run/start of a main function in a class when clicking the green Arrow in IntelliJ. I already tried to add it in all task like follows

```<code>compileJava {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
processResources {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
classes {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
jar {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
startScripts {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
installDist {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
build {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
</code>```

but without success. Note that only in test 'systemProperty' can be used. Since in other tasks a 'No Signature Method exception' is thrown .When I try to start the program I get Exception in thread "main" java.lang.UnsatisfiedLinkError: no native in java.library.path: [/usr/java/packages/lib, /usr/lib64, /lib64, /lib, /usr/lib].

I use here simply the following class:

```<code>public class A {
    public static native void print0();

    static {
        System.loadLibrary("native");
    }

    public static void main(String[] args) {
        print0();
    }
}
</code>```

and yes, it works when i individually set -Djava.library.path... in Run Configuration

Environment:

IntelliJ IDEA Ultimate 2021.3.2

AdoptOpenJDK 11.0.11+9 hs

Gradle 7.1

答:
I simply changed my approach and am now loading my native libraries at Runtime in the class which defines the native functions using

```<code>static {
   System.load('absolute Path to .so file')
}
</code>```

Works like a charm.

Body:
Maybe someone here can help me.
I have a Java Project in which I use Gradle and process the whole thing in IntelliJ. (Specs down below)

In my project I use JNI and write my own C++ library (.so file) which I put in a directory in my project e.g. ./native/build/lib/main/debug/libnative.so.

Now, when running my program normally in IntelliJ, I want the VM to add the path of my .so-library to the java.library.path and use it accordingly.
At the moment I have to do this for each main class individually by going to Edit Configurations and under Modify Options > Add VM Options add -Djava.library.path=...../native/build/lib/main/debug. But somehow it must be possible to set this globally for all classes in gradle, or not ?

I know you can add in gradle.build the java.library.path for tests like follows

test {
    systemProperty 'java.library.path','path/to/directory'
}

but I don't need this for the tests but for the normal run/start of a main function in a class when clicking the green Arrow in IntelliJ. I already tried to add it in all task like follows

compileJava {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
processResources {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
classes {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
jar {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
startScripts {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
installDist {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
build {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}

but without success. Note that only in test 'systemProperty' can be used. Since in other tasks a 'No Signature Method exception' is thrown .When I try to start the program I get Exception in thread "main" java.lang.UnsatisfiedLinkError: no native in java.library.path: [/usr/java/packages/lib, /usr/lib64, /lib64, /lib, /usr/lib].

I use here simply the following class:

public class A {
    public static native void print0();

    static {
        System.loadLibrary("native");
    }

    public static void main(String[] args) {
        print0();
    }
}

and yes, it works when i individually set -Djava.library.path... in Run Configuration

Environment:

IntelliJ IDEA Ultimate 2021.3.2

AdoptOpenJDK 11.0.11+9 hs

Gradle 7.1

Body:
I simply changed my approach and am now loading my native libraries at Runtime in the class which defines the native functions using

static {
   System.load('absolute Path to .so file')
}

Works like a charm.


问:
Comparing two function types in typescript
I cannot understand the current behavior of typescript typing. Can someone explain why it happens?

```<code>type FunctionType = (a: number, b: number) => void;

const foo: FunctionType = (a, b) => (a + b); // No Error!
const foo2 = (a: number, b:number): void => (a + b); // Error: Type 'number' is not assignable to type 'void'.(2322)

const a = foo(1, 2);

a.toString(); // Error: Property 'toString' does not exist on type 'void'.(2339)
</code>```

Here is a playground

答:
The arrow function is returning (a + b) that's why it's complaining about void. You should do

type FunctionType = (a: number, b: number) => number;

const foo: FunctionType = (a, b) => (a + b);
const foo2 = (a: number, b:number): number => (a + b);

const a = foo(1, 2);

a.toString();
```

void is used when nothing is returned.

Body:
I cannot understand the current behavior of typescript typing. Can someone explain why it happens?

type FunctionType = (a: number, b: number) => void;

const foo: FunctionType = (a, b) => (a + b); // No Error!
const foo2 = (a: number, b:number): void => (a + b); // Error: Type 'number' is not assignable to type 'void'.(2322)

const a = foo(1, 2);

a.toString(); // Error: Property 'toString' does not exist on type 'void'.(2339)

Here is a playground

Body:
The arrow function is returning (a + b) that's why it's complaining about void. You should do

type FunctionType = (a: number, b: number) => number;

const foo: FunctionType = (a, b) => (a + b);
const foo2 = (a: number, b:number): number => (a + b);

const a = foo(1, 2);

a.toString();

void is used when nothing is returned.


问:
How to find text in a richtextbox going reverse?
I'm trying to make a search code that allows you to find text in both directions (right and left). I've already made a code that searches text to the right but, not to the left.

Example of what I'm trying to do:

example1 example2 example3 example4

Lets say I found 'example3' (going to the right) and now I need to find example2 (going to the left) How will i make that code?

Question:
How to make a code that searches text going to the left (reverse)?

Here is an example of what I've tried to do for searching text to the left:

```<code>try
{
    richTextBox1.Focus();
    richTextBox1.Find(findwhat, findPos, RichTextBoxFinds.Reverse);
    richTextBox1.Select(findPos, findwhat.Length);
    findPos += findwhat.Length;
}
catch
{
    findPos = 0;
}
</code>```

答:
Like Amritendu Mukhopadhyay say, You need use this version of "Find".

Find(String, Int32, Int32, RichTextBoxFinds)

Searches the text in a RichTextBox control for a string within a range of text within the control and with specific options applied to the search.

e.g.
richTextBoxTarget.Find(text, 0, findStart, RichTextBoxFinds.Reverse);

Body:
I'm trying to make a search code that allows you to find text in both directions (right and left). I've already made a code that searches text to the right but, not to the left.

Example of what I'm trying to do:

example1 example2 example3 example4

Lets say I found 'example3' (going to the right) and now I need to find example2 (going to the left) How will i make that code?

Question:
How to make a code that searches text going to the left (reverse)?

Here is an example of what I've tried to do for searching text to the left:

try
{
    richTextBox1.Focus();
    richTextBox1.Find(findwhat, findPos, RichTextBoxFinds.Reverse);
    richTextBox1.Select(findPos, findwhat.Length);
    findPos += findwhat.Length;
}
catch
{
    findPos = 0;
}


问:
index.php and protecting of its content
What are the chances hackers are able to download index.php file from the server (not the result, but the content of index.php file)? Do you recommend to put the content of index.php to modules/index_content.php, where modules folder is .htaccess protected AND index.php contains the only string <?php require_once('modules/index_content.php') ?> ?  Does it make sense?

答:
Chances are null. Two big exceptions though:

"Lost" machine (through SSH, FTP, etc,...)

Human mistake: If you have a script that reads files, be sure it can't be used to read your php files.

Title: index.php and protecting of its content


问:
Big O notation - python function
What is the Big O notation of this function (as a function of n = len(lst)):

```<code>def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += i
        jump = jump * 2
    return total
</code>```

I thought it was O(n*log(n)) but it's not, trying to understand why it's actually O(n)...
I'm kinda new in this so if you could also explain how you got to the answer it'll be the best! thanks

答:
You keep doubling your step: 1, 2, 4, 8, ...

So those ranges range(0, n, step) that you go through have sizes n, n/2, n/4, n/8, ... (well, approximately - rounded to ints).

The sum of those is 2n (approximately). Which is O(n).

If you didn't know that sum yet, yet, it's easy to see: You start with 0. Then n gets you halfway to 2n. Adding n/2 gets you to 1.5n, again halfway to 2n. Adding n/4 gets you to 1.75, again halfway to 2n. And so on. You only get closer and closer to 2n.

Title: Big O notation - python function

Body:
What is the Big O notation of this function (as a function of n = len(lst)):

def foo(lst):
    jump = 1
    total = 0
    while jump < len(lst):
        for i in range(0, len(lst), jump):
            total += i
        jump = jump * 2
    return total

I thought it was O(n*log(n)) but it's not, trying to understand why it's actually O(n)...
I'm kinda new in this so if you could also explain how you got to the answer it'll be the best! thanks


问:
How to destructure objects with keys names that are numbers?
I have props that need to be destructured in a component. As it comes from API, it is actually an object from which I would like to take objects from 0 to 39. However, when I try to destructure them this way:

```<code> const { 0, ...39: weatherData } = this.props;
</code>```

VSCode gives me an error of unexpected token because of the comma. How can I destructure the props without having to enumerate every single object?

答:
You can simply rename the number variables to string while destructuring to avoid the error:</p>
```<code> const { 0:newName, 39:weatherData, ...restOfData } = this.props;
</code>```

Body:
I have props that need to be destructured in a component. As it comes from API, it is actually an object from which I would like to take objects from 0 to 39. However, when I try to destructure them this way:

 const { 0, ...39: weatherData } = this.props;

VSCode gives me an error of unexpected token because of the comma. How can I destructure the props without having to enumerate every single object?

Body:
You can simply rename the number variables to string while destructuring to avoid the error:

 const { 0:newName, 39:weatherData, ...restOfData } = this.props;


问:
How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation?
How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation?
I need to run animation when scrolled to that section please help if you know any part of the problem.</p>

答:
u probably want to take a look on the Intersection Observer API which provides just that ability.

from Intersection Observer MDN documentation -

The Intersection Observer API provides a way to asynchronously observe
changes in the intersection of a target element with an ancestor
element or with a top-level document's viewport.

for more information checkout mdn's page regarding intersection observer API - https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API


问:
Kibana visualize use wild card in search bar
Is it possible to use wild card in Kibana visualize search bar.

Tried to use it like below, but did not work.

```<code>operation: "Revers" NOT file:"*Test.Revers"
</code>```

This returns 2 because there are two Revers terms ("Revers", "/test/count/Test.Revers" ) even though only one data entry is in the stats data.

The following also returns the same value as 2.

```<code>operation: "Revers"
</code>```

Stat data sample is as below.

```<code>"_source": {
  "status": 0,
  "trstime": 1819,
  "username": "test",
  "operation": "Revers",
  "file": "/test/count/Test.Revers"
}
</code>```

答:
The result given for the below query as 1 without double quotes.</p>
```<code>operation: Revers AND NOT file: *Test.Revers
</code>```

Body:
Is it possible to use wild card in Kibana visualize search bar.

Tried to use it like below, but did not work.

operation: "Revers" NOT file:"*Test.Revers"

This returns 2 because there are two Revers terms ("Revers", "/test/count/Test.Revers" ) even though only one data entry is in the stats data.

The following also returns the same value as 2.

operation: "Revers"

Stat data sample is as below.

"_source": {
  "status": 0,
  "trstime": 1819,
  "username": "test",
  "operation": "Revers",
  "file": "/test/count/Test.Revers"
}

Body:
The result given for the below query as 1 without double quotes.

operation: Revers AND NOT file: *Test.Revers


问:
Python selenium - AttributeError: 'dict' object has no attribute 'get_attribute'
I wanted to showcase selenium and instead of starting a complete Java / C# suite I wanted to quickly use Python since it can be done with a single script.

```<code>from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

print("sample test case started")
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("MyUrl")
element = driver.find_element(By.ID, "Username")
element.send_keys("MyUsername")

driver.close()
print("sample test case successfully completed")
</code>```

I am getting this error message:
AttributeError: 'dict' object has no attribute 'send_keys'

I would seam that find_element method is returning some kind of dict (Dictonary??) object instead of a selenium web element. How can I fix this??

答:
Selenium project is moving to only support W3C and Chrome (since version 75) is using W3C by default. You can run into an issue that you described, if you have old version of chromedriver and selenium >=4, which was the problem in my case. Update your chromedriver or downgrade Selenium version to <4 and it should fix your problem.

I reproduced this problem using Selenium 4.1.0 and Chromedriver 98, by disabling w3c:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("w3c", False)
driver = webdriver.Chrome(options=options)
```

So, it's another option that could lead to this error.
You can fix it by removing it or changing its value to True.

Body:
I wanted to showcase selenium and instead of starting a complete Java / C# suite I wanted to quickly use Python since it can be done with a single script.

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

print("sample test case started")
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("MyUrl")
element = driver.find_element(By.ID, "Username")
element.send_keys("MyUsername")

driver.close()
print("sample test case successfully completed")

I am getting this error message:
AttributeError: 'dict' object has no attribute 'send_keys'

I would seam that find_element method is returning some kind of dict (Dictonary??) object instead of a selenium web element. How can I fix this??

Body:
Selenium project is moving to only support W3C and Chrome (since version 75) is using W3C by default. You can run into an issue that you described, if you have old version of chromedriver and selenium >=4, which was the problem in my case. Update your chromedriver or downgrade Selenium version to <4 and it should fix your problem.

I reproduced this problem using Selenium 4.1.0 and Chromedriver 98, by disabling w3c:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("w3c", False)
driver = webdriver.Chrome(options=options)

So, it's another option that could lead to this error.
You can fix it by removing it or changing its value to True.


问:
Are C# events synchronous?
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?

答:
This is a general answer and reflects the default behavior:

Yes, it blocks the thread, if the methods subscribing to the event are not asynchronous.

They are executed one after the other. This has another twist: If one event handler throws an exception, the event handlers not yet executed will not be executed.

Having said that, every class that provides events can choose to implement its event asynchronously. IDesign provides a class called EventsHelper that simplifies this.

[Note] this link requires you to provide an e-mail address to download EventsHelper class. (I am not affiliated in any way)

Title: Are C# events synchronous?


问:
cordova - Error: Failed to fetch platform android
I installed cordova and create a new project.

But when I use this command to add android platform:

cordova platform add android

this error appears:

```<code>Error: Failed to fetch platform android
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
Error: version not found: cordova-android@5.1.0
</code>```

This is how I created the new project:

cordova create hello com.example.hello HelloWorld

And this is my SDK Manager:

But I can add ios platform (But I work on Windows)

答:
If you have a space character after the platform name, it will cause this problem.

Just remove it.

Body:
I installed cordova and create a new project.

But when I use this command to add android platform:

cordova platform add android

this error appears:

Error: Failed to fetch platform android
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
Error: version not found: cordova-android@5.1.0

This is how I created the new project:

cordova create hello com.example.hello HelloWorld

And this is my SDK Manager:

But I can add ios platform (But I work on Windows)


问:
FileProviderExtension won't be loaded in macOS 12.2
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

```<code>@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}
</code>```

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.

答:
I encountered the same problem and even opened feedback with apple.
What I figured out (after way too long pulling my hair out) is, as you write, the app group is essential.
But not only that, the Extension Info.plist key "NSExtensionFileProviderDocumentGroup" must correspond to your app group.</p>

Body:
I am new to macOS development.

I am trying to develop macOS FileProvider extension, and everything was fine until I updated my macOS from 11 to 12.2.

After updating OS, FileProvider extension won't being loaded by NSFileProviderManager.add(domain) and its completion handler returns error - NSFileProviderDomain.Error.providerNotFound

@IBAction func tapAddDomainButton(_ sender: Any) {
NSFileProviderManager.add(domain) { error in
    print("Error: \(error)") // <- Error: Optional(Error Domain=NSFileProviderErrorDomain Code=-2001 "The application cannot be used right now." UserInfo={NSLocalizedDescription=The application cannot be used right now.})
}

}

I've made a new boilerplate project with default macOS > App + 'File Provider Extension' in Xcode, and still got same error.
Same code works on macOS 11.6.1.

Weird thing is that apple sample code won't return error and still works in macOS 12.2.
I can't find any difference between my code and Apple Sample Code.

I uploaded my test project here.
Please help

Thanks in advance.

Additional info: My colleague tested in macOS 12.0.1/12.1 and my test project works fine.


问:
What is the difference between LOGGER.error(exception.getMessage()) and LOGGER.error(exception.getMessage(), exception)
Like in this picture

I know that both of them works fine but I just wanted to know how are they different from each other? PS: I am a beginner.

答:
A LogEvent can contain both a message and an exception. If you use the first form:

LOGGER.error(exception.getMessage());
```
<p>only the error message will be recorded and you'll have a similar output in your logs (depends upon the layout):</p>
```[ERROR] - Exception message.
```
<p>If you use the second form:</p>
<pre class="lang-java prettyprint-override"><code>LOGGER.error(exception.getMessage(), exception);
</code>```

you'll have both a message and an exception. This typically outputs the stack trace in the logs:

```<code>[ERROR] - Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]
</code>```

Since you can always configure Log4j 2.x to suppress stack traces from the output (see alwaysWriteExceptions in the PatternLayout documentation), the second form is always better, as it provides more information.

Remark: Since the stack trace always prints the error's message, I'd suggest a third form:

```<code>LOGGER.error("An unexpected condition occurred while performing foo: {}",
    exception.getMessage(), exception);
</code>```

This way you can explain the context, when the exception occurred:

```<code>[ERROR] - An unexpected condition occurred while performing foo: Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]
</code>```

Body:
A LogEvent can contain both a message and an exception. If you use the first form:

LOGGER.error(exception.getMessage());

only the error message will be recorded and you'll have a similar output in your logs (depends upon the layout):

[ERROR] - Exception message.

If you use the second form:

LOGGER.error(exception.getMessage(), exception);

you'll have both a message and an exception. This typically outputs the stack trace in the logs:

[ERROR] - Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]

Since you can always configure Log4j 2.x to suppress stack traces from the output (see alwaysWriteExceptions in the PatternLayout documentation), the second form is always better, as it provides more information.

Remark: Since the stack trace always prints the error's message, I'd suggest a third form:

LOGGER.error("An unexpected condition occurred while performing foo: {}",
    exception.getMessage(), exception);

This way you can explain the context, when the exception occurred:

[ERROR] - An unexpected condition occurred while performing foo: Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]


问:
How to pass javaScript variable value in asp-route-id prefix?
I've an anchor element with the attribute of asp-controller and
asp-action. I've a javaScript variable, named g_id that will call the getIdFromUrl function. This function will retrieve the id appended at the end of the url.

```<code>/User/Account/5
</code>```

For example, this function will retrieve the value of 5 from the URL. I want to assign this value to the asp-route-id. However, I am unable to do so.

```<code><a asp-action="ActivityPrice" asp-controller="Activity" asp-route-id = "g_id" class="btn btn-primary" >
Add Activity Price
</code>```

```<code>var g_id = getIdFromURL();

function getIdFromURL() {
    var urlArray = window.location.href.split('/');
    var id = urlArray[urlArray.length - 1];
    return id;
}
</code>```

答:
asp-route-id is translated to formaction. My solution is

```<code>var formActionAttr = $("#myBtn").get(0).getAttribute('formaction');
        formActionAttr = formActionAttr.replace("&", "&idLeft=" + "myValue" + "&idRight=" + "myValue" + "&");
        $("#confirmBtn").get(0).setAttribute('formaction', formActionAttr);
</code>```

Body:
I've an anchor element with the attribute of asp-controller and
asp-action. I've a javaScript variable, named g_id that will call the getIdFromUrl function. This function will retrieve the id appended at the end of the url.

/User/Account/5

For example, this function will retrieve the value of 5 from the URL. I want to assign this value to the asp-route-id. However, I am unable to do so.

Add Activity Price

var g_id = getIdFromURL();

function getIdFromURL() {
    var urlArray = window.location.href.split('/');
    var id = urlArray[urlArray.length - 1];
    return id;
}

Body:
asp-route-id is translated to formaction. My solution is

var formActionAttr = $("#myBtn").get(0).getAttribute('formaction');
        formActionAttr = formActionAttr.replace("&", "&idLeft=" + "myValue" + "&idRight=" + "myValue" + "&");
        $("#confirmBtn").get(0).setAttribute('formaction', formActionAttr);


问:
What can be the reason for Windows error ERROR_DISK_FULL (112) when opening a NTFS alternate data stream?
My application writes some bytes of data to an alternate data stream. This works fine on all but one machine (Windows Server 2003 SP2).
Instead, CreateFile returns ERROR_DISK_FULL when I try to create an alternate data stream (on the root directory). I don't find the reason for this result, because...

There's plenty of space on that drive.

The drive is NTFS formatted (due to GetVolumeInformation).

The drive supports altenate data
streams (due to GetVolumeInformation).

Edit: I can provide some more information about what the reason not is:
I added many streams on a test system which didn't show the error and wondered if the error might occur. It didn't. Instead after about 2000 Streams with long file names another error occurred and persisted: 1450 (ERROR_NO_SYSTEM_RESOURCES).

EDIT: Here is an example for one of the used file names:

```<code>char szStreamFileName[] = "C:\\:abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnoqrstuvwxyz012345";
</code>```

EDIT: Our customer uses some corporate antivirus software from Avira on this server. Maybe this is the reason (Alternate data streams can be abused by malware).

答: After opening a support ticket at MS I know that there was a readonly flag set which one only can set (and reset) with undocumented Windows functions. Nobody knows who set this flag and why, but I sent them an image of the drive (after I got the machine from our customer) and so they figured it out. We only have a workaround in our application (We use another location if we detect this error). Meanwhile we know that some of our customers have this problem.</p>

Body:
My application writes some bytes of data to an alternate data stream. This works fine on all but one machine (Windows Server 2003 SP2).
Instead, CreateFile returns ERROR_DISK_FULL when I try to create an alternate data stream (on the root directory). I don't find the reason for this result, because...

There's plenty of space on that drive.

The drive is NTFS formatted (due to GetVolumeInformation).

The drive supports altenate data
streams (due to GetVolumeInformation).

Edit: I can provide some more information about what the reason not is:
I added many streams on a test system which didn't show the error and wondered if the error might occur. It didn't. Instead after about 2000 Streams with long file names another error occurred and persisted: 1450 (ERROR_NO_SYSTEM_RESOURCES).

EDIT: Here is an example for one of the used file names:

char szStreamFileName[] = "C:\\:abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnoqrstuvwxyz012345";

EDIT: Our customer uses some corporate antivirus software from Avira on this server. Maybe this is the reason (Alternate data streams can be abused by malware).


问:
C program using BIOSDISK function for a removable disk attached with system. Check whether it is ready for access or not. Read the drive parameters
Write C language program to complete the following three tasks using BIOSDISK function.
Suppose one removable disk is attached with your system. Check whether it is ready for access or not. Show appropriate messages in either case.
Read the drive parameters of the first removable disk of the system. (The drive parameters will be returned in the buffer that is passed as a parameter). After reading, write the contents of the buffer in a file.
Format Track number 1 and set the bad-sector Flags (if bad-sectors are present) of first removable disk of your system. The remaining parameters should be as follows:
Head number = 0, Sector number = 1, Total number of sectors (nSect) = 1</p>

答:
use biosdisk(int command No, int drive No, int head No, int track No, int sector No, void *buffer);

Drive is a number that specifies which disk drive is to be used:

```<code>0 for the first floppy disk drive, 1 for the second floppy disk drive, 2 for the third, and so on.
For hard disk drives, a drive value of 0x80 specifies the first drive, 0x81 specifies the second, 0x82 the third, and so forth.
</code>```

Body:
use biosdisk(int command No, int drive No, int head No, int track No, int sector No, void *buffer);

Drive is a number that specifies which disk drive is to be used:

0 for the first floppy disk drive, 1 for the second floppy disk drive, 2 for the third, and so on.
For hard disk drives, a drive value of 0x80 specifies the first drive, 0x81 specifies the second, 0x82 the third, and so forth.


问:
How we can use onLongClick listener for bottom sheet in jetpack compose?
I am try to learn jetpack compose, and I want to apply bottom sheet for on long click listener, I have example of code below, and I try to use bottom sheet for onLongClick listener, but I have some  confused about how can I apply for row data? I had some example but I do not have an idea about this problem?</p>
```<code>@Composable
fun BSDataScreen() {
    val modalBottomSheetState = rememberModalBottomSheetState(initialValue =
 ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()

    ModalBottomSheetLayout(
        sheetContent = {

            SheetScreen()
        },
        sheetState = modalBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp),
        sheetBackgroundColor = Color.White,

    ) {
        Scaffold(

            backgroundColor =  Color.White,
        ) {
            DataScreen(
                scope = scope, state = modalBottomSheetState)}}}

@Composable
fun DataScreen(
    scope: CoroutineScope,
    state: ModalBottomSheetState
  ) {

    val listOfData = listOf(
        Data( painterResource(R.drawable.image1)),
        Data(painterResource(R.drawable.image2)),
        Data(painterResource(R.drawable.image3),)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)

    ) {

        LazyColumn(
            modifier = Modifier

        ) {

            items(listOfData.size) { index ->
                DataListItem(listOfData[index])}}}}

@Composable
fun DataListItem(data: Data) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(

            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                .combinedClickable(
                    onLongClick= {
                scope.launch {
                    state.show()
                }},)

        ) {

            Image(
                painter = data.painter,
                contentDescription = null,)}}}

</code>```

答:
You can create a lambda onClick: (Data) -> Unit and hoist state from DataListItem to DataScreen for each item

```<code>@Composable
fun DataListItem(data: Data, onLongClick: (Data) -> Unit) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                    .combinedClickable(
                    onClick = {

                    },
                    onLongClick = {
                      onLongClick(data)
                    }
                )
        ) {
        }
    }
}
</code>```

And in DataScreen

```<code>  LazyColumn(
    modifier = Modifier

) {

    items(listOfData.size) { index ->
        DataListItem(listOfData[index]) { data: Data->
            // you can call bottom sheet or pass data if required
            scope.launch {
                state.show()
            }
        }
    }
}
</code>```

Body:
I am try to learn jetpack compose, and I want to apply bottom sheet for on long click listener, I have example of code below, and I try to use bottom sheet for onLongClick listener, but I have some  confused about how can I apply for row data? I had some example but I do not have an idea about this problem?

@Composable
fun BSDataScreen() {
    val modalBottomSheetState = rememberModalBottomSheetState(initialValue =
 ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()

    ModalBottomSheetLayout(
        sheetContent = {

            SheetScreen()
        },
        sheetState = modalBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp),
        sheetBackgroundColor = Color.White,

    ) {
        Scaffold(

            backgroundColor =  Color.White,
        ) {
            DataScreen(
                scope = scope, state = modalBottomSheetState)}}}

@Composable
fun DataScreen(
    scope: CoroutineScope,
    state: ModalBottomSheetState
  ) {

    val listOfData = listOf(
        Data( painterResource(R.drawable.image1)),
        Data(painterResource(R.drawable.image2)),
        Data(painterResource(R.drawable.image3),)

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)

    ) {

        LazyColumn(
            modifier = Modifier

        ) {

            items(listOfData.size) { index ->
                DataListItem(listOfData[index])}}}}

@Composable
fun DataListItem(data: Data) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(

            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                .combinedClickable(
                    onLongClick= {
                scope.launch {
                    state.show()
                }},)

        ) {

            Image(
                painter = data.painter,
                contentDescription = null,)}}}

Body:
You can create a lambda onClick: (Data) -> Unit and hoist state from DataListItem to DataScreen for each item

@Composable
fun DataListItem(data: Data, onLongClick: (Data) -> Unit) {

    val context = LocalContext.current

    Column(
        modifier = Modifier.padding(5.dp)
    ) {

        Row(modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                    .combinedClickable(
                    onClick = {

                    },
                    onLongClick = {
                      onLongClick(data)
                    }
                )
        ) {
        }
    }
}

And in DataScreen

  LazyColumn(
    modifier = Modifier

) {

    items(listOfData.size) { index ->
        DataListItem(listOfData[index]) { data: Data->
            // you can call bottom sheet or pass data if required
            scope.launch {
                state.show()
            }
        }
    }
}


问:
DynamoDB - SpringBoot app inside Docker Containers - Application starts delayed
so I have this docker-compose where I have my spring boot application in one container and my dynamodb in another. Everything goes well, the containers are created and started successfully, the application starts to log stuff and then I encounter a strange delay. The app is completely booted only after around 3 minutes, and after those 3 minutes it just works, the DB is connected to the app.

I've tried destroying the container and I've rebuilt the images from scratch as I thought that maybe something wrecked inside the container when I forcefully closed it, but got the same result.

Below you can see the logs of the container with the app.

Is there anything I am missing here ? Any other ideas to try ?

I see this weird closing connections log being logged 4 times. And I have no idea if it could be because of this.

Anyone knows what this java-sdk-http-connection-reaper is ?

Closing connections idle longer than 60000 MILLISECONDS

If I start the application with some IntelliJ configuration it simply starts with no delay, it connects to the dynamodb container with no issues. (see the screenshot below)

Thank you! Any help is appreciated.

答: The delay was caused because I executed the jar with java -jar. The solution was to have the entrypoint as mvn spring-boot:run</p>


答:
You are looking for IntersectionObserver:

const observer = new IntersectionObserver((nodes)=>{
    nodes.forEach(node =>
      node.target.classList.toggle('visible', node.isIntersecting)
    )
});

observer.observe(document.querySelector('.node'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node {
  width: 40px;
  height: 40px;
  background: red;
  margin: 500px;
  transition: 1s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.node.visible {
  background: lightgreen;
  border-radius: 50%;
  color: white;
}</code>```

x
```

Body:
How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation?
I need to run animation when scrolled to that section please help if you know any part of the problem.

Body:
You are looking for IntersectionObserver:

const observer = new IntersectionObserver((nodes)=>{
    nodes.forEach(node =>
      node.target.classList.toggle('visible', node.isIntersecting)
    )
});

observer.observe(document.querySelector('.node'))

.node {
  width: 40px;
  height: 40px;
  background: red;
  margin: 500px;
  transition: 1s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.node.visible {
  background: lightgreen;
  border-radius: 50%;
  color: white;
}

<div class='node'>x</div>


问:
How to access error message in the front end sent by the server?
In my node backend, this is how I send the error message to the front end:

```<code>catch (err) {
    res.status(500).json("UNEXPECTED ERROR. Please try again later.");
  }
</code>```

How do I access the error message in the backend? Is this correct?

```<code>catch (err) {
  err.response.data;
}
</code>```

答:
You can access the error message like: error.message

I have tried in typescript this worked for me.

```<code>try {
    throw new Error("UNEXPECTED ERROR. Please try again later.");
  } catch (error: any) {
    console.log(error!.message);
    return res.status(400).send(error!.message);
  }
</code>```

Body:
In my node backend, this is how I send the error message to the front end:

catch (err) {
    res.status(500).json("UNEXPECTED ERROR. Please try again later.");
  }

How do I access the error message in the backend? Is this correct?

catch (err) {
  err.response.data;
}

Body:
You can access the error message like: error.message

I have tried in typescript this worked for me.

try {
    throw new Error("UNEXPECTED ERROR. Please try again later.");
  } catch (error: any) {
    console.log(error!.message);
    return res.status(400).send(error!.message);
  }


问:
Create treemap like chart in python
I have a data frame that I would like to use to create a Treemap like chart, similar to the one in the attached image. Below is the code to generate the data followed by a code that I have tried but the treemap didn't give the desired results.

Code to generate data:

```<code>import pandas as pd

data = {'ID': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'],
        'A': [1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2],
        'B':[3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2],
        'Cat': ['UP','UP','GONE','GONE','GONE','GONE','GONE','GONE','UP','UP','GONE','MID','MID','MID']
        }

df = pd.DataFrame(data)

print (df)
</code>```

The above creates the underlying data and the below will create the counts - the aggregated version of the above data. The logic behind this aggregation is:

```<code>If A = 2 & B = 2 then Cat = MID ...
If A = 2 & B = 1 then Cat = GONE ...
If A = 1 & B = 1 then Cat = GONE ...
If A = 1 & B = 2 then Cat = GONE ...
If A = 2 OR A = 1 & B = 3 then Cat = UP
</code>```

Based on the underlying data, this will result in
4 cases for UP,
3 cases for MID and
7 cases for GONE.

```<code>data_agg = {'Cat': ['UP', 'GONE', 'MID'],
        'Count': [4, 7, 3]
        }

df_agg = pd.DataFrame(data_agg)

print (df_agg)
</code>```

I have tried using squarify to create the chart I want but it doesn't give the desired results. The squarify code I used is below:

```<code>colors=['red','green','blue']
squarify.plot(df_agg['Count'], label=df_agg['Cat'], color=colors, alpha=0.5)

squarify.plot(df_agg['Count'], label=df_agg['Cat'], color=colors, alpha=0.5)
</code>```

I need to create a chart like the last picture and any help in creating that will be greatly appreciated.
The current result I get is

The desired chart result is this, with the variables A and B showing on the Axis:

答: I suppose squarify is not the right tool for what you want, as it only allows comparing quantities by size in a fixed space (here df_agg['Count']).</p>

Title: Create treemap like chart in python

Body:
I have a data frame that I would like to use to create a Treemap like chart, similar to the one in the attached image. Below is the code to generate the data followed by a code that I have tried but the treemap didn't give the desired results.

Code to generate data:

import pandas as pd

data = {'ID': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'],
        'A': [1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2],
        'B':[3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2],
        'Cat': ['UP','UP','GONE','GONE','GONE','GONE','GONE','GONE','UP','UP','GONE','MID','MID','MID']
        }

df = pd.DataFrame(data)

print (df)

The above creates the underlying data and the below will create the counts - the aggregated version of the above data. The logic behind this aggregation is:

If A = 2 & B = 2 then Cat = MID ...
If A = 2 & B = 1 then Cat = GONE ...
If A = 1 & B = 1 then Cat = GONE ...
If A = 1 & B = 2 then Cat = GONE ...
If A = 2 OR A = 1 & B = 3 then Cat = UP

Based on the underlying data, this will result in
4 cases for UP,
3 cases for MID and
7 cases for GONE.

data_agg = {'Cat': ['UP', 'GONE', 'MID'],
        'Count': [4, 7, 3]
        }

df_agg = pd.DataFrame(data_agg)

print (df_agg)

I have tried using squarify to create the chart I want but it doesn't give the desired results. The squarify code I used is below:

colors=['red','green','blue']
squarify.plot(df_agg['Count'], label=df_agg['Cat'], color=colors, alpha=0.5)

squarify.plot(df_agg['Count'], label=df_agg['Cat'], color=colors, alpha=0.5)

I need to create a chart like the last picture and any help in creating that will be greatly appreciated.
The current result I get is

The desired chart result is this, with the variables A and B showing on the Axis:


答:
In general, events are synchronous. However there are some exceptions, such as System.Timers.Timer.Elapsed event being raised on a ThreadPool thread if SyncronisingObject is null.

Docs: http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx

Title: Are C# events synchronous?

Body:
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?


问:
async axios get call axios returns nothing
I'm trying to get the current temperature from openweathermaps using axios.

I can put my url into the browser and it works fine. But when I try do an axios call with the correct url it doesnt event call.

Here is the relevant code section:

function Overview() {
  const [temperature, setTemperature] = useState('')
  const API_KEY = '{apikey}'

  const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
      2,
    )}&appid=${API_KEY}`

    console.log('my provided url is set to:', url)

    const response = await axios.get(url)
    if (response.data) {
      setTemperature(response.data.main.temp)
    }
  }, [latitude, longitude])

  useEffect(() => {
    getTemperature().catch(console.error)
  }, [getTemperature])

  return <>{temperature ? temperature : 'no data'}</>
}
```

Any help as to where I'm going wrong would be great as I just cant see my error!

答:
It looks like your arrow function is calling itself recursively:

```<code>const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};
</code>```

Your code doesn't show where this is being called.  Probably it needs to be something like:

```<code>const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    return response.data.main.temp;
};
</code>```

Perhaps it just needs to be a one letter change:

```<code>const getTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};
</code>```

Credit to @devklick

Body:
I'm trying to get the current temperature from openweathermaps using axios.

I can put my url into the browser and it works fine. But when I try do an axios call with the correct url it doesnt event call.

Here is the relevant code section:

function Overview() {
  const [temperature, setTemperature] = useState('')
  const API_KEY = '{apikey}'

  const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
      2,
    )}&appid=${API_KEY}`

    console.log('my provided url is set to:', url)

    const response = await axios.get(url)
    if (response.data) {
      setTemperature(response.data.main.temp)
    }
  }, [latitude, longitude])

  useEffect(() => {
    getTemperature().catch(console.error)
  }, [getTemperature])

  return <>{temperature ? temperature : 'no data'}</>
}

Any help as to where I'm going wrong would be great as I just cant see my error!

Body:
It looks like your arrow function is calling itself recursively:

const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};

Your code doesn't show where this is being called.  Probably it needs to be something like:

const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    return response.data.main.temp;
};

Perhaps it just needs to be a one letter change:

const getTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};

Credit to @devklick