问:
Applying a texture to a custom effect using DirectXTK results in the texture being stretched
I'm trying to apply a custom effect using the DirectXTK. The effect is supposed to be an "unlit" shader with just one texture. But for some reason, the texture is stretched across the model. I looked in renderdoc and the texturecoordinates appear to be loaded correctly so i'm not sure what's going on.

UnlitEffect.h

```<code>#pragma once
#include <vector>
class UnlitEffect : public DirectX::IEffect, public DirectX::IEffectMatrices
{
public:
    explicit UnlitEffect(ID3D11Device* device);
    UnlitEffect() = default;
    virtual void Apply(_In_ ID3D11DeviceContext* deviceContext) override;
    virtual void GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) override;
    void SetTexture(ID3D11ShaderResourceView* value);

    void XM_CALLCONV SetWorld(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetView(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetProjection(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection) override;

    struct __declspec(align(16)) UnlitEffectConstants
    {
        DirectX::XMMATRIX MVP;
    };

    DirectX::ConstantBuffer<UnlitEffectConstants> m_constantBuffer;

protected:
    Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vs;
    Microsoft::WRL::ComPtr<ID3D11PixelShader> m_ps;
    Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_texture;
    std::vector<uint8_t> m_vsBlob;

    DirectX::SimpleMath::Matrix m_World;
    DirectX::SimpleMath::Matrix m_View;
    DirectX::SimpleMath::Matrix m_Projection;
    DirectX::SimpleMath::Matrix m_MVP;

    uint32_t m_dirtyFlags;
};
</code>```

UnlitEffect.cpp

```<code>#include "pch.h"
#include "UnlitEffect.h"
#include "ReadData.h"
namespace
{
    constexpr uint32_t DirtyConstantBuffer = 0x1;
    constexpr uint32_t DirtyMVPMatrix= 0x2;
}

UnlitEffect::UnlitEffect(ID3D11Device* device)
    :m_constantBuffer(device),m_dirtyFlags(uint32_t(-1))
{
    m_vsBlob = DX::ReadData(L"Shaders/UnlitVS.cso");

    DX::ThrowIfFailed(
        device->CreateVertexShader(m_vsBlob.data(), m_vsBlob.size(), nullptr, m_vs.ReleaseAndGetAddressOf())
    );

    auto ps_blob = DX::ReadData(L"Shaders/UnlitPS.cso");
    DX::ThrowIfFailed(
        device->CreatePixelShader(ps_blob.data(), ps_blob.size(), nullptr, m_ps.ReleaseAndGetAddressOf())
    );
}

void UnlitEffect::Apply(_In_ ID3D11DeviceContext* deviceContext)
{

    if(m_dirtyFlags & DirtyMVPMatrix)
    {
        m_MVP = m_World * m_View;
        m_MVP = m_MVP * m_Projection;

        m_dirtyFlags &= ~DirtyMVPMatrix;
        m_dirtyFlags |= DirtyConstantBuffer;
    }

    if(m_dirtyFlags & DirtyConstantBuffer)
    {
        UnlitEffectConstants constants;

        constants.MVP = m_MVP.Transpose();
        m_constantBuffer.SetData(deviceContext, constants);

        m_dirtyFlags &= ~DirtyConstantBuffer;
    }

    auto cb = m_constantBuffer.GetBuffer();

    deviceContext->VSSetConstantBuffers(0, 1, &cb);
    deviceContext->PSSetShaderResources(0, 1, m_texture.GetAddressOf());

    deviceContext->VSSetShader(m_vs.Get(), nullptr, 0);
    deviceContext->PSSetShader(m_ps.Get(), nullptr, 0);
}

void UnlitEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength)
{
    assert(pShaderByteCode != nullptr && pByteCodeLength != nullptr);
    *pShaderByteCode = m_vsBlob.data();
    *pByteCodeLength = m_vsBlob.size();
}

void UnlitEffect::SetTexture(ID3D11ShaderResourceView* value)
{
    m_texture = value;
}

void XM_CALLCONV UnlitEffect::SetWorld(DirectX::FXMMATRIX value)
{
    m_World = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetView(DirectX::FXMMATRIX value)
{
    m_View = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetProjection(DirectX::FXMMATRIX value)
{
    m_Projection = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection)
{
    m_View = view;
    m_World = world;
    m_Projection = projection;
    m_dirtyFlags |= DirtyMVPMatrix;
}
</code>```

Unlit.hlsli

```<code>#ifndef __UNLINT_HLSLI__
#define __UNLINT_HLSLI__

cbuffer UnlitConstants : register(b0)
{
    float4x4 MVP;
}

struct VSOutput
{
    float4 PositionPS : SV_Position;
    float2 TexCoord : TEXCOORD0;
};

struct VSInput
{
    float4 Position : SV_Position;
    float2 TexCoord : TEXCOORD0;
};

#endif
</code>```

UnlitPS.hlsl

```<code>#include "Unlit.hlsli"

Texture2D BaseColor : register(t0);
SamplerState SampleType : register(s0);

float4 main(VSOutput vout) : SV_TARGET0
{
    return BaseColor.Sample(SampleType, normalize(vout.TexCoord));

}
</code>```

UnlitVS.hlsl

```<code>#include "Unlit.hlsli"

VSOutput main(VSInput vin)
{
    VSOutput vout;
    vout.PositionPS = mul(vin.Position, MVP);
    vout.TexCoord = vin.TexCoord;
    return vout;

}
</code>```

here is the result

答:
Chuck Walbourn was correct. My issue was that I was normalizing my texture coordinates in the pixel shader.
The correct code is
return BaseColor.Sample(SampleType, vout.TexCoord);

Body:
I'm trying to apply a custom effect using the DirectXTK. The effect is supposed to be an "unlit" shader with just one texture. But for some reason, the texture is stretched across the model. I looked in renderdoc and the texturecoordinates appear to be loaded correctly so i'm not sure what's going on.

UnlitEffect.h

#pragma once
#include <vector>
class UnlitEffect : public DirectX::IEffect, public DirectX::IEffectMatrices
{
public:
    explicit UnlitEffect(ID3D11Device* device);
    UnlitEffect() = default;
    virtual void Apply(_In_ ID3D11DeviceContext* deviceContext) override;
    virtual void GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) override;
    void SetTexture(ID3D11ShaderResourceView* value);

    void XM_CALLCONV SetWorld(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetView(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetProjection(DirectX::FXMMATRIX value) override;
    void XM_CALLCONV SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection) override;

    struct __declspec(align(16)) UnlitEffectConstants
    {
        DirectX::XMMATRIX MVP;
    };

    DirectX::ConstantBuffer<UnlitEffectConstants> m_constantBuffer;

protected:
    Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vs;
    Microsoft::WRL::ComPtr<ID3D11PixelShader> m_ps;
    Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_texture;
    std::vector<uint8_t> m_vsBlob;

    DirectX::SimpleMath::Matrix m_World;
    DirectX::SimpleMath::Matrix m_View;
    DirectX::SimpleMath::Matrix m_Projection;
    DirectX::SimpleMath::Matrix m_MVP;

    uint32_t m_dirtyFlags;
};

UnlitEffect.cpp

#include "pch.h"
#include "UnlitEffect.h"
#include "ReadData.h"
namespace
{
    constexpr uint32_t DirtyConstantBuffer = 0x1;
    constexpr uint32_t DirtyMVPMatrix= 0x2;
}

UnlitEffect::UnlitEffect(ID3D11Device* device)
    :m_constantBuffer(device),m_dirtyFlags(uint32_t(-1))
{
    m_vsBlob = DX::ReadData(L"Shaders/UnlitVS.cso");

    DX::ThrowIfFailed(
        device->CreateVertexShader(m_vsBlob.data(), m_vsBlob.size(), nullptr, m_vs.ReleaseAndGetAddressOf())
    );

    auto ps_blob = DX::ReadData(L"Shaders/UnlitPS.cso");
    DX::ThrowIfFailed(
        device->CreatePixelShader(ps_blob.data(), ps_blob.size(), nullptr, m_ps.ReleaseAndGetAddressOf())
    );
}

void UnlitEffect::Apply(_In_ ID3D11DeviceContext* deviceContext)
{

    if(m_dirtyFlags & DirtyMVPMatrix)
    {
        m_MVP = m_World * m_View;
        m_MVP = m_MVP * m_Projection;

        m_dirtyFlags &= ~DirtyMVPMatrix;
        m_dirtyFlags |= DirtyConstantBuffer;
    }

    if(m_dirtyFlags & DirtyConstantBuffer)
    {
        UnlitEffectConstants constants;

        constants.MVP = m_MVP.Transpose();
        m_constantBuffer.SetData(deviceContext, constants);

        m_dirtyFlags &= ~DirtyConstantBuffer;
    }

    auto cb = m_constantBuffer.GetBuffer();

    deviceContext->VSSetConstantBuffers(0, 1, &cb);
    deviceContext->PSSetShaderResources(0, 1, m_texture.GetAddressOf());

    deviceContext->VSSetShader(m_vs.Get(), nullptr, 0);
    deviceContext->PSSetShader(m_ps.Get(), nullptr, 0);
}

void UnlitEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength)
{
    assert(pShaderByteCode != nullptr && pByteCodeLength != nullptr);
    *pShaderByteCode = m_vsBlob.data();
    *pByteCodeLength = m_vsBlob.size();
}

void UnlitEffect::SetTexture(ID3D11ShaderResourceView* value)
{
    m_texture = value;
}

void XM_CALLCONV UnlitEffect::SetWorld(DirectX::FXMMATRIX value)
{
    m_World = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetView(DirectX::FXMMATRIX value)
{
    m_View = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetProjection(DirectX::FXMMATRIX value)
{
    m_Projection = value;
    m_dirtyFlags |= DirtyMVPMatrix;
}

void XM_CALLCONV UnlitEffect::SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection)
{
    m_View = view;
    m_World = world;
    m_Projection = projection;
    m_dirtyFlags |= DirtyMVPMatrix;
}

Unlit.hlsli

#ifndef __UNLINT_HLSLI__
#define __UNLINT_HLSLI__

cbuffer UnlitConstants : register(b0)
{
    float4x4 MVP;
}

struct VSOutput
{
    float4 PositionPS : SV_Position;
    float2 TexCoord : TEXCOORD0;
};

struct VSInput
{
    float4 Position : SV_Position;
    float2 TexCoord : TEXCOORD0;
};

#endif

UnlitPS.hlsl

#include "Unlit.hlsli"

Texture2D BaseColor : register(t0);
SamplerState SampleType : register(s0);

float4 main(VSOutput vout) : SV_TARGET0
{
    return BaseColor.Sample(SampleType, normalize(vout.TexCoord));

}

UnlitVS.hlsl

#include "Unlit.hlsli"

VSOutput main(VSInput vin)
{
    VSOutput vout;
    vout.PositionPS = mul(vin.Position, MVP);
    vout.TexCoord = vin.TexCoord;
    return vout;

}

here is the result


来源: stackexchange

问:
Mounting .img error: wrong fs type, bad option, bad superblock on /dev/loop1, missing codepage or helper program, or other error
I tried to write a simple operating system and started with a boot.asm.
Firstly I used

```<code>#nasm boot.asm -o boot.bin
</code>```

to compile the source and then used

```<code>#dd conv=sync if=boot.bin of=os.img bs=512 count=1
</code>```

to make a .img file. I used VMware to run this img and succeeded in booting.

Now I want to add loader.bin into this .img so Firstly I use

```<code>#losetup /dev/loop1 os.img
</code>```

to set it as loop device. Then

```<code>#mount /dev/loop1 /tmp
</code>```

. However, an error occurred:

```<code>mount: /tmp: wrong fs type, bad option, bad superblock on /dev/loop1, missing codepage or helper program, or other error.
</code>```

Here are some details about os.img:

```<code>#file os.img
os.img: DOS/MBR boot sector
#fdisk -l  os.img
Disk os.img: 512 B, 512 bytes, 1 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000

Device     Boot      Start        End    Sectors   Size Id Type
os.img1          778530409 2158795926 1380265518 658.2G 42 SFS
os.img2         1145130828 2321654160 1176523333   561G 20 unknown
os.img3         1109414469 1109434509      20041   9.8M 4c unknown
</code>```

答:
You need to build the file system, run following commands one by one in bash/root.

```<code>img=diskimage.img
cd /tmp
dd if=/dev/zero of=$img bs=1048576 count=128
fdisk $img <<< $'g\nn p\n1\n2048\n+8M\nt 1\n1\nw'
# You need to change "LOADER BIN" to "LOADER.BIN" in boot.asm. Compile loader.asm to LOADER.BIN
dd if=boot.bin of=$img conv=notrunc bs=446 count=1
dd if=boot.bin of=$img conv=notrunc bs=1 count=2 skip=510 seek=510
loop=$(losetup --show -o $((2048*512)) --sizelimit $((16*1024*1024)) -f $img)
echo "loop device is $loop"
mkfs.vfat -F 16 -n "EFI System" $loop
mount=/tmp/boot; mkdir -p $mount
mount $loop $mount
cp LOADER.BIN $mount/
umount $mount
losetup -d $loop
</code>```

Now you can use diskimage.img in VMWare as floppy disk.

ContentLicense: CC BY-SA 4.0

Body:
I tried to write a simple operating system and started with a boot.asm.
Firstly I used

#nasm boot.asm -o boot.bin

to compile the source and then used

#dd conv=sync if=boot.bin of=os.img bs=512 count=1

to make a .img file. I used VMware to run this img and succeeded in booting.

Now I want to add loader.bin into this .img so Firstly I use

#losetup /dev/loop1 os.img

to set it as loop device. Then

#mount /dev/loop1 /tmp

. However, an error occurred:

mount: /tmp: wrong fs type, bad option, bad superblock on /dev/loop1, missing codepage or helper program, or other error.

Here are some details about os.img:

#file os.img
os.img: DOS/MBR boot sector
#fdisk -l  os.img
Disk os.img: 512 B, 512 bytes, 1 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000

Device     Boot      Start        End    Sectors   Size Id Type
os.img1          778530409 2158795926 1380265518 658.2G 42 SFS
os.img2         1145130828 2321654160 1176523333   561G 20 unknown
os.img3         1109414469 1109434509      20041   9.8M 4c unknown

Body:
You need to build the file system, run following commands one by one in bash/root.

img=diskimage.img
cd /tmp
dd if=/dev/zero of=$img bs=1048576 count=128
fdisk $img <<< $'g\nn p\n1\n2048\n+8M\nt 1\n1\nw'
# You need to change "LOADER BIN" to "LOADER.BIN" in boot.asm. Compile loader.asm to LOADER.BIN
dd if=boot.bin of=$img conv=notrunc bs=446 count=1
dd if=boot.bin of=$img conv=notrunc bs=1 count=2 skip=510 seek=510
loop=$(losetup --show -o $((2048*512)) --sizelimit $((16*1024*1024)) -f $img)
echo "loop device is $loop"
mkfs.vfat -F 16 -n "EFI System" $loop
mount=/tmp/boot; mkdir -p $mount
mount $loop $mount
cp LOADER.BIN $mount/
umount $mount
losetup -d $loop

Now you can use diskimage.img in VMWare as floppy disk.


问:
Kotlin - Iterate over Class properties
Quick question, let's say we have this code:

```<code>fun main() {
    val instance = Random(1, "B", 3)
    for(__?__) {
        println(__?__)
    }
}

class Random(
    val A: Int,
    val B: String,
    val C: Int,
) {}
</code>```

What should I add in places of __?__ so that the program will print out all properities of instance?

答:
Existing answer provides a solution using Java reflection. Alternatively, we can do this using the Kotlin reflection:

for (prop in Random::class.memberProperties) {
    prop.isAccessible = true
    println("${prop.name} = ${prop.get(instance)}")
}
```

Kotlin reflection works for multiplatform projects, not only for the JVM target. Also, it understands Kotlin properties, while Java does only recognize fields and methods.

Title: Kotlin - Iterate over Class properties

Body:
Quick question, let's say we have this code:

fun main() {
    val instance = Random(1, "B", 3)
    for(__?__) {
        println(__?__)
    }
}

class Random(
    val A: Int,
    val B: String,
    val C: Int,
) {}

What should I add in places of __?__ so that the program will print out all properities of instance?

Body:
Existing answer provides a solution using Java reflection. Alternatively, we can do this using the Kotlin reflection:

for (prop in Random::class.memberProperties) {
    prop.isAccessible = true
    println("${prop.name} = ${prop.get(instance)}")
}

Kotlin reflection works for multiplatform projects, not only for the JVM target. Also, it understands Kotlin properties, while Java does only recognize fields and methods.


问:
Creating a BroadcastReceiver Dynamically in Android
I am building an Android app that works by providing information via SMS to users.Users send an SMS to a predetermined number hardcoded in the APP and in turn receive a response.

To achieve this, I am using a broadcast Receiver in my Android Manifest

```<code><receiver android:name=".SMSReciever">
        <intent-filter android:priority="2">
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</code>```

If I create a new class SMSReciever, then when a response is received, I would to somehow send the information back to the activity which the user has open on the screen. Is it possible I can do this in my main activity dynamically so that the app can be made more interactive?

I have learnt about the Context.registerReciever method, but how do I mention the priority for the receiver? If the receiver does not have a higher priority, then the messaging app might stop the broadcast from reaching my app. Has anyone come across a solution for something like this?

答:
I haven't tested this myself, but I've made a quick search via Android source code.

The priority is parsed and saved into IntentFilter (see code). So you can create IntentFilter and use its setPriority() function to set priority of your broadcast receiver.

```<code> IntentFilter filter = new IntentFilter(...);
 filter.setPriority(receiverPriority);// <-----
 context.registerReceiver(filter, mBroadcastReceiver);
</code>```

Body:
I am building an Android app that works by providing information via SMS to users.Users send an SMS to a predetermined number hardcoded in the APP and in turn receive a response.

To achieve this, I am using a broadcast Receiver in my Android Manifest

<receiver android:name=".SMSReciever">
        <intent-filter android:priority="2">
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

If I create a new class SMSReciever, then when a response is received, I would to somehow send the information back to the activity which the user has open on the screen. Is it possible I can do this in my main activity dynamically so that the app can be made more interactive?

I have learnt about the Context.registerReciever method, but how do I mention the priority for the receiver? If the receiver does not have a higher priority, then the messaging app might stop the broadcast from reaching my app. Has anyone come across a solution for something like this?

Body:
I haven't tested this myself, but I've made a quick search via Android source code.

The priority is parsed and saved into IntentFilter (see code). So you can create IntentFilter and use its setPriority() function to set priority of your broadcast receiver.

 IntentFilter filter = new IntentFilter(...);
 filter.setPriority(receiverPriority);// <-----
 context.registerReceiver(filter, mBroadcastReceiver);

ContentLicense: CC BY-SA 3.0


问:
How to use Spark SQL to parse the JSON array of objects
now has JSON data as follows

```<code>{"Id":11,"data":[{"package":"com.browser1","activetime":60000},{"package":"com.browser6","activetime":1205000},{"package":"com.browser7","activetime":1205000}]}
{"Id":12,"data":[{"package":"com.browser1","activetime":60000},{"package":"com.browser6","activetime":1205000}]}
......
</code>```

This JSON is the activation time of app, the purpose of which is to analyze the total activation time of each app

I use sparK SQL to parse JSON

scala

```<code>val sqlContext = sc.sqlContext
val behavior = sqlContext.read.json("behavior-json.log")
behavior.cache()
behavior.createOrReplaceTempView("behavior")
val appActiveTime = sqlContext.sql ("SELECT data FROM behavior") // SQL query
appActiveTime.show (100100) // print dataFrame
appActiveTime.rdd.foreach(println) // print RDD
</code>```

But the printed dataFrame is like this

.

```<code>+----------------------------------------------------------------------+

| data|

+----------------------------------------------------------------------+

| [[60000, com.browser1], [12870000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1207000, com.browser]]|

| [[120000, com.browser]]|

| [[60000, com.browser1], [1204000, com.browser5]]|

| [[60000, com.browser1], [12075000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1204000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1201000, com.browser]]|

| [[1200400, com.browser5]]|

| [[60000, com.browser1], [1200400, com.browser]]|

|[[60000, com.browser1], [1205000, com.browser6], [1205000, com.browser7]]|
</code>```

.

RDD is like this

.

```<code>[WrappedArray ([60000, com.browser1], [60000, com.browser1])]

[WrappedArray ([120000, com.browser])]

[WrappedArray ([60000, com.browser1], [1204000, com.browser5])]

[WrappedArray ([12075000, com.browser], [12075000, com.browser])]
</code>```

.

And I want to turn the data into

.

```<code>Com.browser1 60000

Com.browser1 60000

Com.browser 12075000

Com.browser 12075000

...
</code>```

.

I want to turn the array elements of each line in RDD into one row. Of course, it can be another structure that is easy to analyze.

Because I only learn  spark and Scala a lot, I have try it for a long time but fail, so I hope you can guide me.

答:
For Apache spark Java we will require to do something like below:

```<code>Dataset<Row> dataDF = spark.read()
                .option("header", "true")
                .json("/file_path");
dataDF.createOrReplaceTempView("behavior");
String sqlQuery = "SELECT data from behavior";
Dataset<Row> jsonData = spark.sql(sqlQuery);
snapshot.withColumn("data", explode(jsonData.col("data"))).select("data.*").show();
</code>```

Body:
now has JSON data as follows

{"Id":11,"data":[{"package":"com.browser1","activetime":60000},{"package":"com.browser6","activetime":1205000},{"package":"com.browser7","activetime":1205000}]}
{"Id":12,"data":[{"package":"com.browser1","activetime":60000},{"package":"com.browser6","activetime":1205000}]}
......

This JSON is the activation time of app, the purpose of which is to analyze the total activation time of each app

I use sparK SQL to parse JSON

scala

val sqlContext = sc.sqlContext
val behavior = sqlContext.read.json("behavior-json.log")
behavior.cache()
behavior.createOrReplaceTempView("behavior")
val appActiveTime = sqlContext.sql ("SELECT data FROM behavior") // SQL query
appActiveTime.show (100100) // print dataFrame
appActiveTime.rdd.foreach(println) // print RDD

But the printed dataFrame is like this

.

+----------------------------------------------------------------------+

| data|

+----------------------------------------------------------------------+

| [[60000, com.browser1], [12870000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1207000, com.browser]]|

| [[120000, com.browser]]|

| [[60000, com.browser1], [1204000, com.browser5]]|

| [[60000, com.browser1], [12075000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1204000, com.browser]]|

| [[60000, com.browser1], [120000, com.browser]]|

| [[60000, com.browser1], [1201000, com.browser]]|

| [[1200400, com.browser5]]|

| [[60000, com.browser1], [1200400, com.browser]]|

|[[60000, com.browser1], [1205000, com.browser6], [1205000, com.browser7]]|

.

RDD is like this

.

[WrappedArray ([60000, com.browser1], [60000, com.browser1])]

[WrappedArray ([120000, com.browser])]

[WrappedArray ([60000, com.browser1], [1204000, com.browser5])]

[WrappedArray ([12075000, com.browser], [12075000, com.browser])]

.

And I want to turn the data into

.

Com.browser1 60000

Com.browser1 60000

Com.browser 12075000

Com.browser 12075000

...

.

I want to turn the array elements of each line in RDD into one row. Of course, it can be another structure that is easy to analyze.

Because I only learn  spark and Scala a lot, I have try it for a long time but fail, so I hope you can guide me.

Body:
For Apache spark Java we will require to do something like below:

Dataset<Row> dataDF = spark.read()
                .option("header", "true")
                .json("/file_path");
dataDF.createOrReplaceTempView("behavior");
String sqlQuery = "SELECT data from behavior";
Dataset<Row> jsonData = spark.sql(sqlQuery);
snapshot.withColumn("data", explode(jsonData.col("data"))).select("data.*").show();


问:
How to install gfortran for MacOS Monterey (version 12.2.1) M1?
I am trying to install Fortran on my MacBook MacOS Monterey (version 12.2.1) M1 chip laptop. I downloaded and installed the gfortran from this website (gfortran 12-Dec 18, 2021): https://github.com/fxcoudert/gfortran-for-macOS/releases with no issues.

I then followed the instructions on this link: https://thecoatlessprofessor.com/programming/cpp/r-compiler-tools-for-rcpp-on-macos/ and when following the steps to do a 'quick check' with C++, I receive these errors:

```<code>ld: warning: directory not found for option '-L/opt/R/arm64/gfortran/lib/gcc/aarch64-apple-darwin20.2.0/11.0.0'
ld: warning: directory not found for option '-L/opt/R/arm64/gfortran/lib'
ld: library not found for -lgfortran
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [sourceCpp_3.so] Error 1
</code>```

I attempted to solve the issue by inputted this command in terminal:

```<code>ln -s /usr/local/gfortran /opt/R/arm64
</code>```

But I received a "Permission denied" output.

There may be issues with installing gfortran on Monterey M1 chip, but I think the main problem is where my gfortran is located on my laptop. I am not sure. Does anyone have a solution as to how to relocate gfortran on my laptop through Terminal?

Much appreciated.

答:
Have you tried to install and update XCode Command Line Tools? In principle, it comes with gcc and gfortran. Once installed, you do not need to use directly XCode to run gfortran on a terminal. XCode is available from the app store.

You can also install gcc (which contain gfortran) via brew brew install gcc.

Body:
I am trying to install Fortran on my MacBook MacOS Monterey (version 12.2.1) M1 chip laptop. I downloaded and installed the gfortran from this website (gfortran 12-Dec 18, 2021): https://github.com/fxcoudert/gfortran-for-macOS/releases with no issues.

I then followed the instructions on this link: https://thecoatlessprofessor.com/programming/cpp/r-compiler-tools-for-rcpp-on-macos/ and when following the steps to do a 'quick check' with C++, I receive these errors:

ld: warning: directory not found for option '-L/opt/R/arm64/gfortran/lib/gcc/aarch64-apple-darwin20.2.0/11.0.0'
ld: warning: directory not found for option '-L/opt/R/arm64/gfortran/lib'
ld: library not found for -lgfortran
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [sourceCpp_3.so] Error 1

I attempted to solve the issue by inputted this command in terminal:

ln -s /usr/local/gfortran /opt/R/arm64

But I received a "Permission denied" output.

There may be issues with installing gfortran on Monterey M1 chip, but I think the main problem is where my gfortran is located on my laptop. I am not sure. Does anyone have a solution as to how to relocate gfortran on my laptop through Terminal?

Much appreciated.


问:
winrt IBuffer in Python
I am using winrt in python to read sensor data over Bluetooth. This returns a _winrt_Windows_Storage_Streams.IBuffer object. Does anyone know how to turn this into a nice python object?

答:
Bleak is a cross-platform Bluetooth Low Energy client Python library that may be a better solution than using the Windows runtime APIs directly. It has a simplified API and already handles the conversion of IBuffer to bytearray.

Under the hood, Bleak uses bleak-winrt to provide Python bindings to the Windows SDK. These bindings are automatically generated using PyWinRT.
These projects are based on the same code but have many improvements over the seemingly unmaintained winrt package from the xlang project.

The bleak-winrt bindings implement the Python buffer protocol for the IBuffer interface. So you can pass the IBuffer object directly to any Python API that uses the Python buffer protocol. For example, if the data is structured (as opposed to a stream), then struct.unpack() is probably quite useful in this case.

Title: winrt IBuffer in Python


问:
What is the meaning of multiple class methods separated by "::"?
I found this line of code where I'm working, but I don't quite understand its meaning:

```<code>virtual method1::method2::method3 f() = 0;
</code>```

In the main function, I have method1::method2::method3.g1().g2(). I really don't understand. I know method::A where A is a class.

答:
:: is a scope operator.

You may need to append multiple of them either when using nested classes (a class defined within another class) or when you use namespaces. Resolution is done the same way.

Body:
I found this line of code where I'm working, but I don't quite understand its meaning:

virtual method1::method2::method3 f() = 0;

In the main function, I have method1::method2::method3.g1().g2(). I really don't understand. I know method::A where A is a class.


问:
How can i get a specific data from my dataset using SQL and PHPmyadmin?
I'm new to sql.
I have 3 datasets ,
patient (columns : id age Zip_Code, size, weight, sex)
blood_tests (columns : test_ID, test_date, blood_sugar, laboratory_ID, patient_ID)
laboratory (columns : id, name, Zip_code, departments)

how can i get the number of patients per center ?
i did this code but it doesnt give the number per

```<code>select DISTINCT patient_ID, laboratory_ID from patient,blood_tests where patient.id = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id;
</code>```

but i don't know how to get the total number of patients per center, because some of them did more than one exam in the same center and they have done tests in many labs?

For the second question. he aks us to get the 4 tests that a specific patient carried out in a laboratory called 'NWB'.
and i did this and noticed that he is patient with and ID = 25 but how can i get that without specifying that the id is 25.

```<code>select patient_ID, laboratory.name from patient, blood_tests,laboratory where patient_ID = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id HAVING laboratory.name = "NWB";
</code>```

Thank You in advance.

答:
This query will give you the number of distinct patients that had a blood test done for each laboratory.  The query GROUPs all the records with the same laboratory_ID and then counts the number of DISTINCT patients per GROUP.  Distinct in this case means that each patient is only counted once per GROUP even if there are multiple records with the same patient_ID and laboratory_ID.  However the patient can still be counted in other GROUPs.

```<code>SELECT laboratory_ID, COUNT(DISTINCT patient_ID)
FROM blood_tests
GROUP BY laboratory_ID;
</code>```

You could join the laboratory table to show the name of the laboratory instead of the id.

```<code>SELECT laboratory.nom, COUNT(DISTINCT blood_tests.patient_ID)
FROM blood_tests
JOIN laboratory ON laboratory.id = blood_tests.laboratory_ID
GROUP BY blood_tests.laboratory_ID;
</code>```

Your other question is confusing because there is no 'the' test for a patient having carried out 4 tests.  There would be 4 tests - which one of them is 'the' test.

Here is a query that will list the ids of all patients that have had 4 test carried out at the laboratory with the id 42.

```<code>SELECT patient_ID
FROM blood_tests
WHERE laboratory_ID = 42
GROUP BY patient_ID
HAVING COUNT(patient_ID) = 4;
</code>```

EDIT based on comment from OP:

I hope this is useful for anyone trying to learn how to query a database.

When you query a database your asking it for information based on what is found in the database not based on what you already know to be true.  You first need to figure out what it is that you are asking.

If you say you know that there is some (some means at least one) specific patient that did exactly 4 tests at laboratory NWB, you could ask the database to list all patients that carried out exactly 4 tests at laboratory NWB.

If you know the specific patient and want to get the tests then you would ask the database for all the tests carried out at at laboratory NWB for this specific patient. In this case the fact that you know there are 4 of them is not a criteria for selection, so it wouldn't appear in your query.

If you know there is some patient that did exactly 4 tests and you want to get their tests. What are you asking the database?  You could ask: Find me all tests for any patient that has done exactly 4 tests at laboratory NWB.  But if there are other patients that also had exactly 4 tests at that laboratory you would get their tests as well.

Above you saw how to group records together by a criteria and how to count the members of each group.
The HAVING clause allows you to limit results based on criteria that applies to a group.
The WHERE clause allows you to limit results based on criteria that applies to a record.

You should be able to construct a query for any of those scenarios using what was shown above.

Body:
I'm new to sql.
I have 3 datasets ,
patient (columns : id age Zip_Code, size, weight, sex)
blood_tests (columns : test_ID, test_date, blood_sugar, laboratory_ID, patient_ID)
laboratory (columns : id, name, Zip_code, departments)

how can i get the number of patients per center ?
i did this code but it doesnt give the number per

select DISTINCT patient_ID, laboratory_ID from patient,blood_tests where patient.id = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id;

but i don't know how to get the total number of patients per center, because some of them did more than one exam in the same center and they have done tests in many labs?

For the second question. he aks us to get the 4 tests that a specific patient carried out in a laboratory called 'NWB'.
and i did this and noticed that he is patient with and ID = 25 but how can i get that without specifying that the id is 25.

select patient_ID, laboratory.name from patient, blood_tests,laboratory where patient_ID = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id HAVING laboratory.name = "NWB";

Thank You in advance.

Body:
This query will give you the number of distinct patients that had a blood test done for each laboratory.  The query GROUPs all the records with the same laboratory_ID and then counts the number of DISTINCT patients per GROUP.  Distinct in this case means that each patient is only counted once per GROUP even if there are multiple records with the same patient_ID and laboratory_ID.  However the patient can still be counted in other GROUPs.

SELECT laboratory_ID, COUNT(DISTINCT patient_ID)
FROM blood_tests
GROUP BY laboratory_ID;

You could join the laboratory table to show the name of the laboratory instead of the id.

SELECT laboratory.nom, COUNT(DISTINCT blood_tests.patient_ID)
FROM blood_tests
JOIN laboratory ON laboratory.id = blood_tests.laboratory_ID
GROUP BY blood_tests.laboratory_ID;

Your other question is confusing because there is no 'the' test for a patient having carried out 4 tests.  There would be 4 tests - which one of them is 'the' test.

Here is a query that will list the ids of all patients that have had 4 test carried out at the laboratory with the id 42.

SELECT patient_ID
FROM blood_tests
WHERE laboratory_ID = 42
GROUP BY patient_ID
HAVING COUNT(patient_ID) = 4;

EDIT based on comment from OP:

I hope this is useful for anyone trying to learn how to query a database.

When you query a database your asking it for information based on what is found in the database not based on what you already know to be true.  You first need to figure out what it is that you are asking.

If you say you know that there is some (some means at least one) specific patient that did exactly 4 tests at laboratory NWB, you could ask the database to list all patients that carried out exactly 4 tests at laboratory NWB.

If you know the specific patient and want to get the tests then you would ask the database for all the tests carried out at at laboratory NWB for this specific patient. In this case the fact that you know there are 4 of them is not a criteria for selection, so it wouldn't appear in your query.

If you know there is some patient that did exactly 4 tests and you want to get their tests. What are you asking the database?  You could ask: Find me all tests for any patient that has done exactly 4 tests at laboratory NWB.  But if there are other patients that also had exactly 4 tests at that laboratory you would get their tests as well.

Above you saw how to group records together by a criteria and how to count the members of each group.
The HAVING clause allows you to limit results based on criteria that applies to a group.
The WHERE clause allows you to limit results based on criteria that applies to a record.

You should be able to construct a query for any of those scenarios using what was shown above.


问:
Problem with dynamic image in MS Access report
I have a report for printing labels on a grid of let's say 3 by 6 on A4 paper. These are peel-off labels, which can be printed either full sheet or just 1, depending on needs.

The report's record source is a query, which contains always 18 records (to cover a 3x6 grid), and 3 columns: [ID] (1-18), [LabelText], and [Path]. Out of these 18 records sometimes all 18 LabelText and Path are populated, but sometimes only the first few (and the rest is empty "" ), but also it could be that say first 4 are empty, then 6 have data and the rest 8 are empty. ID is always populated with numbers 1 to 18. This is done so that labels on A4 are not wasted.

Each printed label should contain a different image based on the file path given in column [Path]. This is achieved with the Detail On Format event

```<code>Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
   Me.Image0.Picture = Me.path
End Sub
</code>```

All works with a problem.

If all 18 labels are filled, all is correct

If say first 3 records are filled, then the first 3 labels get the correct Image, but all the rest of the 15 labels also get the last image (from label 3)

If say first 3 records are empty and the next 3 records have data and the rest is empty, then the first 3 labels have no image (as it should be) labels 4-6 have a correct image and the rest again get the last image (from label 6)

I tried many different "If/Else" options in the On Format event, but always get the same result. There must a simple solution, but I am not seeing it.

答:
As you have the path (even empty), you could use a bound image control.

Simply set its ControlSource to: Path

For an example, see the demo at my project VBA.PictureUrl.

Body:
I have a report for printing labels on a grid of let's say 3 by 6 on A4 paper. These are peel-off labels, which can be printed either full sheet or just 1, depending on needs.

The report's record source is a query, which contains always 18 records (to cover a 3x6 grid), and 3 columns: [ID] (1-18), [LabelText], and [Path]. Out of these 18 records sometimes all 18 LabelText and Path are populated, but sometimes only the first few (and the rest is empty "" ), but also it could be that say first 4 are empty, then 6 have data and the rest 8 are empty. ID is always populated with numbers 1 to 18. This is done so that labels on A4 are not wasted.

Each printed label should contain a different image based on the file path given in column [Path]. This is achieved with the Detail On Format event

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
   Me.Image0.Picture = Me.path
End Sub

All works with a problem.

If all 18 labels are filled, all is correct

If say first 3 records are filled, then the first 3 labels get the correct Image, but all the rest of the 15 labels also get the last image (from label 3)

If say first 3 records are empty and the next 3 records have data and the rest is empty, then the first 3 labels have no image (as it should be) labels 4-6 have a correct image and the rest again get the last image (from label 6)

I tried many different "If/Else" options in the On Format event, but always get the same result. There must a simple solution, but I am not seeing it.


问:
Custom sound push notification does not work (Flutter)
```<code>{
  "to": "XXXX",
  "notification": {
    "title": "ASAP Alert",
    "body": "Please open your app"
  },
  "data": {
    "screen": "/Nexpage1",
    "sound": "alarm",
    "click_action": "FLUTTER_NOTIFICATION_CLICK"
  }
}
</code>```

Above is my payload for the push notification. I have insert the alarm.mp3 file inside the raw folder, however it still does not give me the alarm sound, i have try for alarm.mp3 also, is there anything wrong with the json? of it because of the code on my dart file?

答:
For the people who try to make custom sound for both android and ios good guide here:

For iOS:

To add a custom sound for iOS, add the audio clip for iOS to your
project's App_Resources/iOS/ directory (iOS only accepts .wav, .aiff,
and .caf extensions).

For Android:

First, add the audio clip to your project's
App_Resources/Android/src/main/res/raw/ directory ((Android only
accepts .wav, .mp3 and .ogg extensions).

So we can use .wav file in order to use custom sound available for both platform:

```<code>"notification": {
            "body": "Test notification",
            "title": "Test Test Test",
            "click_action": "FLUTTER_NOTIFICATION_CLICK",

            "sound": "your_custom_sound.wav"
            "android_channel_id": "channel_id_youcreated",
},

          'to':
              "",
        },
</code>```

Body:
{
  "to": "XXXX",
  "notification": {
    "title": "ASAP Alert",
    "body": "Please open your app"
  },
  "data": {
    "screen": "/Nexpage1",
    "sound": "alarm",
    "click_action": "FLUTTER_NOTIFICATION_CLICK"
  }
}

Above is my payload for the push notification. I have insert the alarm.mp3 file inside the raw folder, however it still does not give me the alarm sound, i have try for alarm.mp3 also, is there anything wrong with the json? of it because of the code on my dart file?

Body:
For the people who try to make custom sound for both android and ios good guide here:

For iOS:

To add a custom sound for iOS, add the audio clip for iOS to your
project's App_Resources/iOS/ directory (iOS only accepts .wav, .aiff,
and .caf extensions).

For Android:

First, add the audio clip to your project's
App_Resources/Android/src/main/res/raw/ directory ((Android only
accepts .wav, .mp3 and .ogg extensions).

So we can use .wav file in order to use custom sound available for both platform:

"notification": {
            "body": "Test notification",
            "title": "Test Test Test",
            "click_action": "FLUTTER_NOTIFICATION_CLICK",

            "sound": "your_custom_sound.wav"
            "android_channel_id": "channel_id_youcreated",
},

          'to':
              "",
        },


问:
How to use basic deleteview
I start use DeleteView of django.views.generic.

However I am still confused about DeleteView

Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView

So,,,,is this correct??

It doesn't delete the item.

in urls.py

```<code>path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(),
     name="pre-action-delete"),
</code>```

in views.py

```<code>class PreActionDeleteView(LoginRequiredMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def delete(self, request, *args, **kwargs):
        success_url = self.get_success_url()
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return HttpResponseRedirect(success_url)
</code>```

答:
Don't override delete() method. It's much clearer to do such things in form_valid():

```<code>from django.contrib.messages.views import SuccessMessageMixin

class BookDeleteView(SuccessMessageMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def form_valid(self, form):
        data_to_return = super().form_valid(form)
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return data_to_return
</code>```

Just in case, you usually need to return super() of the method, that is normally in the View.

Also you don't need to use return HttpResponseRedirect(success_url), because it's standard behaviour of DeleteView to redirect to success_url.

Title: How to use basic deleteview

Body:
I start use DeleteView of django.views.generic.

However I am still confused about DeleteView

Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView

So,,,,is this correct??

It doesn't delete the item.

in urls.py

path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(),
     name="pre-action-delete"),

in views.py

class PreActionDeleteView(LoginRequiredMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def delete(self, request, *args, **kwargs):
        success_url = self.get_success_url()
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return HttpResponseRedirect(success_url)

Body:
Don't override delete() method. It's much clearer to do such things in form_valid():

from django.contrib.messages.views import SuccessMessageMixin

class BookDeleteView(SuccessMessageMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def form_valid(self, form):
        data_to_return = super().form_valid(form)
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return data_to_return

Just in case, you usually need to return super() of the method, that is normally in the View.

Also you don't need to use return HttpResponseRedirect(success_url), because it's standard behaviour of DeleteView to redirect to success_url.


问:
How to run JUnit tests with Gradle?
Currently I have the following build.gradle file:

```<code>apply plugin: 'java'

sourceSets {
    main {
        java {
            srcDir 'src/model'
        }
    }
}

dependencies {
    compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
    runtime fileTree(dir: 'libs', include: '*.jar')
}
</code>```

This build.gradle file is for my repository here. All of my main files are in src/model/ and their respective tests are in test/model.

How do I add a JUnit 4 dependency correctly and then run those tests in the folders of tests/model?

答:
This is for Kotlin DSL (build.gradle.kts) and using JUnit 5 (JUnit platform):

tasks.test {
    // Discover and execute JUnit4-based tests
    useJUnit()

    // Discover and execute TestNG-based tests
    useTestNG()

    // Discover and execute JUnit Platform-based (JUnit 5, JUnit Jupiter) tests
    // Note that JUnit 5 has the ability to execute JUnit 4 tests as well
    useJUnitPlatform()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
    // ...
}
```

Title: How to run JUnit tests with Gradle?

Body:
Currently I have the following build.gradle file:

apply plugin: 'java'

sourceSets {
    main {
        java {
            srcDir 'src/model'
        }
    }
}

dependencies {
    compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
    runtime fileTree(dir: 'libs', include: '*.jar')
}

This build.gradle file is for my repository here. All of my main files are in src/model/ and their respective tests are in test/model.

How do I add a JUnit 4 dependency correctly and then run those tests in the folders of tests/model?


问:
PHP 8.1: strftime() is deprecated
When upgrading to PHP 8.1, I got an error regarding "strftime".
How do I correct the code to correctly display the full month name in any language?</p>
```<code> $date = strftime("%e %B %Y", strtotime('2010-01-08'))
</code>```

答:
A quick and simple replacement for the deprecated function strftime can be following.

Instead of using (taking the sample from the question)

$date = strftime("%e %B %Y", strtotime('2010-01-08'))

convert that to:

$date = date('d M Y', strtotime('2010-01-08')

Title: PHP 8.1: strftime() is deprecated

Body:
When upgrading to PHP 8.1, I got an error regarding "strftime".
How do I correct the code to correctly display the full month name in any language?

 $date = strftime("%e %B %Y", strtotime('2010-01-08'))


问:
React/node build error. Could not find a declaration file for module 'history'. 'node_modules/history/index.js' implicitly has an 'any' type
My project is suddenly having a build error. My current repo still has no problem, it only happens when I clone the repo to a new folder and install the package again then do npm run build.
So I am so scared to update the package right now...

I checked the merge history, I don't think any code merge should cause this issue..

Here is the error message I got:

```<code>$ npm run build

> container-client@2.32.0 build I:\ds\projects\new\container-service\client
> craco build

Creating an optimized production build...
Failed to compile.

I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx
TypeScript error in I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx(4,25):
Could not find a declaration file for module 'history'. 'I:/ds/projects/new/container-service/client/node_modules/history/index.js' implicitly has an 'any' type.
  If the 'history' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/history`  TS7016

    2 | import './_index.scss';
    3 | import store from '../../store';
  > 4 | import { History } from 'history';
      |                         ^

</code>```

This is the package.json:

```<code>  {
  "private": false,
  "dependencies": {
    "axios": "^0.19.2",
    "bootstrap": "^4.6.0",
    "history": "^4.10.1",
    "identity-obj-proxy": "^3.0.0",
    "react": "~17.0.1",
    "react-app-polyfill": "~2.0.0",
    "react-dom": "~17.0.1",
    "react-router-dom": "~5.2.0"
  },

Looks like the library "history" is causing the problem.

</code>```

I tried:

delete the node_module --> npm install --> npm run build --> same error

clone the project again --> npm install --> npm run build --> same error

clone the older version of the project --> npm install --> npm run build --> same error

Nothing seems to work.

答: Looks like the new history needs a dependency library @types/history.  I did a npm i @types/history@4.7.9 and then did a npm i again.  This fixed my problem.

Body:
My project is suddenly having a build error. My current repo still has no problem, it only happens when I clone the repo to a new folder and install the package again then do npm run build.
So I am so scared to update the package right now...

I checked the merge history, I don't think any code merge should cause this issue..

Here is the error message I got:

$ npm run build

> container-client@2.32.0 build I:\ds\projects\new\container-service\client
> craco build

Creating an optimized production build...
Failed to compile.

I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx
TypeScript error in I:/ds/projects/new/container-service/client/src/views/add-application/AddApplicationPage.tsx(4,25):
Could not find a declaration file for module 'history'. 'I:/ds/projects/new/container-service/client/node_modules/history/index.js' implicitly has an 'any' type.
  If the 'history' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/history`  TS7016

    2 | import './_index.scss';
    3 | import store from '../../store';
  > 4 | import { History } from 'history';
      |                         ^

This is the package.json:

  {
  "private": false,
  "dependencies": {
    "axios": "^0.19.2",
    "bootstrap": "^4.6.0",
    "history": "^4.10.1",
    "identity-obj-proxy": "^3.0.0",
    "react": "~17.0.1",
    "react-app-polyfill": "~2.0.0",
    "react-dom": "~17.0.1",
    "react-router-dom": "~5.2.0"
  },

Looks like the library "history" is causing the problem.

I tried:

delete the node_module --> npm install --> npm run build --> same error

clone the project again --> npm install --> npm run build --> same error

clone the older version of the project --> npm install --> npm run build --> same error

Nothing seems to work.


问:
split background into 3 divs flippable
I'm trying to apply a background into my html/css website but I also want to split this background into 3 divs who can flip when the cursor is hover.

So I guess the best to do could be to make 3 divs side by side (the total size of my screen) then to apply 3 backgrounds to these 3 divs but each of them are a different part of my background image.

Is anyone here can show me how to do that with a snippet please ?

答:
Flipping with backside content

/* css reset */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  min-height: 100vh;
  width: 100%;
}

/* ---- */

/* flexbox to place partitions beside each other */

.image-canvas {
  display: flex;
}

/* making each partition of 1/3rd width */

.image-section {
  flex-basis: calc(100% / 3);
  flex-grow: 1;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

/* image container to keep a part of the image */

.image-section .image {
  transition: transform 1s;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

/* image to span the screen width */

.image-section .image img {
  width: 100vw;
  height: 100%;
  position: absolute;
}

/* content container to span the partition width */

.image-section .content {
  width: 100%;
  height: 100%;
  background: #fff;
  /* optional centering */
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
  transition: transform 1s;
  transform: rotateY(180deg);
}

/* flip effect to image */

.image-section:hover .image {
  transform: rotateY(180deg);
}

/* reverse flip effect to content */

.image-section:hover .content {
  transform: rotate(0);
}

/* showing only a portion of the image on each partition by dragging to the desired position */

.image-section.one img {
  left: calc(-1 * ((100vw / 3)) * 0);
}

.image-section.two img {
  left: calc(-1 * ((100vw / 3)) * 1);
}

.image-section.three img {
  left: calc(-1 * ((100vw / 3)) * 2);
  /*   right: 0; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="image-canvas">
  <div class="image-section one">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part one">
    </div>
    <div class="content">
      Part one
    </div>
  </div>
  <div class="image-section two">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part two">
    </div>
    <div class="content">
      Part two
    </div>
  </div>
  <div class="image-section three">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part three">
    </div>
    <div class="content">
      Part three
    </div>
  </div>
</section></code>```

I have used the following series of steps to achieve your result:

Take a flex container.

Take a partition div with flex-basis: calc(100% / 3) inside of the container and place two elements for image and content.

Rotate the content section to 180deg and backface-visibility:hidden to hide it when the image is showing.

Apply flip effect to the image on hover, and reverse flip effect to content on the same hover.

Flipping without backside content

/* css reset */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  min-height: 100vh;
  width: 100%;
}

/* ---- */

.image-canvas {
  display: flex;
  height: 100vh;
}

.image-section {
  flex-basis: calc(100% / 3);
  flex-grow: 1;
  height: 100vh;
  overflow: hidden;
  position: relative;
  transition: transform 1s;
  /*   backface-visibility: hidden; */
}

.image-section img {
  width: 100vw;
  height: 100vh;
  position: absolute;
}

.image-section:hover {
  transform: rotateY(180deg);
}

.image-section.one img {
  left: calc(-1 * ((100vw / 3)) * 0);
}

.image-section.two img {
  left: calc(-1 * ((100vw / 3)) * 1);
}

.image-section.three img {
  left: calc(-1 * ((100vw / 3)) * 2);
  /* right: 0; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="image-canvas">
  <div class="image-section one">
    <img src="https://picsum.photos/536/354" alt="Partition 1">
  </div>
  <div class="image-section two">
    <img src="https://picsum.photos/536/354" alt="Partition 2">
  </div>
  <div class="image-section three">
    <img src="https://picsum.photos/536/354" alt="Partition 3">
  </div>
</section></code>```

I have used the following series of steps to achieve your result:

Take a container and set it to full width of the screen.

Place three divs with one-third width of the total width inside of the container.

Make the container flex to place the partitions beside each other.

Place an img with the same src inside each of the partitions spanning the width of the screen.

Pull the second image by 100vw / 3 from the left.

Pull the third image by (100vw / 3) * 2 from left (or 0 from right).

Apply flip effect using transform: rotateY(180deg) and animation effect using transition: transform 1s to the images.

References:

Flexbox

Transition

Transform

Position

calc()

Backface visibility

Title: split background into 3 divs flippable

Body:
Flipping with backside content

/* css reset */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  min-height: 100vh;
  width: 100%;
}

/* ---- */

/* flexbox to place partitions beside each other */

.image-canvas {
  display: flex;
}

/* making each partition of 1/3rd width */

.image-section {
  flex-basis: calc(100% / 3);
  flex-grow: 1;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

/* image container to keep a part of the image */

.image-section .image {
  transition: transform 1s;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

/* image to span the screen width */

.image-section .image img {
  width: 100vw;
  height: 100%;
  position: absolute;
}

/* content container to span the partition width */

.image-section .content {
  width: 100%;
  height: 100%;
  background: #fff;
  /* optional centering */
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
  transition: transform 1s;
  transform: rotateY(180deg);
}

/* flip effect to image */

.image-section:hover .image {
  transform: rotateY(180deg);
}

/* reverse flip effect to content */

.image-section:hover .content {
  transform: rotate(0);
}

/* showing only a portion of the image on each partition by dragging to the desired position */

.image-section.one img {
  left: calc(-1 * ((100vw / 3)) * 0);
}

.image-section.two img {
  left: calc(-1 * ((100vw / 3)) * 1);
}

.image-section.three img {
  left: calc(-1 * ((100vw / 3)) * 2);
  /*   right: 0; */
}

<section class="image-canvas">
  <div class="image-section one">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part one">
    </div>
    <div class="content">
      Part one
    </div>
  </div>
  <div class="image-section two">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part two">
    </div>
    <div class="content">
      Part two
    </div>
  </div>
  <div class="image-section three">
    <div class="image">
      <img src="https://picsum.photos/536/354" alt="Part three">
    </div>
    <div class="content">
      Part three
    </div>
  </div>
</section>

I have used the following series of steps to achieve your result:

Take a flex container.

Take a partition div with flex-basis: calc(100% / 3) inside of the container and place two elements for image and content.

Rotate the content section to 180deg and backface-visibility:hidden to hide it when the image is showing.

Apply flip effect to the image on hover, and reverse flip effect to content on the same hover.

Flipping without backside content

/* css reset */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  min-height: 100vh;
  width: 100%;
}

/* ---- */

.image-canvas {
  display: flex;
  height: 100vh;
}

.image-section {
  flex-basis: calc(100% / 3);
  flex-grow: 1;
  height: 100vh;
  overflow: hidden;
  position: relative;
  transition: transform 1s;
  /*   backface-visibility: hidden; */
}

.image-section img {
  width: 100vw;
  height: 100vh;
  position: absolute;
}

.image-section:hover {
  transform: rotateY(180deg);
}

.image-section.one img {
  left: calc(-1 * ((100vw / 3)) * 0);
}

.image-section.two img {
  left: calc(-1 * ((100vw / 3)) * 1);
}

.image-section.three img {
  left: calc(-1 * ((100vw / 3)) * 2);
  /* right: 0; */
}

<section class="image-canvas">
  <div class="image-section one">
    <img src="https://picsum.photos/536/354" alt="Partition 1">
  </div>
  <div class="image-section two">
    <img src="https://picsum.photos/536/354" alt="Partition 2">
  </div>
  <div class="image-section three">
    <img src="https://picsum.photos/536/354" alt="Partition 3">
  </div>
</section>

I have used the following series of steps to achieve your result:

Take a container and set it to full width of the screen.

Place three divs with one-third width of the total width inside of the container.

Make the container flex to place the partitions beside each other.

Place an img with the same src inside each of the partitions spanning the width of the screen.

Pull the second image by 100vw / 3 from the left.

Pull the third image by (100vw / 3) * 2 from left (or 0 from right).

Apply flip effect using transform: rotateY(180deg) and animation effect using transition: transform 1s to the images.

References:

Flexbox

Transition

Transform

Position

calc()

Backface visibility


答:
:: is the scope resolution operator. It allows you to statically traverse scopes such as namespaces and classes in order to reference the identifier you want.

I think what you have is not methods but namespaces and classes.

Title: What is the meaning of multiple class methods separated by "::"?


问:
Why are my Bootstrap 5 tabs not switching when clicked?
I am very new here, and have spent some time learning HTML, CSS, and Bootstrap (5). As a starter project to practise these skills, I am attempting to replicate another website which includes (amongst other things), a tabbed section.

I followed a tutorial to create a tabbed section and have got all the content in each tab (two columns in each - one column with a picture and one column with a H3 and some text). However, when attempting to switch between tabs, the tabs won't switch.

The original tutorial was pretty minimal, and after it wouldn't work I tried searching on here and on Google. A few others suggested adding roles and aria controls to each div, which I tried but am still unsuccessful.

Please take a look and let me know what I have missed!

```<code>    <!DOCTYPE html>
<html lang="en-GB">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <Meta name="author" content="">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

        <Meta name="description" content="">
        <title>Starbucks Tabs</title>

    </head>

    <body>

      <section id="favourites">

        <div class="container-fluid favourites-header">
          <h2 class="sectionheader">Get your favourites for free</h2>
        </div>

          <div class="container">
            <ul class="nav nav-tabs" role="tablist">
              <li class="nav-item"><a class="nav-link active" id="25link" data-bs-toggle="tab" role="tab" href="#25tab" aria-controls="25tab" aria-selected="true">25*</a></li>
              <li class="nav-item"><a class="nav-link" id="50link" data-bs-toggle="tab" role="tab" href="#50tab" aria-controls="50tab" aria-selected="false">50*</a></li>
              <li class="nav-item"><a class="nav-link" id="150link" data-bs-toggle="tab" role="tab" href="#150tab" aria-controls="150tab" aria-selected="false">150*</a></li>
              <li class="nav-item"><a class="nav-link" id="200link" data-bs-toggle="tab" role="tab" href="#200tab" aria-controls="200tab" aria-selected="false">200*</a></li>
              <li class="nav-item"><a class="nav-link" id="400link" data-bs-toggle="tab" role="tab" href="#400tab" aria-controls="400tab" aria-selected="false">400*</a></li>
            </ul>

            <div class="tab-content">

              <div class="tab-pane active show fade" role="tabpanel" id="25tab"  aria-labelledby="25link">
                <div class="row">
                  <div class="col">
                    <img src="img/025.png" alt="an espresso and a latte">
                  </div>
                  <div class="col">
                    <h3>Customise your drink</h3>
                    <p>Make your drink just right with an extra espresso shot, dairy substitute or a dash of your favorite syrup.</p>
                  </div>
                </div>
              </div>

              <div class="tab-pane fade" role="tabpanel" id="50tab" aria-labelledby="50link">
                <div class="row">
                  <div class="col">
                    <img src="img/050.png" alt="a cake and a black americano">
                  </div>
                  <div class="col">
                    <h3>Brewed hot coffee, bakery item, or hot tea</h3>
                    <p>Pair coffee cake or an almond croissant with your fresh cup of hot brew.</p>
                  </div>
                </div>
              </div>

              <div class="tab-pane fade" role="tabpanel" id="150tab" aria-labelledby="150link">
                <div class="row">
                  <div class="col">
                    <img src="img/150.png" alt="a muffin, a soda, and a caramel latte">
                  </div>
                  <div class="col">
                    <h3>Handcrafted drink, hot breakfast or parfait</h3>
                    <p>Have a really good morning with a breakfast sandwich, oatmeal or your favorite drink.</p>
                  </div>
                </div>
              </div>

              <div class="tab-pane fade" role="tabpanel" id="200tab" aria-labelledby="200link">
                <div class="row">
                  <div class="col">
                    <img src="img/200.png" alt="a chicken salad and a snack box">
                  </div>
                  <div class="col">
                    <h3>Salad, sandwich, or protein box</h3>
                    <p>Nourish your day with a hearty Chipotle Chicken Wrap or Eggs & Cheese Protein Box.</p>
                  </div>
                </div>
              </div>

              <div class="tab-pane fade" role="tabpanel" id="400tab" aria-labelledby="400link">
                <div class="row">
                  <div class="col">
                    <img src="img/400.png" alt="a mug and a bag of coffee">
                  </div>
                  <div class="col">
                    <h3>Select merchandise or at-home coffee</h3>
                    <p>Take home a signature cup, a bag of coffee or your choice of select coffee accessories.</p>
                  </div>
                </div>
              </div>

            </div>
          </div>

      </section>

      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    </body>
</html>
</code>```

答: You have done everything correctly, except the id values. It should not begin with a number. You can read more about it here What are valid values for the id attribute in HTML?.

Body:
I am very new here, and have spent some time learning HTML, CSS, and Bootstrap (5). As a starter project to practise these skills, I am attempting to replicate another website which includes (amongst other things), a tabbed section.

I followed a tutorial to create a tabbed section and have got all the content in each tab (two columns in each - one column with a picture and one column with a H3 and some text). However, when attempting to switch between tabs, the tabs won't switch.

The original tutorial was pretty minimal, and after it wouldn't work I tried searching on here and on Google. A few others suggested adding roles and aria controls to each div, which I tried but am still unsuccessful.

Please take a look and let me know what I have missed!

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <Meta name="author" content="">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

        <Meta name="description" content="">
        <title>Starbucks Tabs</title>

Get your favourites for free

25*

50*

150*

200*

400*

Customise your drink

Make your drink just right with an extra espresso shot, dairy substitute or a dash of your favorite syrup.

Brewed hot coffee, bakery item, or hot tea

Pair coffee cake or an almond croissant with your fresh cup of hot brew.

Handcrafted drink, hot breakfast or parfait

Have a really good morning with a breakfast sandwich, oatmeal or your favorite drink.

Salad, sandwich, or protein box

Nourish your day with a hearty Chipotle Chicken Wrap or Eggs & Cheese Protein Box.

Select merchandise or at-home coffee

Take home a signature cup, a bag of coffee or your choice of select coffee accessories.


问:
Single Datagridview Master-Details, no error but only shows "(Collection)"
I am using SQLite and I would like to use Master-Detail in a single DataGridView.  No error return, I check the Master Table ("ASM") and the Details Table ("PART") their data are good. However, my gridAsmPart only shows one row with the word (Collection) on column PART. Any help will be appreciated.

```<code>  public void LoadData()
    {
       var asm = new SQLiteDataAdapter("SELECT * FROM ASM", dB.connectionString);
       var part = new SQLiteDataAdapter("SELECT * FROM PART", dB.connectionString);

       var ds = new DataSet();

        asm.Fill(ds, "ASM");
        part.Fill(ds, "PART");

        DataRelation data_relation = new DataRelation(
            "ASM_PART",
            ds.Tables["ASM"].Columns["PART"],
            ds.Tables["PART"].Columns["PART"]);
        ds.Relations.Add(data_relation);

        gridAsmPart.DataSource = ds;
    }
</code>```

Edit 1: It seems that if I use the old DataGrid, it works.

答:
Well… on the line of code… gridAsmPart.DataSource = ds; … ds is a DataSet and when you assign a DataSet to the grid as a DataSource, then you also need to specify “which” table in the DataSet the grid should display. That is what the grids DataMember is for.

Have you tried to set the grids DataMember property to something like…?

```<code>gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “ASM”;
</code>```

Or if you want the “Part” table to display….

```<code>gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “PART”;
</code>```

Body:
I am using SQLite and I would like to use Master-Detail in a single DataGridView.  No error return, I check the Master Table ("ASM") and the Details Table ("PART") their data are good. However, my gridAsmPart only shows one row with the word (Collection) on column PART. Any help will be appreciated.

  public void LoadData()
    {
       var asm = new SQLiteDataAdapter("SELECT * FROM ASM", dB.connectionString);
       var part = new SQLiteDataAdapter("SELECT * FROM PART", dB.connectionString);

       var ds = new DataSet();

        asm.Fill(ds, "ASM");
        part.Fill(ds, "PART");

        DataRelation data_relation = new DataRelation(
            "ASM_PART",
            ds.Tables["ASM"].Columns["PART"],
            ds.Tables["PART"].Columns["PART"]);
        ds.Relations.Add(data_relation);

        gridAsmPart.DataSource = ds;
    }

Edit 1: It seems that if I use the old DataGrid, it works.

Body:
Well… on the line of code… gridAsmPart.DataSource = ds; … ds is a DataSet and when you assign a DataSet to the grid as a DataSource, then you also need to specify “which” table in the DataSet the grid should display. That is what the grids DataMember is for.

Have you tried to set the grids DataMember property to something like…?

gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “ASM”;

Or if you want the “Part” table to display….

gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “PART”;


问:
How to turn off the ringtone programmatically?
I want to turn off the ringtone. Otherwise, at least to decrease the sound of the ring tone and to stop the vibration of the device.</p>

答: Unless you’re targeting jailbroken devices and use private, undocumented APIs, you simply can’t.</p>


问:
In R grid package , how to use viewport for merge ggplot2 plots
I want to merge geom_point() and geom_boxplot() into one plot as attached image.Below code can't work.Anyone can help on this? Thanks!

```<code>library(grid)
library(ggplot2)
grid.newpage()
vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)
push.Viewport(vp)
ggplot(mtcars) + geom_point(aes(mpg, disp))

vp_sub <- viewport(x=0.5,y=0.7,width=0.3,height=0.3)
push.viewport(vp_sub)
ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
</code>```

答:
Maybe you can use the patchwork package, there's a section that describes your problem exactly.

```<code>library(tidyverse)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + inset_element(
  p2,
  left = 0.5,
  bottom = 0.5,
  right = unit(1, 'npc') - unit(1, 'cm'),
  top = unit(1, 'npc') - unit(1, 'cm')
)
</code>```

Body:
I want to merge geom_point() and geom_boxplot() into one plot as attached image.Below code can't work.Anyone can help on this? Thanks!

library(grid)
library(ggplot2)
grid.newpage()
vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)
push.Viewport(vp)
ggplot(mtcars) + geom_point(aes(mpg, disp))

vp_sub <- viewport(x=0.5,y=0.7,width=0.3,height=0.3)
push.viewport(vp_sub)
ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

Body:
Maybe you can use the patchwork package, there's a section that describes your problem exactly.

library(tidyverse)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

p1 + inset_element(
  p2,
  left = 0.5,
  bottom = 0.5,
  right = unit(1, 'npc') - unit(1, 'cm'),
  top = unit(1, 'npc') - unit(1, 'cm')
)


问:
How to get parent div in handleChange with React
I have multiple divs that are dynamic (it depends on which filter the visitor checked). So I can not use getElementById.

I need to get the parent div to change its CSS if an input is checked.

Here is my code:

```<code>            {workout?.map(x => {
                return <div className='relative bg-gray-200 p-4 rounded-md my-3 mx-2' key={x.name}>
                    <input onClick={handleChecked} className='absolute right-0 top-0' type="checkbox" />
                    <div className='flex'>
                        <img className='w-2/6 rounded mr-5' src={`${x.path}`} alt={x.name} />
                        <div className='w-4/6'>
                            <h2 className='text-xl'>{x.name}</h2>
                            <p>Nombre de séries : {x.set}</p>
                            <p>Nombre de rép : {x.reps}</p>
                            {x.secondary ? <p>Muscles solicités : <br />
                                <span className='space-x-2'>
                                    {x?.secondary?.map(k => {
                                        return <span className='bg-white px-1 rounded-md' key={k}>{k}</span>
                                    })}
                                </span>
                            </p> : null}
                        </div>
                    </div>
                </div>
            })}
</code>```

The idea, is to add a border-2 border-teal-500 class to the parent div of the input when it is checked.

Here is my handleChecked:

  function handleChecked(e) {
    // code here
  }
```

I saw that I had to use parentNode but the problem is, I can't store in a variable the current input because it is dynamic. Every item has its own input.

Any idea how I can handle this?

答:
You shouldn't be using getElementById (or any other vanilla JS DOM method) in React anyway - store and change values in state instead. You can leverage this by making input a controlled component, and storing the checked values in an array, or in workout - then, when returning the JSX, you just need to check whether the x variable (the item being iterated over) indicates that the current input should be checked or not - which will also tell you whether the parent should have a different class.

```<code>const makeHandleChecked = (i) => (e) = {
  setWorkout(
    workout.map(
      (w, j) => j !== i ? w : { ...w, checked: e.target.checked }
    )
  );
};
</code>```
```<code>{workout?.map((x, i) => (
  <div className={`relative bg-gray-200 p-4 rounded-md my-3 mx-2${x.checked ? ' checked' : ''}`} key={x.name}>
    <input onClick={makeHandleChecked(i)} checked={x.checked} className='absolute right-0 top-0' type="checkbox" />
</code>```

Body:
I have multiple divs that are dynamic (it depends on which filter the visitor checked). So I can not use getElementById.

I need to get the parent div to change its CSS if an input is checked.

Here is my code:

            {workout?.map(x => {
                return

                    <input onClick={handleChecked} className='absolute right-0 top-0' type="checkbox" />

                        <img className='w-2/6 rounded mr-5' src={`${x.path}`} alt={x.name} />

{x.name}

Nombre de séries : {x.set}

Nombre de rép : {x.reps}

                            {x.secondary ?
Muscles solicités :

                                    {x?.secondary?.map(k => {
                                        return {k}
                                    })}

 : null}

            })}

The idea, is to add a border-2 border-teal-500 class to the parent div of the input when it is checked.

Here is my handleChecked:

  function handleChecked(e) {
    // code here
  }

I saw that I had to use parentNode but the problem is, I can't store in a variable the current input because it is dynamic. Every item has its own input.

Any idea how I can handle this?

Body:
You shouldn't be using getElementById (or any other vanilla JS DOM method) in React anyway - store and change values in state instead. You can leverage this by making input a controlled component, and storing the checked values in an array, or in workout - then, when returning the JSX, you just need to check whether the x variable (the item being iterated over) indicates that the current input should be checked or not - which will also tell you whether the parent should have a different class.

const makeHandleChecked = (i) => (e) = {
  setWorkout(
    workout.map(
      (w, j) => j !== i ? w : { ...w, checked: e.target.checked }
    )
  );
};

{workout?.map((x, i) => (
  <div className={`relative bg-gray-200 p-4 rounded-md my-3 mx-2${x.checked ? ' checked' : ''}`} key={x.name}>
    <input onClick={makeHandleChecked(i)} checked={x.checked} className='absolute right-0 top-0' type="checkbox" />


问:
Spring Boot : mapping between entity and database not working.(Getting {} in response body)
I'm trying to create a webservice but when I try to get records from database(MariaDB), the response is being shown as {} and does not show the actual fields.The code is as below.

(Imports are hidden)

Customer.java

```<code>
@AllArgsConstructor

@Data
@Entity
@Table(name ="customer")
public class Customer {
    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long customerId;

    @Column(name = "acc_holder_name")
    String accHolderName;

    @Column(name = "clear_balance")
    Long clearBalance;

    @Column(name = "over_draft")
    Boolean overDraft;

    public Customer() {}

    public Customer(Long id)
    {
        this.customerId = id;
        this.accHolderName = "default";
        this.clearBalance = (long) 0;
        this.overDraft = false;
    }

    public String toString()
    {
        return this.customerId + this.accHolderName;
    }

    public Customer(String accHolderName, long clearBalance, boolean overDraft)
    {
        this.accHolderName = accHolderName;
        this.clearBalance = clearBalance;
        this.overDraft = overDraft;
    }
}
</code>```

CustomerService.java

```<code>
@Service
public class CustomerService {
    private CustomerRepository customerRepo;

    @Autowired
    public CustomerService(CustomerRepository cr)
    {
        this.customerRepo = cr;
    }

    public List<Customer> getCustomers(){
        List<Customer> ls = customerRepo.findAll();
        return ls;
    }

}

</code>```

CustomerController.java

```<code>

@RestController
@RequestMapping("customer")
public class CustomerController {
    private CustomerService custService;

    @Autowired
    public CustomerController(CustomerService cs)
    {
        this.custService = cs;
    }
    @GetMapping
    @ResponseBody
    public List<Customer> getCustomers() {
        return custService.getCustomers();
    }
}
</code>```

application.properties

```<code>spring.datasource.url=jdbc:mariadb://localhost:3306/sample-db
spring.datasource.username=hidden
spring.datasource.password=hidden
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update
</code>```

CustomerRepostitory.java

```<code>@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {

}
</code>```

My table is  follows

```<code>+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| customer_id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| acc_holder_name | varchar(40) | YES  |     | NULL    |                |
| clear_balance   | int(11)     | YES  |     | NULL    |                |
| over_draft      | tinyint(1)  | YES  |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+
</code>```

My table has 6 records inserted. I send the following request

```<code>curl --location --request GET 'localhost:8080/customer/' \
--data-raw ''
</code>```

And get the following response

```<code>[
    {},
    {},
    {},
    {},
    {},
    {}
]
</code>```

答:
Don’t expose your JPA entities in your Rest API. It is a bad practice. Exposing your entities creates a strong coupling between your API and your persistence model.
Therefore use DTO(Data Transfer Object) to return your data. you can use model mapper to map Entity to DTO as bellows.

```<code>@Data
public class CustomerDTO {

    Long customerId;

    String accHolderName;

    Long clearBalance;

    Boolean overDraft;
}
</code>```

use bellow dependency to your pom.xml to get model mapper.

```<code><dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.4.5</version>
</dependency>
</code>```

then map an entity to DTO as follows.

```<code>public List<CustomerDTO> getCustomers(){
    List<CustomerDTO> ls = customerRepo.findAll()
                          .stream()
                          .map(customer->
                               new ModelMapper().map(page, SimpleBaseDTO.class))
                          .collect(Collectors.toList());

    return ls;
}
</code>```

Body:
I'm trying to create a webservice but when I try to get records from database(MariaDB), the response is being shown as {} and does not show the actual fields.The code is as below.

(Imports are hidden)

Customer.java

@AllArgsConstructor

@Data
@Entity
@Table(name ="customer")
public class Customer {
    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long customerId;

    @Column(name = "acc_holder_name")
    String accHolderName;

    @Column(name = "clear_balance")
    Long clearBalance;

    @Column(name = "over_draft")
    Boolean overDraft;

    public Customer() {}

    public Customer(Long id)
    {
        this.customerId = id;
        this.accHolderName = "default";
        this.clearBalance = (long) 0;
        this.overDraft = false;
    }

    public String toString()
    {
        return this.customerId + this.accHolderName;
    }

    public Customer(String accHolderName, long clearBalance, boolean overDraft)
    {
        this.accHolderName = accHolderName;
        this.clearBalance = clearBalance;
        this.overDraft = overDraft;
    }
}

CustomerService.java

@Service
public class CustomerService {
    private CustomerRepository customerRepo;

    @Autowired
    public CustomerService(CustomerRepository cr)
    {
        this.customerRepo = cr;
    }

    public List<Customer> getCustomers(){
        List<Customer> ls = customerRepo.findAll();
        return ls;
    }

}

CustomerController.java

@RestController
@RequestMapping("customer")
public class CustomerController {
    private CustomerService custService;

    @Autowired
    public CustomerController(CustomerService cs)
    {
        this.custService = cs;
    }
    @GetMapping
    @ResponseBody
    public List<Customer> getCustomers() {
        return custService.getCustomers();
    }
}

application.properties

spring.datasource.url=jdbc:mariadb://localhost:3306/sample-db
spring.datasource.username=hidden
spring.datasource.password=hidden
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update

CustomerRepostitory.java

@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {

}

My table is  follows

+-----------------+-------------+------+-----+---------+----------------+
| Field           | Type        | Null | Key | Default | Extra          |
+-----------------+-------------+------+-----+---------+----------------+
| customer_id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| acc_holder_name | varchar(40) | YES  |     | NULL    |                |
| clear_balance   | int(11)     | YES  |     | NULL    |                |
| over_draft      | tinyint(1)  | YES  |     | NULL    |                |
+-----------------+-------------+------+-----+---------+----------------+

My table has 6 records inserted. I send the following request

curl --location --request GET 'localhost:8080/customer/' \
--data-raw ''

And get the following response

[
    {},
    {},
    {},
    {},
    {},
    {}
]

Body:
Don’t expose your JPA entities in your Rest API. It is a bad practice. Exposing your entities creates a strong coupling between your API and your persistence model.
Therefore use DTO(Data Transfer Object) to return your data. you can use model mapper to map Entity to DTO as bellows.

@Data
public class CustomerDTO {

    Long customerId;

    String accHolderName;

    Long clearBalance;

    Boolean overDraft;
}

use bellow dependency to your pom.xml to get model mapper.

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.4.5</version>
</dependency>

then map an entity to DTO as follows.

public List<CustomerDTO> getCustomers(){
    List<CustomerDTO> ls = customerRepo.findAll()
                          .stream()
                          .map(customer->
                               new ModelMapper().map(page, SimpleBaseDTO.class))
                          .collect(Collectors.toList());

    return ls;
}


问:
Constraint layout with top title, recycler view and bottom button
I am trying to implement a layout, which will contain the top title, recycler view and bottom button.
Looks simple, but I need to have a wrap_content height for constraint layout to make it scalable depending on the content (top title, bottom button and recycler view. All examples that I've already found with match_parent value. Also, I need to keep the title and bottom button on the screen, where there are a lot of recycler view items. In turn recycler view must fill all available place and don't overlap title and bottom button.

So, requirements for layout:

Title is always on the screen

Bottom button is always on the screen

Constraint layout must be scalable depending on the recycler view content (picture below)

The concept:

Layout which I have now

```<code> <?xml version="1.0" encoding="utf-8"?>
   <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Title"
        android:background="@color/yellow"
        android:textAlignment="center"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="16dp"
        android:textStyle="bold" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvList"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/constraint_parent"
        app:layout_constraintBottom_toTopOf="@id/btnSave"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tvTitle"
        tools:itemCount="50" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnSave"
        android:layout_width="@dimen/constraint_parent"
        android:layout_height="wrap_content"
        android:text="Save"
        android:textSize="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Result - recycler view isn't displayed

Perhaps there is another way to do this, but I spent a lot of time looking for a solution. I believe the solution should be simple, but I haven't found one yet.
DialogFragment doesn't fit here because this screen needs to be in full-screen mode when the app is in portrait orientation.

答: Try to set android:layout_height to match_parent on your ContraintLayout.

Body:
I am trying to implement a layout, which will contain the top title, recycler view and bottom button.
Looks simple, but I need to have a wrap_content height for constraint layout to make it scalable depending on the content (top title, bottom button and recycler view. All examples that I've already found with match_parent value. Also, I need to keep the title and bottom button on the screen, where there are a lot of recycler view items. In turn recycler view must fill all available place and don't overlap title and bottom button.

So, requirements for layout:

Title is always on the screen

Bottom button is always on the screen

Constraint layout must be scalable depending on the recycler view content (picture below)

The concept:

Layout which I have now

 <?xml version="1.0" encoding="utf-8"?>
   <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Title"
        android:background="@color/yellow"
        android:textAlignment="center"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="16dp"
        android:textStyle="bold" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvList"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/constraint_parent"
        app:layout_constraintBottom_toTopOf="@id/btnSave"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tvTitle"
        tools:itemCount="50" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnSave"
        android:layout_width="@dimen/constraint_parent"
        android:layout_height="wrap_content"
        android:text="Save"
        android:textSize="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Result - recycler view isn't displayed

Perhaps there is another way to do this, but I spent a lot of time looking for a solution. I believe the solution should be simple, but I haven't found one yet.
DialogFragment doesn't fit here because this screen needs to be in full-screen mode when the app is in portrait orientation.


问:
Open .dat files with a Hex Editor
I'm trying to Open up a series of .dat files with a Hex Editor thru the vba in excel and then start a copy and paste process. Does anybody know how one can open up a file using a program other than excel inside the vba in Excel? Also I have a few errors in the code that I've written. </p>

```<code> test = count
 Do While (test >= 0)
 Workbooks.Open Filename:=AllFiles(test) 'Open .dat file in order of Highest to Lowest count index. ERROR: SUBSCRIPT OUT OF RANGE. Need to open .dat files with Hex Edit HOW?
 test = test - 1
Loop
 'How do I manipulate the Hex Editor program: HxD with vba excel??
</code>```

答:
Opening a hex editor via vba to read a file then cut/paste the file's contents seems like overkill. If all you want is to read the file's data into a variable, then try the solutions posted here: http://www.excelforum.com/excel-programming/332741-getting-text-file-into-a-vba-string-variable.html   which read a file directly into a variable, without having to resort to other apps and clipboard operations.

In essence, if you're trying to turn on a light, just flip the switch directly. Hiring/Firing someone to do it for you each time you enter/leave a room is highly inefficient.

Title: Open .dat files with a Hex Editor

Body:
I'm trying to Open up a series of .dat files with a Hex Editor thru the vba in excel and then start a copy and paste process. Does anybody know how one can open up a file using a program other than excel inside the vba in Excel? Also I have a few errors in the code that I've written.

 test = count
 Do While (test >= 0)
 Workbooks.Open Filename:=AllFiles(test) 'Open .dat file in order of Highest to Lowest count index. ERROR: SUBSCRIPT OUT OF RANGE. Need to open .dat files with Hex Edit HOW?
 test = test - 1
Loop
 'How do I manipulate the Hex Editor program: HxD with vba excel??


问:
How to get the definition of a stored procedure in a Linked Server?
I need to get the definition of a stored procedure, from another different server. When I want to see the definition locally, I can do something like:

```<code>SELECT TOP 1 *
FROM sysobjects
WHERE name = 'procedure_name'
</code>```

When I want to see how this same stored procedure is currently, I tried to do this, since it's on a linked server:

```<code>SELECT TOP 1 *
FROM [xxx.xx.xxx.xx].DBName.dbo.sysobjects
WHERE name = 'procedure_name'
</code>```

It runs okay, no error, but I get the definition of my local procedure, not the one on the remote server. Is there a way to do this? I couldn't seem to find any information about this case.

答:
You might try:

EXECUTE
(
    '
    SELECT
        OBJECT_DEFINITION(
            OBJECT_ID(N''dbo.ProcName'', ''P''))
    '
) AT [LinkedServer]
```

Body:
I need to get the definition of a stored procedure, from another different server. When I want to see the definition locally, I can do something like:

SELECT TOP 1 *
FROM sysobjects
WHERE name = 'procedure_name'

When I want to see how this same stored procedure is currently, I tried to do this, since it's on a linked server:

SELECT TOP 1 *
FROM [xxx.xx.xxx.xx].DBName.dbo.sysobjects
WHERE name = 'procedure_name'

It runs okay, no error, but I get the definition of my local procedure, not the one on the remote server. Is there a way to do this? I couldn't seem to find any information about this case.


答:
Besides patchwork::inset_element a second option would be to add your boxplot via ggplot2::annotation_custom. However, in contrast to patchwork::inset_element you have to set the positions in absolute coordinates of the data range of your main plot:

library(ggplot2)

bp <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

base <- ggplot(mtcars) +
  geom_point(aes(mpg, disp))

base +
  annotation_custom(grob = ggplotGrob(bp), xmin = 22.5, ymin = 250)
```

Title: In R grid package , how to use viewport for merge ggplot2 plots