问:
How to connect postman gRPC mock server by Android app?
I'm struggling to access postman gRPC mock server by Android/kotlin app for several days.

I created the mock server after reading official document. I got the URL for mock server and I could get a response by grpcurl and a Node.js gRPC client. However, I got a error when I used the URL by Android gRPC client.

Stacktrace is below.

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.aniokrait.grpcsample/io.github.aniokrait.grpcsample.MainActivity}: io.grpc.StatusRuntimeException: UNAVAILABLE
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE
        at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271)
        at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252)
        at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165)
        at com.book.BookServiceGrpc$BookServiceBlockingStub.getBook(BookServiceGrpc.java:312)
        at io.github.aniokrait.grpcsample.MainActivity$Companion.startGrpc(MainActivity.kt:71)
        at io.github.aniokrait.grpcsample.MainActivity$Companion.access$startGrpc(MainActivity.kt:34)
        at io.github.aniokrait.grpcsample.MainActivity.onCreate(MainActivity.kt:30)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.RuntimeException: TLS ALPN negotiation failed with protocols: [h2]
        at io.grpc.okhttp.OkHttpProtocolNegotiator.negotiate(OkHttpProtocolNegotiator.java:104)
        at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.negotiate(OkHttpProtocolNegotiator.java:218)
        at io.grpc.okhttp.OkHttpTlsUpgrader.upgrade(OkHttpTlsUpgrader.java:63)
        at io.grpc.okhttp.OkHttpClientTransport$3.run(OkHttpClientTransport.java:551)
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
</code>```

The messages says "TLS ALPN negotiation failed with protocols: [h2]", so I have an idea that the problem is around SSL/TLS, but I don't know how to solve it.

I do not think it is likely to be a certificate issue, as I am able to access the URL from Node.js and grpcurl but the issue of my Android app.

I've read tls-on-android and Update your security provider to protect against SSL exploits.

I added dependecies of play-services and installing code as below but still it doesn't work.

Here's my code.

MainActivity.kt

```<code>import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.book.BookServiceGrpc
import com.book.Index.GetBookRequest
import com.google.android.gms.security.ProviderInstaller
import io.grpc.okhttp.OkHttpChannelBuilder

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ProviderInstaller.installIfNeeded(this@MainActivity)
        startGrpc()
    }

    companion object {
        private fun startGrpc() {
            try {
                val channel = OkHttpChannelBuilder
                    .forAddress("g-95d43o92ollxvwmm7nx895731r4g9y.srv.pstmn.io",443) //URL is slightly altered to prevent tampering
                    .useTransportSecurity()
                    .build()
                val stub = BookServiceGrpc.newBlockingStub(channel)
                val request = GetBookRequest.newBuilder().setIsbn(123).build()
                val result = stub.getBook(request)
            } catch (e: Exception) {
                e.printStackTrace()
                throw e
            }

        }
    }
}
</code>```

my proto file.

```<code>syntax = "proto3";
package com.book;

message Book {
  int64 isbn = 1;
  string title = 2;
  string author = 3;
}

message GetBookRequest {
  int64 isbn = 1;
}

service BookService {
  rpc GetBook (GetBookRequest) returns (Book) {}
}
</code>```

and dependecies relevant to gRPC

```<code>dependencies {
    implementation 'io.grpc:grpc-okhttp:1.51.1'
    implementation 'io.grpc:grpc-protobuf-lite:1.51.1'
    implementation 'io.grpc:grpc-stub:1.51.1'
    implementation 'org.apache.tomcat:annotations-api:6.0.53'
    implementation 'com.google.android.gms:play-services-basement:18.1.0'
}
</code>```

Update:
I found these messages in Debug logs.

```<code>W/DynamiteModule: Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule: Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller: Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL
</code>```

Perhaps The Dynamic Security Provider isn't installed properly, but still I don't know why.

Body:
I'm struggling to access postman gRPC mock server by Android/kotlin app for several days.

I created the mock server after reading official document. I got the URL for mock server and I could get a response by grpcurl and a Node.js gRPC client. However, I got a error when I used the URL by Android gRPC client.

Stacktrace is below.

java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.aniokrait.grpcsample/io.github.aniokrait.grpcsample.MainActivity}: io.grpc.StatusRuntimeException: UNAVAILABLE
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE
        at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271)
        at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252)
        at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165)
        at com.book.BookServiceGrpc$BookServiceBlockingStub.getBook(BookServiceGrpc.java:312)
        at io.github.aniokrait.grpcsample.MainActivity$Companion.startGrpc(MainActivity.kt:71)
        at io.github.aniokrait.grpcsample.MainActivity$Companion.access$startGrpc(MainActivity.kt:34)
        at io.github.aniokrait.grpcsample.MainActivity.onCreate(MainActivity.kt:30)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.RuntimeException: TLS ALPN negotiation failed with protocols: [h2]
        at io.grpc.okhttp.OkHttpProtocolNegotiator.negotiate(OkHttpProtocolNegotiator.java:104)
        at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.negotiate(OkHttpProtocolNegotiator.java:218)
        at io.grpc.okhttp.OkHttpTlsUpgrader.upgrade(OkHttpTlsUpgrader.java:63)
        at io.grpc.okhttp.OkHttpClientTransport$3.run(OkHttpClientTransport.java:551)
        at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)

The messages says "TLS ALPN negotiation failed with protocols: [h2]", so I have an idea that the problem is around SSL/TLS, but I don't know how to solve it.

I do not think it is likely to be a certificate issue, as I am able to access the URL from Node.js and grpcurl but the issue of my Android app.

I've read tls-on-android and Update your security provider to protect against SSL exploits.

I added dependecies of play-services and installing code as below but still it doesn't work.

Here's my code.

MainActivity.kt

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.book.BookServiceGrpc
import com.book.Index.GetBookRequest
import com.google.android.gms.security.ProviderInstaller
import io.grpc.okhttp.OkHttpChannelBuilder

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ProviderInstaller.installIfNeeded(this@MainActivity)
        startGrpc()
    }

    companion object {
        private fun startGrpc() {
            try {
                val channel = OkHttpChannelBuilder
                    .forAddress("g-95d43o92ollxvwmm7nx895731r4g9y.srv.pstmn.io",443) //URL is slightly altered to prevent tampering
                    .useTransportSecurity()
                    .build()
                val stub = BookServiceGrpc.newBlockingStub(channel)
                val request = GetBookRequest.newBuilder().setIsbn(123).build()
                val result = stub.getBook(request)
            } catch (e: Exception) {
                e.printStackTrace()
                throw e
            }

        }
    }
}

my proto file.

syntax = "proto3";
package com.book;

message Book {
  int64 isbn = 1;
  string title = 2;
  string author = 3;
}

message GetBookRequest {
  int64 isbn = 1;
}

service BookService {
  rpc GetBook (GetBookRequest) returns (Book) {}
}

and dependecies relevant to gRPC

dependencies {
    implementation 'io.grpc:grpc-okhttp:1.51.1'
    implementation 'io.grpc:grpc-protobuf-lite:1.51.1'
    implementation 'io.grpc:grpc-stub:1.51.1'
    implementation 'org.apache.tomcat:annotations-api:6.0.53'
    implementation 'com.google.android.gms:play-services-basement:18.1.0'
}

Update:
I found these messages in Debug logs.

W/DynamiteModule: Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule: Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller: Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL

Perhaps The Dynamic Security Provider isn't installed properly, but still I don't know why.


来源: stackexchange

问:
Warning: could not download https://pkg.julialang.org/registries
I live in a country with a high level of internet censorship. It's been a while since I updated my packages, and I'm unsuccessful in updating them.

```<code>(@v1.8) pkg> up
┌ Warning: could not download https://pkg.julialang.org/registries
│   exception = schannel: failed to receive handshake, SSL/TLS connection failed while requesting https://pkg.julialang.org/registries
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:68
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
    Updating git-repo `https://github.com/peng1999/PkgDependency.jl`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Project.toml`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Manifest.toml`
</code>```

I tried using a Virtual private network to bypass the censorship, but the error still exists. How can I solve this?

Update:

I tried another server for my VPN, and it was helpful until I got this error:

```<code>(@v1.8) pkg> update
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
    Downloading [=>                                       ]  0.6 %

# I didn't monitor it and switched the window to another application. After a minute I came to check the progress, and I was confronted with the following log:
(@v1.8) pkg> update
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
┌ Error: Some registries failed to update:
│     — C:\Users\<A GEEK>\.julia\registries\General.toml — failed to download from https://pkg.julialang.org/registry/23338594-aafe-5451-b93e-139f81909106/80cc6104fbf941669a72a24525a38330e308ae6c. Exception: HTTP/1.1 200 OK (Operation too slow. Less than 1 bytes/sec transferred the last 20 seconds) while requesting https://pkg.julialang.org/registry/23338594-aafe-5451-b93e-139f81909106/80cc6104fbf941669a72a24525a38330e308ae6c
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:449
    Updating git-repo `https://github.com/peng1999/PkgDependency.jl`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Project.toml`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Manifest.toml`

# I tried it again and the content of the exception changed:
│   exception = HTTP/1.1 301 AS -> IN internal redirect trigger (schannel: failed to receive handshake, SSL/TLS connection failed) while requesting https://pkg.julialang.org/registries
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:68
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I live in a country with a high level of internet censorship. It's been a while since I updated my packages, and I'm unsuccessful in updating them.

(@v1.8) pkg> up
┌ Warning: could not download https://pkg.julialang.org/registries
│   exception = schannel: failed to receive handshake, SSL/TLS connection failed while requesting https://pkg.julialang.org/registries
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:68
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
    Updating git-repo `https://github.com/peng1999/PkgDependency.jl`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Project.toml`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Manifest.toml`

I tried using a Virtual private network to bypass the censorship, but the error still exists. How can I solve this?

Update:

I tried another server for my VPN, and it was helpful until I got this error:

(@v1.8) pkg> update
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
    Downloading [=>                                       ]  0.6 %

# I didn't monitor it and switched the window to another application. After a minute I came to check the progress, and I was confronted with the following log:
(@v1.8) pkg> update
    Updating registry at `C:\Users\<A GEEK>\.julia\registries\General.toml`
┌ Error: Some registries failed to update:
│     — C:\Users\\.julia\registries\General.toml — failed to download from https://pkg.julialang.org/registry/23338594-aafe-5451-b93e-139f81909106/80cc6104fbf941669a72a24525a38330e308ae6c. Exception: HTTP/1.1 200 OK (Operation too slow. Less than 1 bytes/sec transferred the last 20 seconds) while requesting https://pkg.julialang.org/registry/23338594-aafe-5451-b93e-139f81909106/80cc6104fbf941669a72a24525a38330e308ae6c
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:449
    Updating git-repo `https://github.com/peng1999/PkgDependency.jl`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Project.toml`
  No Changes to `C:\Users\<A GEEK>\.julia\environments\v1.8\Manifest.toml`

# I tried it again and the content of the exception changed:
│   exception = HTTP/1.1 301 AS -> IN internal redirect trigger (schannel: failed to receive handshake, SSL/TLS connection failed) while requesting https://pkg.julialang.org/registries
└ @ Pkg.Registry C:\workdir\usr\share\julia\stdlib\v1.8\Pkg\src\Registry\Registry.jl:68


问:
Call a static C# function without its class name in PowerShell
Let's say you wrote a totally awesome function in C# and want to use it in your PowerShell script. You can do this like so:

```<code>$Source = @"
public class BasicTest
{
  public static int AddNumbers(int a, int b)
    {
        return (a + b);
    }
}
"@

Add-Type -TypeDefinition $Source

[BasicTest]::AddNumbers(4, 3)
# output: 7
</code>```

The question is, how to call this function without [BasicTest]:: part? Like this:

```<code>AddNumbers(4, 3)
</code>```

What I tried (and it didn't work)

```<code>using namespace BasicTest
</code>```
```<code>Set-Alias -Name AddNumbers -Value [BasicTest]::AddNumber
</code>```

Body:
Let's say you wrote a totally awesome function in C# and want to use it in your PowerShell script. You can do this like so:

$Source = @"
public class BasicTest
{
  public static int AddNumbers(int a, int b)
    {
        return (a + b);
    }
}
"@

Add-Type -TypeDefinition $Source

[BasicTest]::AddNumbers(4, 3)
# output: 7

The question is, how to call this function without [BasicTest]:: part? Like this:

AddNumbers(4, 3)

What I tried (and it didn't work)

using namespace BasicTest

Set-Alias -Name AddNumbers -Value [BasicTest]::AddNumber


问:
How to get decibels accurately with AVAudioRecorder?
After comparing more than 20 apps, I found that the decibel values measured by each app are different.

```<code>// Method 1:
float power = [self.audioRecorder averagePowerForChannel:0];
float powerMax = [self.audioRecorder peakPowerForChannel:0];

power = power + 160  - 50;

int dB = 0;
if (power < 0.f) {
    dB = 0;
} else if (power < 40.f) {
    dB = (int)(power * 0.875);
} else if (power < 100.f) {
    dB = (int)(power - 15);
} else if (power < 110.f) {
    dB = (int)(power * 2.5 - 165);
} else {
    dB = 110;
}

NSLog(@"power = %f, powerMax = %f , dB = %d",power, powerMax,dB);

// Method 2:

float   level;                // The linear 0.0 .. 1.0 value we need.
float   minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
float   decibels = [self.audioRecorder averagePowerForChannel:0];
if (decibels < minDecibels)
{
    level = 0.0f;
}
else if (decibels >= 0.0f)
{
    level = 1.0f;
}
else
{
    float   root            = 2.0f;
    float   minAmp          = powf(10.0f, 0.05f * minDecibels);
    float   inverseAmpRange = 1.0f / (1.0f - minAmp);
    float   amp             = powf(10.0f, 0.05f * decibels);
    float   adjAmp          = (amp - minAmp) * inverseAmpRange;
    level = powf(adjAmp, 1.0f / root);
}
NSLog(@"leval %f", level * 120);
</code>```

There is a big gap between Method 1 and Method 2

So,Are these methods accurate? Is there a more correct way?

Body:
After comparing more than 20 apps, I found that the decibel values measured by each app are different.

// Method 1:
float power = [self.audioRecorder averagePowerForChannel:0];
float powerMax = [self.audioRecorder peakPowerForChannel:0];

power = power + 160  - 50;

int dB = 0;
if (power < 0.f) {
    dB = 0;
} else if (power < 40.f) {
    dB = (int)(power * 0.875);
} else if (power < 100.f) {
    dB = (int)(power - 15);
} else if (power < 110.f) {
    dB = (int)(power * 2.5 - 165);
} else {
    dB = 110;
}

NSLog(@"power = %f, powerMax = %f , dB = %d",power, powerMax,dB);

// Method 2:

float   level;                // The linear 0.0 .. 1.0 value we need.
float   minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
float   decibels = [self.audioRecorder averagePowerForChannel:0];
if (decibels < minDecibels)
{
    level = 0.0f;
}
else if (decibels >= 0.0f)
{
    level = 1.0f;
}
else
{
    float   root            = 2.0f;
    float   minAmp          = powf(10.0f, 0.05f * minDecibels);
    float   inverseAmpRange = 1.0f / (1.0f - minAmp);
    float   amp             = powf(10.0f, 0.05f * decibels);
    float   adjAmp          = (amp - minAmp) * inverseAmpRange;
    level = powf(adjAmp, 1.0f / root);
}
NSLog(@"leval %f", level * 120);

There is a big gap between Method 1 and Method 2

So,Are these methods accurate? Is there a more correct way?


问:
In expo android app, How to detect call state?
In expo android app, I want detect call state if person is picking incoming calls or making outgoing call. What package or method I can use please suggest.</p>


问:
Is it possible to check whether any given disk sector is being accessed?
I am writing a C++ program that is currently capable of opening any drive given a disk letter ('C', 'D', etc), and then reading or writing to any sector within that drive given a sector identifier (index).

I am using the Windows File API (CreateFile, ReadFile, SetFilePointer, etc.) for achieving this thus far. Also, for insight, I calculate the offset to read from/write to, using:
disk sector size * sector index + offset

Now, I would like to be able to check whether any given sector (specified by an index for example), is in use by the file system already before reading from/writing to it. How could I achieve this?

I am fairly sure it isn't even possible, but, maybe someone out there knows a way.


问:
How can I add the XML tag and data to an existing XML in PL-SQL?
The xmldom usage in the package is as follows. I specify the next line to be added. But I can't find a solution on how to convert the line to xmldom format and add it.</p>
```<code>  vc_xml := '<'||cs_KEY_TAG||'>'|| pin_xml ||'</'||cs_KEY_TAG||'>';
  parser := xmlparser.newParser;
  xmlparser.parseclob(parser, vc_xml);
  doc := xmlparser.getDocument(parser);

  nl1  := xmldom.getElementsByTagName(doc, cs_KEY_TAG);
  node := xmldom.item(nl1, 0);
  nl2  := XMLDOM.getchildnodes(node);
  len1 := xmldom.getLength(nl2);

 FOR i in 0..len1-1 LOOP
     node := xmldom.item(nl2, i);
     nl3 := xmldom.getchildnodes(node);
     len2 := xmldom.getLength(nl3);

     FOR j in 0..len2 -1 LOOP
         node := xmldom.item(nl3, j);
         element := xmldom.makeElement(node);
         node := xmldom.getFirstChild(node);

   '<device_count>' || vs_d_count || '</device_count>'  ->this is the line to add to the XML
</code>```

Body:
The xmldom usage in the package is as follows. I specify the next line to be added. But I can't find a solution on how to convert the line to xmldom format and add it.

  vc_xml := '<'||cs_KEY_TAG||'>'|| pin_xml ||'</'||cs_KEY_TAG||'>';
  parser := xmlparser.newParser;
  xmlparser.parseclob(parser, vc_xml);
  doc := xmlparser.getDocument(parser);

  nl1  := xmldom.getElementsByTagName(doc, cs_KEY_TAG);
  node := xmldom.item(nl1, 0);
  nl2  := XMLDOM.getchildnodes(node);
  len1 := xmldom.getLength(nl2);

 FOR i in 0..len1-1 LOOP
     node := xmldom.item(nl2, i);
     nl3 := xmldom.getchildnodes(node);
     len2 := xmldom.getLength(nl3);

     FOR j in 0..len2 -1 LOOP
         node := xmldom.item(nl3, j);
         element := xmldom.makeElement(node);
         node := xmldom.getFirstChild(node);

   '<device_count>' || vs_d_count || '</device_count>'  ->this is the line to add to the XML


问:
How can I solve an UnsatisfiedResolutionException related to generic interface raised when I try to run the application?
I got this code structure below

```<code>public class ProcessService implements ServiceInterface{

    @Inject
    AnotherInterface another;

    @Inject
    ProcessQueryUseCase useCase;

    Override
    public MyObject<Process> getMyObjectFromService(MyRequestObject att1){
        MyObject<Process> response = useCase.getGateway().getAll(att1);
    }

}

public class ProcessQueryUseCase implements IFindUseCaseBase<Process, ProcessPKClass>{

    @Inject
    IGateway<Process, ProcessPKClass> gateway;

    @Override
    public IGateway<Process, ProcessPKClass> getGateway(){
        return gateway;
    }
}

public interface IFindUseCaseBase<E,I>{
    public IGateway<E,I> getGateway();
}

public interface IGateway<E,I>{
    public IRepositoryBase<E,I> getRepository();

    default MyObject<E> getAll(MyRequestObject att1){
        return getRepository().find(att1);
    }
}

public interface IRepositoryBase extends PanacheRepositoryBase<Entity, Id>{

    @GeneratedBridge
    default MyObject<Entity> find(MyRequestObject att1) {
        String query = ...
        return new PanacheQueryExtends<>(this.find(query,...).methodInPanacheQueryExtendsThatCreatesMyObject();
    }

}
</code>```

I have another Repository Interface declared as IProcessRepository extends PanacheRepositoryBase<Process, ProcessPKClass>

When I try to execute the project

```<code>Build step io.quarkus... -> javax.enterprise.inject.spi.DeploymentException
javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ...repository.IRepositoryBase and qualifiers [@Default]
java member ...dataprovider.ProcessDataProvider#BaseRepository
declared on CLASS bean [types=[...dataprovider.ProcessDataProvider, ...gateway.IProcessGateway, java.lang.Object], qualifiers = [@Default, @Any],
target = ...dataprovider.ProcessDataProvider]

get same problem for IGateway in IFindUseCaseBase and ProcessQueryUseCase
</code>```

Can someone help me? I didn´t understand what is happening and how to solve it.

Body:
I got this code structure below

public class ProcessService implements ServiceInterface{

    @Inject
    AnotherInterface another;

    @Inject
    ProcessQueryUseCase useCase;

    Override
    public MyObject<Process> getMyObjectFromService(MyRequestObject att1){
        MyObject<Process> response = useCase.getGateway().getAll(att1);
    }

}

public class ProcessQueryUseCase implements IFindUseCaseBase<Process, ProcessPKClass>{

    @Inject
    IGateway<Process, ProcessPKClass> gateway;

    @Override
    public IGateway<Process, ProcessPKClass> getGateway(){
        return gateway;
    }
}

public interface IFindUseCaseBase<E,I>{
    public IGateway<E,I> getGateway();
}

public interface IGateway<E,I>{
    public IRepositoryBase<E,I> getRepository();

    default MyObject<E> getAll(MyRequestObject att1){
        return getRepository().find(att1);
    }
}

public interface IRepositoryBase extends PanacheRepositoryBase<Entity, Id>{

    @GeneratedBridge
    default MyObject<Entity> find(MyRequestObject att1) {
        String query = ...
        return new PanacheQueryExtends<>(this.find(query,...).methodInPanacheQueryExtendsThatCreatesMyObject();
    }

}

I have another Repository Interface declared as IProcessRepository extends PanacheRepositoryBase<Process, ProcessPKClass>

When I try to execute the project

Build step io.quarkus... -> javax.enterprise.inject.spi.DeploymentException
javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ...repository.IRepositoryBase and qualifiers [@Default]
java member ...dataprovider.ProcessDataProvider#BaseRepository
declared on CLASS bean [types=[...dataprovider.ProcessDataProvider, ...gateway.IProcessGateway, java.lang.Object], qualifiers = [@Default, @Any],
target = ...dataprovider.ProcessDataProvider]

get same problem for IGateway in IFindUseCaseBase and ProcessQueryUseCase

Can someone help me? I didn´t understand what is happening and how to solve it.


问:
How to install homebrew on mac M1 chip problem
Now, I successfully installed homebrew on my macbook
bue every time after I closed terminal and reopen terminal
I need to type -> export PATH=/opt/homebrew/bin:$PATH
and then type -> brew --version is OKAY

My question is, how can I fixed this problem into when every time I open terminal,
I can directly type brew --version can work?


问:
Is there a way to keep an icon added to .fc-event-title when click-dragging an event in Full Calendar v6.0.2?
I have a feature where I allow users to flag an appointment as missed. When doing so, I add an icon to the event so that it is obvious in the agenda:

This is done by leveraging eventRender:

if (event.extendedProps.isMissed === true) {
  var message = "";
  element.find('.fc-event-title').prepend(message);
}
```

This works fine, until I click'n'drag the event to move it, in which case the icon is lost when I release the click:

The  is element is removed from .fc-event-title.

Is there a way to keep it?

Body:
I have a feature where I allow users to flag an appointment as missed. When doing so, I add an icon to the event so that it is obvious in the agenda:

This is done by leveraging eventRender:

if (event.extendedProps.isMissed === true) {
  var message = "";
  element.find('.fc-event-title').prepend(message);
}

This works fine, until I click'n'drag the event to move it, in which case the icon is lost when I release the click:

The  is element is removed from .fc-event-title.

Is there a way to keep it?


问:
How can I open firefox in normal mode with Selenium? (Python)
I want to work in normal mode using Selenium with Python in the Firefox browser. However, when I write the codes in this way, the test mode always turns on. Is there a way to boot into normal mode?</p>
```<code>from selenium import webdriver

driver = webdriver.Firefox()

driver.get("http://github.com")
</code>```

Body:
I want to work in normal mode using Selenium with Python in the Firefox browser. However, when I write the codes in this way, the test mode always turns on. Is there a way to boot into normal mode?

from selenium import webdriver

driver = webdriver.Firefox()

driver.get("http://github.com")


问:
Problem with displaying data from table with .closest("tr")
iam using 2 modals (Bootstrap) with different contents I now want to display data from a table in Input fields in my Modal. There is an edit button in the row, thats why iam using closest.

With 1 Modal it yesterday worked with:

```<code>$(document).ready(function() {
  $(".trigger_popup").on("click", function(){
    $(".modal").modal("show");
    $(".trigger_close").on("click", function(){
    $(".modal").modal("hide");
    })
    $tr = $(this).closest("tr");
    var data = $tr.children("td").map(function(){
      return $(this).text().trim("");

    }).get();
    console.log(data);
    $("#name").val(data[1])
    $("#model").val(data[2])
    $("#facturer").val(data[3])
    $("#serial").val(data[4])
    $("#place").val(data[6])
    $("#notes").val(data[7])
    $("#updated").val(data[8])
    $("#added").val(data[9])
  })
})
</code>```

now the code is this:

```<code>    $(document).ready(function() {
        $('#exampleModal').on('show.bs.modal', function (e) {
            $tr = $(this).closest("tr");
        var data = $tr.children("td").map(function(){
          return $(this).text().trim("");

        }).get();
        console.log(data);
        $("#name").val(data[1])
        $("#model").val(data[2])
        $("#facturer").val(data[3])
        $("#serial").val(data[4])
        $("#place").val(data[6])
        $("#notes").val(data[7])
        $("#updated").val(data[8])
        $("#added").val(data[9])
      })
        })
</code>```

this is my HTML Code:

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

          <table id="myTable">
                                  <tr>
                                  <th style="display:none;"></th>
                                    <th>Name</th>
                                    <th>Modell</th>
                                    <th>Hersteller</th>
                                    <th>Seriennummer</th>
                                    <th>Bestand</th>
                                    <th style="display:none;"></th>
                                    <th style="display:none;"></th>
                                    <th style="display:none;"></th>
                                    <th style="display:none;"></th>

                                    <th></th>
                                  </tr>
            <tr>
            <td style='display: none;'>id</td>
            <td>name</td>
            <td>model</td>
            <td>facturer</td>
            <td>serial</td>
            <td>count</td>
            <td style='display: none;'>place</td>
            <td style='display: none;'>notes</td>
            <td style='display: none;'>updated</td>
            <td style='display: none;'>added</td>
            <td><i data-toggle="modal" data-target=".bd-example-modal-lg" class="icon fa-solid fa-eye"></i></td>';
            <td><a><i class="icon fa-solid fa-circle-minus"></i></a></td>';
          </tr>
          </table>
        </div>

          <!------------------------------------------------>

<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-body">
            <form action="inserts.php" method="POST" id="form">
              <input type="text" id="name" class="form-control mb-1" name="name" placeholder="Produkttyp" value="" autocomplete="off">
              <input type="text" id="model" class="form-control mb-1" name="model" placeholder="Modell"  autocomplete="off">
              <input type="text" id="facturer" class="form-control mb-1" name="facturer" placeholder="Hersteller"  autocomplete="off">
              <input type="text" id="serial" class="form-control mb-1" name="serial" placeholder="Seriennummer"  autocomplete="off">
              <input type="text" id="place" class="form-control mb-1" name="place" placeholder="Ablageort" autocomplete="off">
              <input type="text" id="notes" class="form-control mb-1" name="notes" placeholder="Notiz"   autocomplete="off">
              <input type="text" id="updated" class="form-control mb-1" name="updated" placeholder="zuletzt geändert"  readonly autocomplete="off">
              <input type="text" id="added" class="form-control mb-1" name="added" placeholder="hinzugefügt" readonly  autocomplete="off">
          </div>
          <div class="modal-footer">
            <button type="submit" name="save" class="btn btn-primary" style="background-color: #F9B711; color: black;border: none;">Änderungen speichern</button>
            </form>
            <button type="button" class="btn btn-secondary trigger_close"  data-dismiss="modal" style="background-color: red; color: black; border: none;">schließen</button>
          </div>
    </div>
  </div>
</div>

<!-- Small modal -->

<div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
        <div class="modal-body">
            <form action="inserts.php" method="POST" id="form">
              <input type="text" id="name" class="form-control mb-1" name="name" placeholder="Produkttyp" autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="model" placeholder="Modell"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="facturer" placeholder="Hersteller"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="serial" placeholder="Seriennummer"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="count" placeholder="Anzahl"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="place" placeholder="Ablageort" autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="notes" placeholder="Notiz"   autocomplete="off">
                      <select name="w" class="form-select">
                          <option value="NULL">Warnung bei niedrigem Bestand?</option>
                          <option value="y">Ja</option>
                          <option value="n">Nein</option>
                        </select>
          </div>
          <div class="modal-footer">
            <button type="submit" name="send" class="btn btn-primary" style="background-color: #F9B711; color: black;border: none;">einlagern</button>
            </form>
            <button type="button" class="btn btn-secondary create_close" data-dismiss="modalcreate" style="background-color: red; color: black; border: none;">schließen</button>
          </div>
    </div>
  </div>
</div>
</code>```

I want that the data from the table (closest) is displayed in the Inputs from the first modal.

Body:
iam using 2 modals (Bootstrap) with different contents I now want to display data from a table in Input fields in my Modal. There is an edit button in the row, thats why iam using closest.

With 1 Modal it yesterday worked with:

$(document).ready(function() {
  $(".trigger_popup").on("click", function(){
    $(".modal").modal("show");
    $(".trigger_close").on("click", function(){
    $(".modal").modal("hide");
    })
    $tr = $(this).closest("tr");
    var data = $tr.children("td").map(function(){
      return $(this).text().trim("");

    }).get();
    console.log(data);
    $("#name").val(data[1])
    $("#model").val(data[2])
    $("#facturer").val(data[3])
    $("#serial").val(data[4])
    $("#place").val(data[6])
    $("#notes").val(data[7])
    $("#updated").val(data[8])
    $("#added").val(data[9])
  })
})

now the code is this:

    $(document).ready(function() {
        $('#exampleModal').on('show.bs.modal', function (e) {
            $tr = $(this).closest("tr");
        var data = $tr.children("td").map(function(){
          return $(this).text().trim("");

        }).get();
        console.log(data);
        $("#name").val(data[1])
        $("#model").val(data[2])
        $("#facturer").val(data[3])
        $("#serial").val(data[4])
        $("#place").val(data[6])
        $("#notes").val(data[7])
        $("#updated").val(data[8])
        $("#added").val(data[9])
      })
        })

this is my HTML Code:

                                    Name
                                    Modell
                                    Hersteller
                                    Seriennummer
                                    Bestand

            id
            name
            model
            facturer
            serial
            count
            place
            notes
            updated
            added
            	';
            	';

            <form action="inserts.php" method="POST" id="form">
              <input type="text" id="name" class="form-control mb-1" name="name" placeholder="Produkttyp" value="" autocomplete="off">
              <input type="text" id="model" class="form-control mb-1" name="model" placeholder="Modell"  autocomplete="off">
              <input type="text" id="facturer" class="form-control mb-1" name="facturer" placeholder="Hersteller"  autocomplete="off">
              <input type="text" id="serial" class="form-control mb-1" name="serial" placeholder="Seriennummer"  autocomplete="off">
              <input type="text" id="place" class="form-control mb-1" name="place" placeholder="Ablageort" autocomplete="off">
              <input type="text" id="notes" class="form-control mb-1" name="notes" placeholder="Notiz"   autocomplete="off">
              <input type="text" id="updated" class="form-control mb-1" name="updated" placeholder="zuletzt geändert"  readonly autocomplete="off">
              <input type="text" id="added" class="form-control mb-1" name="added" placeholder="hinzugefügt" readonly  autocomplete="off">

            <button type="submit" name="save" class="btn btn-primary" style="background-color: #F9B711; color: black;border: none;">Änderungen speichern</button>
            </form>
            <button type="button" class="btn btn-secondary trigger_close"  data-dismiss="modal" style="background-color: red; color: black; border: none;">schließen</button>

            <form action="inserts.php" method="POST" id="form">
              <input type="text" id="name" class="form-control mb-1" name="name" placeholder="Produkttyp" autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="model" placeholder="Modell"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="facturer" placeholder="Hersteller"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="serial" placeholder="Seriennummer"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="count" placeholder="Anzahl"  autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="place" placeholder="Ablageort" autocomplete="off">
                      <input type="text" id="name" class="form-control mb-1" name="notes" placeholder="Notiz"   autocomplete="off">
                      <select name="w" class="form-select">
                          <option value="NULL">Warnung bei niedrigem Bestand?</option>
                          <option value="y">Ja</option>
                          <option value="n">Nein</option>
                        </select>

            <button type="submit" name="send" class="btn btn-primary" style="background-color: #F9B711; color: black;border: none;">einlagern</button>
            </form>
            <button type="button" class="btn btn-secondary create_close" data-dismiss="modalcreate" style="background-color: red; color: black; border: none;">schließen</button>

I want that the data from the table (closest) is displayed in the Inputs from the first modal.


问:
UseEffect Hook Infinite Loop + White Screen
I am working on the Linked in Clone from one of Sonny Sangha's videos, and I have a problem with the useEffect hook. When I run the program, my output is just a blank white screen, and it never changes to the app I programmed before. My guess is that there is some kind of an infinite loop happening, but I do not know where. I copied Sonny's code exactly, so I do not know what the problem is.

Here is the code:

```<code>useEffect(() => {
        db.collection("posts").onSnapshot((snapshot) =>
            setPosts(
                snapshot.docs.map((doc) => ({
                    id: doc.id,
                    data: doc.data(),
                }))
            )
        );
    }, []);
</code>```

I am slo confused why it is giving me a blank screen, when I clearly passed an empty array as the second argument, meaning it should only be rendered once. Everything runs in every console, and everything compiles. Thank you

Body:
I am working on the Linked in Clone from one of Sonny Sangha's videos, and I have a problem with the useEffect hook. When I run the program, my output is just a blank white screen, and it never changes to the app I programmed before. My guess is that there is some kind of an infinite loop happening, but I do not know where. I copied Sonny's code exactly, so I do not know what the problem is.

Here is the code:

useEffect(() => {
        db.collection("posts").onSnapshot((snapshot) =>
            setPosts(
                snapshot.docs.map((doc) => ({
                    id: doc.id,
                    data: doc.data(),
                }))
            )
        );
    }, []);

I am slo confused why it is giving me a blank screen, when I clearly passed an empty array as the second argument, meaning it should only be rendered once. Everything runs in every console, and everything compiles. Thank you


问:
Django query after a given character
I am trying to filter data from the postgres database connected to my django app. The data in the database column to be filtered is in this format:

```<code>Name|ABC & facilities:Unit|XY Unit
</code>```

I want to write a django query that matches the search text after the last pipe ("|") symbol. How can this be done to return the data in shortest time possible.

I tried writing a query

```<code>Mymodel.objects.filter(name__iendswith=searchTxt)
</code>```

but it's not returning any result.

Title: Django query after a given character

Body:
I am trying to filter data from the postgres database connected to my django app. The data in the database column to be filtered is in this format:

Name|ABC & facilities:Unit|XY Unit

I want to write a django query that matches the search text after the last pipe ("|") symbol. How can this be done to return the data in shortest time possible.

I tried writing a query

Mymodel.objects.filter(name__iendswith=searchTxt)

but it's not returning any result.


问:
Switch can't connect to controller in my code in Mininet
I am having trouble connecting the switch to the controller in mininet. I use python script.
My script is the following.
The file name is test.py.

```<code>#!/usr/bin/python

from mininet.cli import CLI
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.node import Controller, OVSSwitch, RemoteController, OVSBridge
from mininet.log import setLogLevel

class test_Topo(Topo):

    def build(self):

        s1 = self.addSwitch( 's1')
        s2 = self.addSwitch( 's2')

        h1 = self.addHost( 'h1' )
        h2 = self.addHost( 'h2' )

        n1 = self.addHost( 'n1' )

        self.addLink( s1, s2 )
        self.addLink( s1, h1 )
        self.addLink( s1, h2 )
        self.addLink( s2, n1 )

def test():

    topo = test_Topo()

    net = Mininet(topo, build=False, waitConnected=True, switch=OVSSwitch, controller=Controller)

    c0 = net.addController( 'c0', port=6633 )
    c1 = net.addController('c1', port=6634)

    net.build()

    s1 = net.get('s1')
    s2 = net.get('s2')

    c0.start()
    c1.start()
    s1.start([c0])
    s2.start([c1])

    net.start()

    net.pingAll()

    CLI( net )
    net.stop()

if __name__ == '__main__':
    setLogLevel('info')
    test()
</code>```

I want to have each switch connected to a different controller.
I ran the script with the following command.
sudo python3 test.py

The result is the following.

```<code>*** Creating network
*** Adding hosts:
h1 h2 n1
*** Adding switches:
s1 s2
*** Adding links:
(s1, h1) (s1, h2) (s1, s2) (s2, n1)
*** Configuring hosts
h1 h2 n1
*** Starting controller
c0 c1
*** Starting 2 switches
s1 s2 ...
*** Waiting for switches to connect

</code>```

The connection does not end permanently after the message

```<code>*** Waiting for switches to connect
</code>```

is displayed.

I referred to this code.
https://github.com/mininet/mininet/blob/master/examples/controllers.py
https://github.com/mininet/mininet/blob/master/examples/controllers2.py

I can't understand why switch can't connect the controller in my code.
I apologize for my poor English.

Body:
I am having trouble connecting the switch to the controller in mininet. I use python script.
My script is the following.
The file name is test.py.

#!/usr/bin/python

from mininet.cli import CLI
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.node import Controller, OVSSwitch, RemoteController, OVSBridge
from mininet.log import setLogLevel

class test_Topo(Topo):

    def build(self):

        s1 = self.addSwitch( 's1')
        s2 = self.addSwitch( 's2')

        h1 = self.addHost( 'h1' )
        h2 = self.addHost( 'h2' )

        n1 = self.addHost( 'n1' )

        self.addLink( s1, s2 )
        self.addLink( s1, h1 )
        self.addLink( s1, h2 )
        self.addLink( s2, n1 )

def test():

    topo = test_Topo()

    net = Mininet(topo, build=False, waitConnected=True, switch=OVSSwitch, controller=Controller)

    c0 = net.addController( 'c0', port=6633 )
    c1 = net.addController('c1', port=6634)

    net.build()

    s1 = net.get('s1')
    s2 = net.get('s2')

    c0.start()
    c1.start()
    s1.start([c0])
    s2.start([c1])

    net.start()

    net.pingAll()

    CLI( net )
    net.stop()

if __name__ == '__main__':
    setLogLevel('info')
    test()

I want to have each switch connected to a different controller.
I ran the script with the following command.
sudo python3 test.py

The result is the following.

*** Creating network
*** Adding hosts:
h1 h2 n1
*** Adding switches:
s1 s2
*** Adding links:
(s1, h1) (s1, h2) (s1, s2) (s2, n1)
*** Configuring hosts
h1 h2 n1
*** Starting controller
c0 c1
*** Starting 2 switches
s1 s2 ...
*** Waiting for switches to connect

The connection does not end permanently after the message

*** Waiting for switches to connect

is displayed.

I referred to this code.
https://github.com/mininet/mininet/blob/master/examples/controllers.py
https://github.com/mininet/mininet/blob/master/examples/controllers2.py

I can't understand why switch can't connect the controller in my code.
I apologize for my poor English.


问:
How to code a revenue forecasting model in R for every certain value?
I have a data table that has a column for the fiscal quarter, a column for the net revenue made for row X's sale, and a column for the type of sale it was.

I want to use a forecasting method in R (was planning to use ARIMA, but am open to options) to predict future fiscal quarter net revenue per type of sale. For example, if the two types of sale are service and good, I want to create a model to predict future revenue for service and a model for good's future net revenue.

How would I approach this code and are there any websites you'd recommend I reference. Thank you in advance!

The websites I have found so far reference if every timestamp (i.e. every fiscal quarter) has only one row. But, my data table shows how i.e. quarter 1 can have 10 different sales and 5 can be labelled service and 5 are good.


Title: same data gives different p-values for kruskal test

Body:
I've defined 3 variables that are " x, y and z".
Tried to kruskal test these independent variables.
P-Value comes out different in python and r.
Have any ideas?

in python

from scipy import stats
import numpy as np
x = np.array([22.293, 23.621, 25.536, 27.322, 28.872, 30.385, 32.621, 35.111, 37.418, 39.607, 41.381, 43.107, 44.747, 46.602])

y = np.array([29.989, 30.184, 29.567, 28.403, 28.166, 28.815, 30.083, 31.520, 32.786, 33.954, 35.105, 35.959, 36.590, 37.173])

z = np.array([19.416, 19.798, 19.493, 18.797, 19.024, 19.031, 19.547, 20.246, 21.474, 22.908, 24.534, 26.458, 28.344, 30.222])
stats.kruskal(x,y,z)

KruskalResult(statistic=21.43236829615566, pvalue=2.2183003995654387e-05)

in r

library(stats)
x = c(22.293, 23.621, 25.536, 27.322, 28.872, 30.385, 32.621, 35.111, 37.418, 39.607, 41.381, 43.107, 44.747, 46.602)
y = c(29.989, 30.184, 29.567, 28.403, 28.166, 28.815, 30.083, 31.520, 32.786, 33.954, 35.105, 35.959, 36.590, 37.173)
z = c(19.416, 19.798, 19.493, 18.797, 19.024, 19.031, 19.547, 20.246, 21.474, 22.908, 24.534, 26.458, 28.344, 30.222)
kruskal.test(x,y,z)

Kruskal-Wallis rank sum test
data:  x y z
Kruskal-Wallis chi-squared = 13, df = 13, p-value = 0.4478


问:
React select from Radix-UI conflicts with default value, how to solve it?
I have this component where I render 3 different selectors depending on the data I pass. The first selector once clicked, gets the data of the second one (without selection), the same for the second, and so on. What I am trying to achieve is that, if I select the first dropdown && the second one has only one item in the list I get that value will be pre-selected without letting the user select it by himself.

This is the parent component where I pass the default value to each selector:

```<code>const CreateBatchTemplateDialog: FC<Props> = ({ open, onClose }) => {
  const [localInstruments, setLocalInstruments] = useState<LocalInstrument[]>();
  const [corridors, setCorridors] = useState<Corridor[]>();
  const [corridorId, setCorridorId] = useState<string>();
  const [productSchemas, setProductSchemas] = useState<ProductSchema[]>();
  const [dowloaded, setDowloaded] = useState<boolean>(false);
  const { data: localInstrumentsData } = useGetLocalInstrumentsQuery();
  const downloadFile = useDownloadFile();

  const [getProductSchemas] = useLazyGetProductSchemasQuery();

  const fetchingProductSchemaData = async () => {
    try {
      const { data: productSchema } = await getProductSchemas(corridorId);
      setProductSchemas(productSchema.data);
    } catch (error: any) {
      console.error(error);
    }
  };
  useEffect(() => {
    if (corridorId) {
      fetchingProductSchemaData();
    }
  }, [corridorId]);

  useEffect(() => {
    if (localInstrumentsData?.data) {
      setLocalInstruments(localInstrumentsData.data);
    }
    setProductSchemas([]);
  }, [localInstrumentsData]);

  const {
    handleSubmit,
    setError,
    formState,
    setValue,
    reset: resetForm,
    getValues
  } = useForm<Inputs>({
    mode: 'onSubmit',
    resolver: yupResolver(schema)
  });

  const localInstrumentsOptions = useMemo(() => {
    setProductSchemas([]);
    return Array.isArray(localInstruments)
      ? localInstruments.map((i) => ({ label: i.name, value: i.name }))
      : [];
  }, [localInstruments]);

  const corridorsOptions = useMemo<SelectChoice[]>(() => {
    setProductSchemas([]);
    return Array.isArray(corridors)
      ? corridors.map((i) => ({
          label: i.label,
          value: i.id.toString()
        }))
      : [];
  }, [corridors, localInstruments]);

  const productSchemasOptions = useMemo(() => {
    return Array.isArray(productSchemas)
      ? productSchemas.map((i) => ({
          label: i.label,
          value: i.id.toString()
        }))
      : [];
  }, [productSchemas, corridors, localInstruments]);

  const onLocalInstrumentChange = (value: string) => {
    setDowloaded(false);
    setProductSchemas([]);
    setCorridorId(undefined);

    const corridorData = localInstruments?.find((i) => i.name === value);
    setCorridors(corridorData ? corridorData.products : []);

    setValue('localInstrument', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
    setValue('corridor', '', {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onCorridorChange = (value: string) => {
    setDowloaded(false);
    setCorridorId(value);
    setProductSchemas([]);
    setValue('corridor', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
    setValue('productSchema', '', {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onProductSchemaChange = (value: string) => {
    setDowloaded(false);
    setValue('productSchema', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onSubmit: FormEventHandler<HTMLFormElement> = async (event: any) => {
    try {
      await handleSubmit(async (data) => {
        downloadFile(`payouts/schemas/${data.productSchema}/csv_template`);
        setDowloaded(true);
      })(event);
    } catch (error: any) {
      setTimeout(
        () =>
          setFormErrors({
            error,
            setError,
            fields: Object.keys(schema.fields)
          }),
        50
      );
    }
  };

  const onDialogClose = (value: boolean) => {
    resetForm();
    onClose(value);
    setLocalInstruments([]);
    setCorridors([]);
    setCorridorId(undefined);
    setProductSchemas([]);
    setDowloaded(false);
  };

  return (
    <Dialog open={open} onOpenChange={onDialogClose}>
      <DialogPortal>
        <DialogOverlay className="fixed inset-0 z-50 bg-inpay-green-700/90">
          <DialogContent
            onClick={(e) => e.stopPropagation()}
            className="fixed top-[50%] left-[50%] translate-y-[-50%] translate-x-[-50%] rounded-lg shadow-[0_0_6px_#B7BCBA]"
          >
            <DialogTitle className="flex h-12 items-center justify-between rounded-t-lg border-b border-b-inpay-pumice bg-white px-6">
              <DownloadIcon className="w-8 stroke-1 group-hover:stroke-1.5" />
              <span className="pr-12">Create batch template</span>
              <DialogClose
                aria-label="Close"
                className="outline-none focus:outline-none"
              >
                <XIcon className="-m-1 h-8 w-8 outline-none focus:outline-none" />
              </DialogClose>
            </DialogTitle>
            <div className="flex justify-center rounded-b-lg bg-inpay-black-haze-100 p-6">
              <div className="w-72">
                <form onSubmit={onSubmit} autoComplete="off">
                  <div className="mb-4 flex flex-col">
                    <label className="mb-0.5 pl-2 text-xs">Format</label>
                    <CsvSelector />
                  </div>
                  <div className="mb-4 flex flex-col">
                    <label className="mb-0.5 pl-2 text-xs">Transfer type</label>
                    <Selector
                      selectChoices={localInstrumentsOptions}
                      onChange={onLocalInstrumentChange}
                      name="localInstruments"
                      disabled={
                        !localInstrumentsOptions ||
                        localInstrumentsOptions.length === 0
                      }
                      defaultValue={
                        localInstrumentsOptions?.length === 1
                          ? localInstrumentsOptions[0].value
                          : undefined
                      }
                    />
                  </div>
                  <div className="mb-4 flex flex-col">
                    <label className="mb-0.5 pl-2 text-xs">Corridor</label>
                    <Selector
                      selectChoices={corridorsOptions}
                      onChange={onCorridorChange}
                      name="corridor"
                      disabled={
                        !corridorsOptions || corridorsOptions.length === 0
                      }
                      value={getValues('corridor')}
                      defaultValue={
                        corridorsOptions?.length === 1
                          ? corridorsOptions[0].label
                          : undefined
                      }
                    />
                    {console.log(
                      corridorsOptions?.length === 1
                        ? corridorsOptions[0].label
                        : undefined
                    )}
                  </div>
                  <div className="mb-10 flex flex-col">
                    <label className="mb-0.5 pl-2 text-xs">Data required</label>
                    <Selector
                      selectChoices={productSchemasOptions}
                      onChange={onProductSchemaChange}
                      name="productSchema"
                      disabled={
                        !productSchemasOptions ||
                        productSchemasOptions.length === 0
                      }
                      value={getValues('productSchema')}
                      defaultValue={
                        productSchemasOptions?.length === 1
                          ? productSchemasOptions[0].label
                          : undefined
                      }
                    />
                  </div>
                  {dowloaded === false ? (
                    <button
                      type="submit"
                      className="inpay-button w-full"
                      disabled={!formState.isValid}
                    >
                      Download CSV template
                    </button>
                  ) : (
                    <button
                      type="submit"
                      className="inpay-button w-full"
                      onClick={() => onClose(false)}
                    >
                      CSV dowloaded, close window
                    </button>
                  )}

                  {formState.errors.base && (
                    <div
                      role="alert"
                      className="mt-2 rounded-2xl bg-rose-200 p-3 text-sm text-inpay-red-600"
                      style={{
                        filter: 'drop-shadow(0 0 1px rgb(0 0 0 / 0.16))'
                      }}
                    >
                      {formState.errors.base.message}
                    </div>
                  )}
                </form>
              </div>
            </div>
          </DialogContent>
        </DialogOverlay>
      </DialogPortal>
    </Dialog>
  );
};
</code>```

This is the child component where I render the Selector, the issue is that even though the default value (string) and the matchingValue (object) are logged in the useEffect, matched and passed to the setCurrentItem state, the selector won't know when to use the defaultValue. So the preselection never works for some reasons. I am a bit confused if it is a limit of the library or if it is some mistake a made. Here below the selector:

```<code>import { FC, useEffect, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemText,
  SelectPortal,
  SelectScrollDownButton,
  SelectScrollUpButton,
  SelectTrigger,
  SelectValue,
  SelectViewport
} from '@radix-ui/react-select';
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/outline';

import cn from 'classnames';
import { twMerge } from 'tailwind-merge';

interface SelectorClassNames {
  loadingClassName?: string;
  formButtonClassName?: string;
  selectedItemClassName?: string;
  selectContentClassName?: string;
  selectItemListClassName?: string;
}
export interface SelectChoice {
  value: string;
  label: string;
}

interface Props {
  defaultValue?: string;
  onChange?: (value: string) => void;
  classNames?: SelectorClassNames;
  selectChoices: SelectChoice[];
  name?: string;
  disabled?: boolean;
  value?: string;
}

const Selector: FC<Props> = ({
  defaultValue,
  onChange,
  classNames,
  selectChoices,
  name,
  disabled,
  value
}) => {
  const [currentItem, setCurrentItem] = useState<SelectChoice | undefined>(
    undefined
  );
  const [availableList, setAvailableList] = useState<SelectChoice[]>([]);
  const [opened, onOpenChange] = useState<boolean>(false);
  const selectTriggerProps = {
    className: twMerge(
      cn(
        'group flex items-center h-12 select-none rounded-lg bg-white px-4 text-left shadow-plain',
        classNames?.formButtonClassName,
        {
          'group hover:shadow-plain-lg cursor-pointer': !disabled,
          'stroke-inpay-black-haze-700 stroke-1.5 group hover:none text-inpay-black-haze-700':
            disabled,
          'bg-inpay-gray-100': disabled && currentItem?.value
        }
      )
    )
  };

  const selectedItemProps = {
    className: twMerge(
      cn(
        'group flex h-12 cursor-pointer items-center px-4 rounded-t-lg outline-offset-[-1px] hover:bg-inpay-green-200 hover:text-inpay-green-700 border-none focus:outline-none',
        classNames?.selectedItemClassName,
        {
          'px-4': disabled
        }
      )
    )
  };

  const selectItemListProps = {
    className: twMerge(
      cn(
        'group h-12 flex items-center cursor-pointer px-4 outline-offset-[-1px] first:rounded-t-lg last:rounded-b-lg hover:bg-inpay-green-200 hover:text-inpay-green-700 border-none focus:outline-none',
        classNames?.selectItemListClassName
      )
    )
  };

  const selectContentProps = {
    className: twMerge(
      cn(
        `${
          currentItem
            ? ' relative z-50 select-none overflow-hidden rounded-lg bg-white shadow-plain-lg w-72'
            : 'relative z-50 select-none overflow-hidden rounded-lg bg-white shadow-plain-lg w-72'
        }`,
        classNames?.selectContentClassName
      )
    )
  };
  const onValueChange = (value: string) => {
    if (selectChoices) {
      const matchingValue = selectChoices.find(
        (element) => element.value == value
      );
      if (matchingValue) {
        setCurrentItem({ ...matchingValue });
        setAvailableList(
          selectChoices.filter((i) => i.value != matchingValue.value)
        );
        onChange && onChange(value);
      }
    }
  };

  useEffect(() => {
    if (defaultValue) {
      console.log(selectChoices, 'selectChoices'); // gets logged correctly
      const newValue = selectChoices.find((i) => i.label === defaultValue);
      console.log(defaultValue, 'defaultValue'); // gets logged correctly
      if (!newValue) {
        console.error('can not find new value');
      }
      setCurrentItem(newValue);
      console.log(newValue, 'new value'); // gets logged correctly

      setAvailableList(selectChoices.filter((i) => i.value != defaultValue));
    }
  }, [defaultValue, selectChoices]);

  useEffect(() => {
    setAvailableList(selectChoices);
    setCurrentItem(undefined);
  }, [selectChoices]);

  return (
    <Select
      onValueChange={onValueChange}
      onOpenChange={onOpenChange}
      name={name}
      disabled={disabled}
      defaultValue={defaultValue}
      value={value}
    >
      <SelectTrigger {...selectTriggerProps}>
        <SelectValue
          placeholder={
            <div className="flex">
              <div className="flex-1"></div>
              <ChevronDownIcon
                className={cn('w-1/12 stroke-inpay-black-haze-700 stroke-1.5', {
                  'group-hover:stroke-inpay-black-500': !disabled
                })}
              />
            </div>
          }
        />
      </SelectTrigger>
      <SelectPortal>
        <SelectContent {...selectContentProps}>
          <SelectScrollUpButton className="flex justify-center">
            <ChevronUpIcon className="h-10 w-6 stroke-1.5" />
          </SelectScrollUpButton>
          <SelectViewport>
            {currentItem && (
              <SelectItem
                key={currentItem.value}
                value={currentItem.value}
                {...selectedItemProps}
              >
                <SelectItemText>
                  <div className="flex">
                    <div className="flex-1">
                      <div>{currentItem.label}</div>
                    </div>
                    {opened ? (
                      <ChevronUpIcon className="w-1/12 stroke-inpay-black-500 stroke-1.5" />
                    ) : (
                      <ChevronDownIcon className="w-1/12 stroke-inpay-black-haze-700 stroke-1.5 group-hover:stroke-inpay-black-500" />
                    )}
                  </div>
                </SelectItemText>
              </SelectItem>
            )}

            {availableList.map((item, index) => (
              <SelectItem
                key={item?.value}
                value={item.value}
                {...selectItemListProps}
              >
                <SelectItemText>
                  <div className="flex">
                    <div className="flex-1">{item.label}</div>
                    {index == 0 && !currentItem && (
                      <ChevronUpIcon className="w-1/12 stroke-inpay-black-500 stroke-1.5" />
                    )}
                  </div>
                </SelectItemText>
              </SelectItem>
            ))}
          </SelectViewport>
          <SelectScrollDownButton className="flex justify-center">
            <ChevronDownIcon className="h-10 w-6 stroke-1.5" />
          </SelectScrollDownButton>
        </SelectContent>
      </SelectPortal>
    </Select>
  );
};

export default Selector;
</code>```

Any clues ?

Body:
I have this component where I render 3 different selectors depending on the data I pass. The first selector once clicked, gets the data of the second one (without selection), the same for the second, and so on. What I am trying to achieve is that, if I select the first dropdown && the second one has only one item in the list I get that value will be pre-selected without letting the user select it by himself.

This is the parent component where I pass the default value to each selector:

const CreateBatchTemplateDialog: FC<Props> = ({ open, onClose }) => {
  const [localInstruments, setLocalInstruments] = useState<LocalInstrument[]>();
  const [corridors, setCorridors] = useState<Corridor[]>();
  const [corridorId, setCorridorId] = useState<string>();
  const [productSchemas, setProductSchemas] = useState<ProductSchema[]>();
  const [dowloaded, setDowloaded] = useState<boolean>(false);
  const { data: localInstrumentsData } = useGetLocalInstrumentsQuery();
  const downloadFile = useDownloadFile();

  const [getProductSchemas] = useLazyGetProductSchemasQuery();

  const fetchingProductSchemaData = async () => {
    try {
      const { data: productSchema } = await getProductSchemas(corridorId);
      setProductSchemas(productSchema.data);
    } catch (error: any) {
      console.error(error);
    }
  };
  useEffect(() => {
    if (corridorId) {
      fetchingProductSchemaData();
    }
  }, [corridorId]);

  useEffect(() => {
    if (localInstrumentsData?.data) {
      setLocalInstruments(localInstrumentsData.data);
    }
    setProductSchemas([]);
  }, [localInstrumentsData]);

  const {
    handleSubmit,
    setError,
    formState,
    setValue,
    reset: resetForm,
    getValues
  } = useForm<Inputs>({
    mode: 'onSubmit',
    resolver: yupResolver(schema)
  });

  const localInstrumentsOptions = useMemo(() => {
    setProductSchemas([]);
    return Array.isArray(localInstruments)
      ? localInstruments.map((i) => ({ label: i.name, value: i.name }))
      : [];
  }, [localInstruments]);

  const corridorsOptions = useMemo<SelectChoice[]>(() => {
    setProductSchemas([]);
    return Array.isArray(corridors)
      ? corridors.map((i) => ({
          label: i.label,
          value: i.id.toString()
        }))
      : [];
  }, [corridors, localInstruments]);

  const productSchemasOptions = useMemo(() => {
    return Array.isArray(productSchemas)
      ? productSchemas.map((i) => ({
          label: i.label,
          value: i.id.toString()
        }))
      : [];
  }, [productSchemas, corridors, localInstruments]);

  const onLocalInstrumentChange = (value: string) => {
    setDowloaded(false);
    setProductSchemas([]);
    setCorridorId(undefined);

    const corridorData = localInstruments?.find((i) => i.name === value);
    setCorridors(corridorData ? corridorData.products : []);

    setValue('localInstrument', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
    setValue('corridor', '', {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onCorridorChange = (value: string) => {
    setDowloaded(false);
    setCorridorId(value);
    setProductSchemas([]);
    setValue('corridor', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
    setValue('productSchema', '', {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onProductSchemaChange = (value: string) => {
    setDowloaded(false);
    setValue('productSchema', value, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };

  const onSubmit: FormEventHandler<HTMLFormElement> = async (event: any) => {
    try {
      await handleSubmit(async (data) => {
        downloadFile(`payouts/schemas/${data.productSchema}/csv_template`);
        setDowloaded(true);
      })(event);
    } catch (error: any) {
      setTimeout(
        () =>
          setFormErrors({
            error,
            setError,
            fields: Object.keys(schema.fields)
          }),
        50
      );
    }
  };

  const onDialogClose = (value: boolean) => {
    resetForm();
    onClose(value);
    setLocalInstruments([]);
    setCorridors([]);
    setCorridorId(undefined);
    setProductSchemas([]);
    setDowloaded(false);
  };

  return (
    <Dialog open={open} onOpenChange={onDialogClose}>
      <DialogPortal>
        <DialogOverlay className="fixed inset-0 z-50 bg-inpay-green-700/90">
          <DialogContent
            onClick={(e) => e.stopPropagation()}
            className="fixed top-[50%] left-[50%] translate-y-[-50%] translate-x-[-50%] rounded-lg shadow-[0_0_6px_#B7BCBA]"
          >
            <DialogTitle className="flex h-12 items-center justify-between rounded-t-lg border-b border-b-inpay-pumice bg-white px-6">
              <DownloadIcon className="w-8 stroke-1 group-hover:stroke-1.5" />
              Create batch template
              <DialogClose
                aria-label="Close"
                className="outline-none focus:outline-none"
              >
                <XIcon className="-m-1 h-8 w-8 outline-none focus:outline-none" />
              </DialogClose>
            </DialogTitle>

                <form onSubmit={onSubmit} autoComplete="off">

                    Format
                    <CsvSelector />

                    Transfer type
                    <Selector
                      selectChoices={localInstrumentsOptions}
                      onChange={onLocalInstrumentChange}
                      name="localInstruments"
                      disabled={
                        !localInstrumentsOptions ||
                        localInstrumentsOptions.length === 0
                      }
                      defaultValue={
                        localInstrumentsOptions?.length === 1
                          ? localInstrumentsOptions[0].value
                          : undefined
                      }
                    />

                    Corridor
                    <Selector
                      selectChoices={corridorsOptions}
                      onChange={onCorridorChange}
                      name="corridor"
                      disabled={
                        !corridorsOptions || corridorsOptions.length === 0
                      }
                      value={getValues('corridor')}
                      defaultValue={
                        corridorsOptions?.length === 1
                          ? corridorsOptions[0].label
                          : undefined
                      }
                    />
                    {console.log(
                      corridorsOptions?.length === 1
                        ? corridorsOptions[0].label
                        : undefined
                    )}

                    Data required
                    <Selector
                      selectChoices={productSchemasOptions}
                      onChange={onProductSchemaChange}
                      name="productSchema"
                      disabled={
                        !productSchemasOptions ||
                        productSchemasOptions.length === 0
                      }
                      value={getValues('productSchema')}
                      defaultValue={
                        productSchemasOptions?.length === 1
                          ? productSchemasOptions[0].label
                          : undefined
                      }
                    />

                  {dowloaded === false ? (
                    <button
                      type="submit"
                      className="inpay-button w-full"
                      disabled={!formState.isValid}
                    >
                      Download CSV template
                    </button>
                  ) : (
                    <button
                      type="submit"
                      className="inpay-button w-full"
                      onClick={() => onClose(false)}
                    >
                      CSV dowloaded, close window
                    </button>
                  )}

                  {formState.errors.base && (

                      {formState.errors.base.message}

                  )}
                </form>

          </DialogContent>
        </DialogOverlay>
      </DialogPortal>
    </Dialog>
  );
};

This is the child component where I render the Selector, the issue is that even though the default value (string) and the matchingValue (object) are logged in the useEffect, matched and passed to the setCurrentItem state, the selector won't know when to use the defaultValue. So the preselection never works for some reasons. I am a bit confused if it is a limit of the library or if it is some mistake a made. Here below the selector:

import { FC, useEffect, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemText,
  SelectPortal,
  SelectScrollDownButton,
  SelectScrollUpButton,
  SelectTrigger,
  SelectValue,
  SelectViewport
} from '@radix-ui/react-select';
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/outline';

import cn from 'classnames';
import { twMerge } from 'tailwind-merge';

interface SelectorClassNames {
  loadingClassName?: string;
  formButtonClassName?: string;
  selectedItemClassName?: string;
  selectContentClassName?: string;
  selectItemListClassName?: string;
}
export interface SelectChoice {
  value: string;
  label: string;
}

interface Props {
  defaultValue?: string;
  onChange?: (value: string) => void;
  classNames?: SelectorClassNames;
  selectChoices: SelectChoice[];
  name?: string;
  disabled?: boolean;
  value?: string;
}

const Selector: FC<Props> = ({
  defaultValue,
  onChange,
  classNames,
  selectChoices,
  name,
  disabled,
  value
}) => {
  const [currentItem, setCurrentItem] = useState<SelectChoice | undefined>(
    undefined
  );
  const [availableList, setAvailableList] = useState<SelectChoice[]>([]);
  const [opened, onOpenChange] = useState<boolean>(false);
  const selectTriggerProps = {
    className: twMerge(
      cn(
        'group flex items-center h-12 select-none rounded-lg bg-white px-4 text-left shadow-plain',
        classNames?.formButtonClassName,
        {
          'group hover:shadow-plain-lg cursor-pointer': !disabled,
          'stroke-inpay-black-haze-700 stroke-1.5 group hover:none text-inpay-black-haze-700':
            disabled,
          'bg-inpay-gray-100': disabled && currentItem?.value
        }
      )
    )
  };

  const selectedItemProps = {
    className: twMerge(
      cn(
        'group flex h-12 cursor-pointer items-center px-4 rounded-t-lg outline-offset-[-1px] hover:bg-inpay-green-200 hover:text-inpay-green-700 border-none focus:outline-none',
        classNames?.selectedItemClassName,
        {
          'px-4': disabled
        }
      )
    )
  };

  const selectItemListProps = {
    className: twMerge(
      cn(
        'group h-12 flex items-center cursor-pointer px-4 outline-offset-[-1px] first:rounded-t-lg last:rounded-b-lg hover:bg-inpay-green-200 hover:text-inpay-green-700 border-none focus:outline-none',
        classNames?.selectItemListClassName
      )
    )
  };

  const selectContentProps = {
    className: twMerge(
      cn(
        `${
          currentItem
            ? ' relative z-50 select-none overflow-hidden rounded-lg bg-white shadow-plain-lg w-72'
            : 'relative z-50 select-none overflow-hidden rounded-lg bg-white shadow-plain-lg w-72'
        }`,
        classNames?.selectContentClassName
      )
    )
  };
  const onValueChange = (value: string) => {
    if (selectChoices) {
      const matchingValue = selectChoices.find(
        (element) => element.value == value
      );
      if (matchingValue) {
        setCurrentItem({ ...matchingValue });
        setAvailableList(
          selectChoices.filter((i) => i.value != matchingValue.value)
        );
        onChange && onChange(value);
      }
    }
  };

  useEffect(() => {
    if (defaultValue) {
      console.log(selectChoices, 'selectChoices'); // gets logged correctly
      const newValue = selectChoices.find((i) => i.label === defaultValue);
      console.log(defaultValue, 'defaultValue'); // gets logged correctly
      if (!newValue) {
        console.error('can not find new value');
      }
      setCurrentItem(newValue);
      console.log(newValue, 'new value'); // gets logged correctly

      setAvailableList(selectChoices.filter((i) => i.value != defaultValue));
    }
  }, [defaultValue, selectChoices]);

  useEffect(() => {
    setAvailableList(selectChoices);
    setCurrentItem(undefined);
  }, [selectChoices]);

  return (
    <Select
      onValueChange={onValueChange}
      onOpenChange={onOpenChange}
      name={name}
      disabled={disabled}
      defaultValue={defaultValue}
      value={value}
    >
      <SelectTrigger {...selectTriggerProps}>
        <SelectValue
          placeholder={

              <ChevronDownIcon
                className={cn('w-1/12 stroke-inpay-black-haze-700 stroke-1.5', {
                  'group-hover:stroke-inpay-black-500': !disabled
                })}
              />

          }
        />
      </SelectTrigger>
      <SelectPortal>
        <SelectContent {...selectContentProps}>
          <SelectScrollUpButton className="flex justify-center">
            <ChevronUpIcon className="h-10 w-6 stroke-1.5" />
          </SelectScrollUpButton>
          <SelectViewport>
            {currentItem && (
              <SelectItem
                key={currentItem.value}
                value={currentItem.value}
                {...selectedItemProps}
              >
                <SelectItemText>

{currentItem.label}

                    {opened ? (
                      <ChevronUpIcon className="w-1/12 stroke-inpay-black-500 stroke-1.5" />
                    ) : (
                      <ChevronDownIcon className="w-1/12 stroke-inpay-black-haze-700 stroke-1.5 group-hover:stroke-inpay-black-500" />
                    )}

                </SelectItemText>
              </SelectItem>
            )}

            {availableList.map((item, index) => (
              <SelectItem
                key={item?.value}
                value={item.value}
                {...selectItemListProps}
              >
                <SelectItemText>

{item.label}

                    {index == 0 && !currentItem && (
                      <ChevronUpIcon className="w-1/12 stroke-inpay-black-500 stroke-1.5" />
                    )}

                </SelectItemText>
              </SelectItem>
            ))}
          </SelectViewport>
          <SelectScrollDownButton className="flex justify-center">
            <ChevronDownIcon className="h-10 w-6 stroke-1.5" />
          </SelectScrollDownButton>
        </SelectContent>
      </SelectPortal>
    </Select>
  );
};

export default Selector;

Any clues ?


问:
How do I get my images to fit into my rows and columns of my bootstrap grid?
I have searched SO for this answer and could not find something specific enough that works. I saw there were a lot of similar questions, but none that lead me to a working solution. I am sorry if this is a duplicate

I am trying to replicate the feature elements from the MySpace homepage (https://myspace.com/). I am trying to get one main feature image on the left and two smaller elements (img and video) on the right. The images should go flush against each other with each column being the same height. The grid should be responsive to the changes in size of the web broser so it stays centered, proportionate, and flush.

I am using the Bootstrap 5 grid system. I have a container with a main row. That row contains two columns. The left column is for the main image. The right column holds two more rows. The top row has an image, the bottom row has an iframe.

I have used object-fit: cover, overflow:hidden, max-width: some value, max-height: auto (and vice-versa), and all combinations of rows/cols.

I've spent hours Googling and looking up examples and YouTube videos. Everything is showing basic concepts but nothing with examples in ReactJS or that are at my lower skill level.

This feels like it should be super easy and it has been the hardest thing I've had. I have even been staring at the HTML in the devtools of the MySpace page to see if I can reverse-engineer it.

```<code>import React from "react";
import Feature from "../page/Feature";
import { IMAGES_BANDS, VIDEOS_HIGHLIGHTS } from "../../images/images";

export default function Bands() {
  return (
    <>
      <div className="container">
        <div className="row">
          <Feature
            IMAGES_FEATURE={IMAGES_BANDS}
            IMAGE_HIGHLIGHT={IMAGES_BANDS[0].image}
            VIDEO_HIGHLIGHT={VIDEOS_HIGHLIGHTS[0].video}
          />
        </div>
      </div>
    </>
  );
}

</code>```
```<code>    import React from "react";
    import Slider from "../page/Slider";

    export default function Feature(props) {
      const { IMAGES_FEATURE, IMAGE_HIGHLIGHT, VIDEO_HIGHLIGHT } = props;
      return (
        <>
          <div className="container image-fit-cover no-margin-padding">
            <div className="row row-cols-2 justify-content-center row-size-feature">
              <div className="col-8">
                <Slider images={IMAGES_FEATURE} />
              </div>
              <div className="col-4">
                <div className="row">
                  <img src={IMAGE_HIGHLIGHT} alt="band-highlight" />
                </div>
                <div className="row">
                  <iframe
                    src={VIDEO_HIGHLIGHT}
                    title="YouTube video player"
                    frameBorder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope;     picture-in-picture; web-share"
                    allowFullScreen
                  />
                </div>
              </div>
            </div>
          </div>
        </>
      );
    }
</code>```
```<code>    .App {
      text-align: center;
    }

    .App-logo {
      height: 40vmin;
      pointer-events: none;
    }

    @media (prefers-reduced-motion: no-preference) {
      .App-logo {
        animation: App-logo-spin infinite 20s linear;
      }
    }

    .App-header {
      background-color: #282c34;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: calc(10px + 2vmin);
      color: white;
    }

    .App-link {
      color: #61dafb;
    }

    @keyframes App-logo-spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }

    .colors-theme {
      background-color: black !important;
        color: white !important;
    }

    .btn-theme {
      background-color: white;
      color: #000000;
      display: inline-block;
      font-weight: 400;
      text-align: center
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: .375rem .75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: .25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
      text-decoration: none
    }

    .btn-theme:focus,
    .btn-theme:hover {
      text-decoration: none;
      background-color: #944dff;
      color: #e0ccff;
    }

    .btn-theme-dark {
      color: white;
      background-color: black;
      display: inline-block;
      font-weight: 400;
      text-align: center;
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: .375rem .75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: .25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out
    }

    .btn-theme-dark:focus,
    .btn-theme-dark:hover {
      text-decoration: none;
      color: black;
      background-color: #e0f2f1;
    }

    .btn-link-theme {
      font-weight: 400;
      color: #f0e6ff;
      background-color: transparent;
      border-color: transparent;
      text-decoration: none;
      padding: 0px;
    }

    .btn-link-theme:hover {
      color: gray;
      text-decoration: underline;
      background-color: transparent;
      border-color: transparent
    }

    .navbar-search-form {
      justify-content: flex-end;
    }

    .float-right{
      float: right;
    }

    /*slider css*/
    .slider {
      position: relative;
      margin-top: 10px;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

.    right-arrow {
      position: absolute;
      top: 50%;
      right: 5px;
      font-size: 1rem;
      color: black;
      z-index: 10;
      cursor: pointer;
      user-select: none;
    }

    .left-arrow {
      position: absolute;
      top: 50%;
      left: 5px;
      font-size: 1rem;
      color: black;
      z-index: 10;
      cursor: pointer;
      user-select: none;
    }

    .slide {
      opacity: 0;
      transition-duration: 2s ease;
    }

    .slide.active {
      opacity: 1;
      transition-duration: 2s;
      transform: scale(1.00);
    }

    /**/
    .text-overlay-parent {
      position: relative;
      width: 100%;
      height: 100%;
    }

    .text-overlay-child{
      position: absolute;
      top: 15%;
      left: 10%;
    }

    .font-styles-heading{
      font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    }

    .row-size-feature{
      height: 360px;
    }

    .image-fit-cover img {
      height:auto;
      max-width:700px;
      overflow: hidden;
      object-fit: cover;
    }

    .image-fit-cover iframe {
      height: auto;
      max-width: 700px;
      overflow: hidden;
      object-fit: cover;
    }

    .no-margin-padding * {
     margin: 0px;
     padding: 0px;
    }
</code>```

img of current page

Body:
I have searched SO for this answer and could not find something specific enough that works. I saw there were a lot of similar questions, but none that lead me to a working solution. I am sorry if this is a duplicate

I am trying to replicate the feature elements from the MySpace homepage (https://myspace.com/). I am trying to get one main feature image on the left and two smaller elements (img and video) on the right. The images should go flush against each other with each column being the same height. The grid should be responsive to the changes in size of the web broser so it stays centered, proportionate, and flush.

I am using the Bootstrap 5 grid system. I have a container with a main row. That row contains two columns. The left column is for the main image. The right column holds two more rows. The top row has an image, the bottom row has an iframe.

I have used object-fit: cover, overflow:hidden, max-width: some value, max-height: auto (and vice-versa), and all combinations of rows/cols.

I've spent hours Googling and looking up examples and YouTube videos. Everything is showing basic concepts but nothing with examples in ReactJS or that are at my lower skill level.

This feels like it should be super easy and it has been the hardest thing I've had. I have even been staring at the HTML in the devtools of the MySpace page to see if I can reverse-engineer it.

import React from "react";
import Feature from "../page/Feature";
import { IMAGES_BANDS, VIDEOS_HIGHLIGHTS } from "../../images/images";

export default function Bands() {
  return (
    <>

          <Feature
            IMAGES_FEATURE={IMAGES_BANDS}
            IMAGE_HIGHLIGHT={IMAGES_BANDS[0].image}
            VIDEO_HIGHLIGHT={VIDEOS_HIGHLIGHTS[0].video}
          />

    </>
  );
}

    import React from "react";
    import Slider from "../page/Slider";

    export default function Feature(props) {
      const { IMAGES_FEATURE, IMAGE_HIGHLIGHT, VIDEO_HIGHLIGHT } = props;
      return (
        <>

                <Slider images={IMAGES_FEATURE} />

        </>
      );
    }

    .App {
      text-align: center;
    }

    .App-logo {
      height: 40vmin;
      pointer-events: none;
    }

    @media (prefers-reduced-motion: no-preference) {
      .App-logo {
        animation: App-logo-spin infinite 20s linear;
      }
    }

    .App-header {
      background-color: #282c34;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: calc(10px + 2vmin);
      color: white;
    }

    .App-link {
      color: #61dafb;
    }

    @keyframes App-logo-spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }

    .colors-theme {
      background-color: black !important;
        color: white !important;
    }

    .btn-theme {
      background-color: white;
      color: #000000;
      display: inline-block;
      font-weight: 400;
      text-align: center
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: .375rem .75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: .25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
      text-decoration: none
    }

    .btn-theme:focus,
    .btn-theme:hover {
      text-decoration: none;
      background-color: #944dff;
      color: #e0ccff;
    }

    .btn-theme-dark {
      color: white;
      background-color: black;
      display: inline-block;
      font-weight: 400;
      text-align: center;
      white-space: nowrap;
      vertical-align: middle;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      border: 1px solid transparent;
      padding: .375rem .75rem;
      font-size: 1rem;
      line-height: 1.5;
      border-radius: .25rem;
      transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out
    }

    .btn-theme-dark:focus,
    .btn-theme-dark:hover {
      text-decoration: none;
      color: black;
      background-color: #e0f2f1;
    }

    .btn-link-theme {
      font-weight: 400;
      color: #f0e6ff;
      background-color: transparent;
      border-color: transparent;
      text-decoration: none;
      padding: 0px;
    }

    .btn-link-theme:hover {
      color: gray;
      text-decoration: underline;
      background-color: transparent;
      border-color: transparent
    }

    .navbar-search-form {
      justify-content: flex-end;
    }

    .float-right{
      float: right;
    }

    /*slider css*/
    .slider {
      position: relative;
      margin-top: 10px;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

.    right-arrow {
      position: absolute;
      top: 50%;
      right: 5px;
      font-size: 1rem;
      color: black;
      z-index: 10;
      cursor: pointer;
      user-select: none;
    }

    .left-arrow {
      position: absolute;
      top: 50%;
      left: 5px;
      font-size: 1rem;
      color: black;
      z-index: 10;
      cursor: pointer;
      user-select: none;
    }

    .slide {
      opacity: 0;
      transition-duration: 2s ease;
    }

    .slide.active {
      opacity: 1;
      transition-duration: 2s;
      transform: scale(1.00);
    }

    /**/
    .text-overlay-parent {
      position: relative;
      width: 100%;
      height: 100%;
    }

    .text-overlay-child{
      position: absolute;
      top: 15%;
      left: 10%;
    }

    .font-styles-heading{
      font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    }

    .row-size-feature{
      height: 360px;
    }

    .image-fit-cover img {
      height:auto;
      max-width:700px;
      overflow: hidden;
      object-fit: cover;
    }

    .image-fit-cover iframe {
      height: auto;
      max-width: 700px;
      overflow: hidden;
      object-fit: cover;
    }

    .no-margin-padding * {
     margin: 0px;
     padding: 0px;
    }

img of current page