问:
error: Type of the parameter must be a class annotated with @Entity or a collection/array of it
I'm facing this Error when I used the suspend keyword with the insert() method in Kotlin. I researched a lot but can't understand the best solution that how I resolve this. Kindly if you people have any best solution against this error. Please suggest/help me, how I can resolve this.

Error Text

```<code>error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    kotlin.coroutines.Continuation<? super java.lang.Long> continuation);
</code>```
```<code>error: Not sure how to handle insert method's return type.
    public abstract java.lang.Object insertConfCard(@org.jetbrains.annotations.NotNull()
</code>```
```<code>Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)
</code>```

My DAO

```<code>@Dao
interface ConfCardDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertConfCard(confCard: ConfCard): Long
}
</code>```

Generated DAO

```<code>import java.lang.System;

@androidx.room.Dao()
@kotlin.Metadata(mv = {1, 7, 1}, k = 1, d1 = {"\u0000\u0018\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\t\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\bg\u0018\u00002\u00020\u0001J\u0019\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u0005H\u00a7@\u00f8\u0001\u0000\u00a2\u0006\u0002\u0010\u0006\u0082\u0002\u0004\n\u0002\b\u0019\u00a8\u0006\u0007"}, d2 = {"Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCardDao;", "", "insertConfCard", "", "confCard", "Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCard;", "(Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCard;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "app_debug"})
public abstract interface ConfCardDao {

    @org.jetbrains.annotations.Nullable()
    @androidx.room.Insert(onConflict = androidx.room.OnConflictStrategy.REPLACE)
    public abstract java.lang.Object insertConfCard(@org.jetbrains.annotations.NotNull()
    com.example.stid_settings_kotlin.datamodel.data.local.ConfCard confCard, @org.jetbrains.annotations.NotNull()
    kotlin.coroutines.Continuation<? super java.lang.Long> continuation);
}
</code>```

My build.gradle(:app)

```<code>dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//    implementation "com.squareup.okhttp3:okhttp:4.9.0"

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

    // Coroutine Lifecycle Scopes
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"

    // Room
    implementation "androidx.room:room-runtime:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"

    // optional - Kotlin Extensions and Coroutines support for Room -- use room with coroutine
    implementation "androidx.room:room-ktx:2.3.0"
}
</code>```

My build.gradle(:Project)

```<code>plugins {
    id 'com.android.application' version '7.2.0' apply false
    id 'com.android.library' version '7.2.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My Entity Class

```<code>@Entity(tableName = "confcard", indices = [Index(value = ["confName"], unique = true)])
class ConfCard {

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0

    @NotNull
    var confName: String

    @NotNull
    var name: String

    @NotNull
    var pid: String

    @NotNull
    var pver: String

    @NotNull
    var data: String

    @NotNull
    var kNew: String

    @NotNull
    var kCur: String

    @NotNull
    var uuid: String

    @NotNull
    var type: String // ScbvsOCB

    @NotNull
    var tkNeeded: String

    @NotNull
    var originatingServer: String

    constructor() {
        this.id = 0
        this.confName = ""
        this.name = ""
        this.pid = ""
        this.pver = ""
        this.data = ""
        this.kNew = ""
        this.kCur = ""
        this.uuid = ""
        this.type = ""
        this.originatingServer = ""
        this.tkNeeded = ""
    }

    constructor(
        ConfName: String,
        Name: String,
        PartId: String,
        PartVer: String,
        Data: String,
        KNew: String,
        KCur: String,
        UUID: String,
        CardType: String,
        OriginatingServer: String,
        TkNeeded: String,
    ) {
        this.confName = ConfName
        this.name = Name
        this.pid = PartId
        this.pver = PartVer
        this.data = Data
        this.kNew = KNew
        this.kCur = KCur
        this.uuid = UUID
        this.type = CardType
        this.originatingServer = OriginatingServer
        this.tkNeeded = TkNeeded
    }

    @JvmName("getId1")
    fun getId(): Int = id

    @JvmName("setId1")
    fun setId(id: Int) {
        this.id = id
    }

    @JvmName("getConfName1")
    fun getConfName(): String = confName

    @JvmName("setConfName1")
    fun setConfName(confName: String) {
        this.confName = confName
    }

    @JvmName("getName1")
    fun getName(): String = name

    @JvmName("setName1")
    fun setName(name: String) {
        this.name = name
    }

    fun getPartId(): String = pid

    fun setPartId(pid: String) {
        this.pid = pid
    }

    fun getPartVer(): String = pver

    fun getPartVer(pver: String) {
        this.pver = pver
    }

    @JvmName("getData1")
    fun getData(): String = data

    @JvmName("setData1")
    fun setData(data: String) {
        this.data = data
    }

    @JvmName("getKNew1")
    fun getKNew(): String = kNew

    @JvmName("setKNew1")
    fun setKNew(kNew: String) {
        this.kNew = kNew
    }

    @JvmName("getKCur1")
    fun getKCur(): String = kCur

    @JvmName("setKCur1")
    fun setKCur(kCur: String) {
        this.kCur = kCur
    }

    fun getUUID(): String = uuid

    fun setUUID(uuid: String) {
        this.uuid = uuid
    }

    fun getCardType(): String = type

    fun setCardType(type: String) {
        this.type = type
    }

    @JvmName("getOriginatingServer1")
    fun getOriginatingServer(): String = originatingServer

    @JvmName("setOriginatingServer1")
    fun setOriginatingServer(originatingServer: String) {
        this.originatingServer = originatingServer
    }

    @JvmName("getTkNeeded1")
    fun getTkNeeded(): String = tkNeeded

    @JvmName("setTkNeeded1")
    fun setTkNeeded(tkNeeded: String) {
        this.tkNeeded = tkNeeded
    }
}
</code>```

Body:
I'm facing this Error when I used the suspend keyword with the insert() method in Kotlin. I researched a lot but can't understand the best solution that how I resolve this. Kindly if you people have any best solution against this error. Please suggest/help me, how I can resolve this.

Error Text

error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
    kotlin.coroutines.Continuation<? super java.lang.Long> continuation);

error: Not sure how to handle insert method's return type.
    public abstract java.lang.Object insertConfCard(@org.jetbrains.annotations.NotNull()

Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

My DAO

@Dao
interface ConfCardDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertConfCard(confCard: ConfCard): Long
}

Generated DAO

import java.lang.System;

@androidx.room.Dao()
@kotlin.Metadata(mv = {1, 7, 1}, k = 1, d1 = {"\u0000\u0018\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\t\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0002\bg\u0018\u00002\u00020\u0001J\u0019\u0010\u0002\u001a\u00020\u00032\u0006\u0010\u0004\u001a\u00020\u0005H\u00a7@\u00f8\u0001\u0000\u00a2\u0006\u0002\u0010\u0006\u0082\u0002\u0004\n\u0002\b\u0019\u00a8\u0006\u0007"}, d2 = {"Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCardDao;", "", "insertConfCard", "", "confCard", "Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCard;", "(Lcom/example/stid_settings_kotlin/datamodel/data/local/ConfCard;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "app_debug"})
public abstract interface ConfCardDao {

    @org.jetbrains.annotations.Nullable()
    @androidx.room.Insert(onConflict = androidx.room.OnConflictStrategy.REPLACE)
    public abstract java.lang.Object insertConfCard(@org.jetbrains.annotations.NotNull()
    com.example.stid_settings_kotlin.datamodel.data.local.ConfCard confCard, @org.jetbrains.annotations.NotNull()
    kotlin.coroutines.Continuation<? super java.lang.Long> continuation);
}

My build.gradle(:app)

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//    implementation "com.squareup.okhttp3:okhttp:4.9.0"

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

    // Coroutine Lifecycle Scopes
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"

    // Room
    implementation "androidx.room:room-runtime:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"

    // optional - Kotlin Extensions and Coroutines support for Room -- use room with coroutine
    implementation "androidx.room:room-ktx:2.3.0"
}

My build.gradle(:Project)

plugins {
    id 'com.android.application' version '7.2.0' apply false
    id 'com.android.library' version '7.2.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My Entity Class

@Entity(tableName = "confcard", indices = [Index(value = ["confName"], unique = true)])
class ConfCard {

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0

    @NotNull
    var confName: String

    @NotNull
    var name: String

    @NotNull
    var pid: String

    @NotNull
    var pver: String

    @NotNull
    var data: String

    @NotNull
    var kNew: String

    @NotNull
    var kCur: String

    @NotNull
    var uuid: String

    @NotNull
    var type: String // ScbvsOCB

    @NotNull
    var tkNeeded: String

    @NotNull
    var originatingServer: String

    constructor() {
        this.id = 0
        this.confName = ""
        this.name = ""
        this.pid = ""
        this.pver = ""
        this.data = ""
        this.kNew = ""
        this.kCur = ""
        this.uuid = ""
        this.type = ""
        this.originatingServer = ""
        this.tkNeeded = ""
    }

    constructor(
        ConfName: String,
        Name: String,
        PartId: String,
        PartVer: String,
        Data: String,
        KNew: String,
        KCur: String,
        UUID: String,
        CardType: String,
        OriginatingServer: String,
        TkNeeded: String,
    ) {
        this.confName = ConfName
        this.name = Name
        this.pid = PartId
        this.pver = PartVer
        this.data = Data
        this.kNew = KNew
        this.kCur = KCur
        this.uuid = UUID
        this.type = CardType
        this.originatingServer = OriginatingServer
        this.tkNeeded = TkNeeded
    }

    @JvmName("getId1")
    fun getId(): Int = id

    @JvmName("setId1")
    fun setId(id: Int) {
        this.id = id
    }

    @JvmName("getConfName1")
    fun getConfName(): String = confName

    @JvmName("setConfName1")
    fun setConfName(confName: String) {
        this.confName = confName
    }

    @JvmName("getName1")
    fun getName(): String = name

    @JvmName("setName1")
    fun setName(name: String) {
        this.name = name
    }

    fun getPartId(): String = pid

    fun setPartId(pid: String) {
        this.pid = pid
    }

    fun getPartVer(): String = pver

    fun getPartVer(pver: String) {
        this.pver = pver
    }

    @JvmName("getData1")
    fun getData(): String = data

    @JvmName("setData1")
    fun setData(data: String) {
        this.data = data
    }

    @JvmName("getKNew1")
    fun getKNew(): String = kNew

    @JvmName("setKNew1")
    fun setKNew(kNew: String) {
        this.kNew = kNew
    }

    @JvmName("getKCur1")
    fun getKCur(): String = kCur

    @JvmName("setKCur1")
    fun setKCur(kCur: String) {
        this.kCur = kCur
    }

    fun getUUID(): String = uuid

    fun setUUID(uuid: String) {
        this.uuid = uuid
    }

    fun getCardType(): String = type

    fun setCardType(type: String) {
        this.type = type
    }

    @JvmName("getOriginatingServer1")
    fun getOriginatingServer(): String = originatingServer

    @JvmName("setOriginatingServer1")
    fun setOriginatingServer(originatingServer: String) {
        this.originatingServer = originatingServer
    }

    @JvmName("getTkNeeded1")
    fun getTkNeeded(): String = tkNeeded

    @JvmName("setTkNeeded1")
    fun setTkNeeded(tkNeeded: String) {
        this.tkNeeded = tkNeeded
    }
}


来源: stackexchange

问:
How can I hide always select-container of select tag?
I' m coding in ASP.NET Core web application.
I have a multi select tag that its options are several barcodes.
I want user scan several barcodes by barcode scanner in this select input tag, but user can't see barcodes. After every scan select container will be opened and the scanned barcode does not show in input tag that user must scan this barcode again to select that barcode.

In fact, every barcode must be scanned twice, to show in selected items.
I guess, If select container opens never, then scanning does once.

How can I prevent this problem?

part of my view:

```<code>  <form id="Export" method="post">
     <div class="form-group">
        <label asp-for="BarcodeList" class="control-label"></label>
        <select asp-for="BarcodeList" asp-items="@ViewBag.Barcodes" class="form-control" id="txtBarcode" multiple>
        </select>
     </div>
     <div class="form-group">
       <button type="submit" asp-action="Export">Export</button>
     </div>
  </form>
</code>```

Edit(More Explanation)

In real world, user has several tags that a barcode is printed on every tag. He wants to scan barcodes of all tags continuously.

Currently he scan these barcodes in an excel file, and after every scan cursor automatically go to next cell and user doesn't need to do any extra work and with the most possible speed.

I want to simulated this in my code. I use multi select input instead excel cells (barcodes are limited and saved in database, so I populated select with whole of saved barcodes).

When user scan a barcode in select box, barcode is read and show in select box, but second scan cause to open dropdown menu of select tag (or select container), and user's scanning losts and doesn't read. In fact every barcode should be read twice.

I want to select container always stays closed, and never open that second scan doesn't cause opening this container. and every scan just read a barcode and show selected barcodes in select box.

ContentLicense: CC BY-SA 4.0

Body:
I' m coding in ASP.NET Core web application.
I have a multi select tag that its options are several barcodes.
I want user scan several barcodes by barcode scanner in this select input tag, but user can't see barcodes. After every scan select container will be opened and the scanned barcode does not show in input tag that user must scan this barcode again to select that barcode.

In fact, every barcode must be scanned twice, to show in selected items.
I guess, If select container opens never, then scanning does once.

How can I prevent this problem?

part of my view:

  <form id="Export" method="post">

        <select asp-for="BarcodeList" asp-items="@ViewBag.Barcodes" class="form-control" id="txtBarcode" multiple>
        </select>

       <button type="submit" asp-action="Export">Export</button>

  </form>

Edit(More Explanation)

In real world, user has several tags that a barcode is printed on every tag. He wants to scan barcodes of all tags continuously.

Currently he scan these barcodes in an excel file, and after every scan cursor automatically go to next cell and user doesn't need to do any extra work and with the most possible speed.

I want to simulated this in my code. I use multi select input instead excel cells (barcodes are limited and saved in database, so I populated select with whole of saved barcodes).

When user scan a barcode in select box, barcode is read and show in select box, but second scan cause to open dropdown menu of select tag (or select container), and user's scanning losts and doesn't read. In fact every barcode should be read twice.

I want to select container always stays closed, and never open that second scan doesn't cause opening this container. and every scan just read a barcode and show selected barcodes in select box.


问:
Disable mouse wheel event for panel scroll bar in c#
In panel, when label text exceed horizontal and vertical it create auto scroll bar horizontal and vertically. both scroll are link to each other so, when i move mouse scroll (mouse wheel) both scrolled but my requirement is to scrolled horizontally. Is there any way to do that??

I tried this one but it doesn't work....

```<code>panel.MouseWheel += delegate (object sender, MouseEventArgs e)
{
    ((HandledMouseEventArgs)e).Handled = false;
};
</code>```

Body:
In panel, when label text exceed horizontal and vertical it create auto scroll bar horizontal and vertically. both scroll are link to each other so, when i move mouse scroll (mouse wheel) both scrolled but my requirement is to scrolled horizontally. Is there any way to do that??

I tried this one but it doesn't work....

panel.MouseWheel += delegate (object sender, MouseEventArgs e)
{
    ((HandledMouseEventArgs)e).Handled = false;
};


问:
serial.write(msg) API is taking around one second time in python. Is there any chances to optimize the time?
Iam sending a request to controller using serial port (9600 baud rate) by using serial.write(msg).
It's taking around one second time to finish.

```<code>def Send_TPC_Cmd(msg):
    try:

        # print(str(datetime.datetime.now()) +": Sending Request...")
        if ser.isOpen():
            logging.info("is open")
            logging.info(str(datetime.datetime.now()) + ": Sending Request...")
            # ser.flushInput()
            # ser.flushOutput()
            ser.write(msg)
            logging.info(str(datetime.datetime.now()) + ": Request sent: " + str(msg.hex()))

</code>```

Can anyone please help to time optimized code.

Body:
Iam sending a request to controller using serial port (9600 baud rate) by using serial.write(msg).
It's taking around one second time to finish.

def Send_TPC_Cmd(msg):
    try:

        # print(str(datetime.datetime.now()) +": Sending Request...")
        if ser.isOpen():
            logging.info("is open")
            logging.info(str(datetime.datetime.now()) + ": Sending Request...")
            # ser.flushInput()
            # ser.flushOutput()
            ser.write(msg)
            logging.info(str(datetime.datetime.now()) + ": Request sent: " + str(msg.hex()))

Can anyone please help to time optimized code.


问:
Can't receive text from PostgreSQL into Excel via ODBC due to character coding problem (UTF-8 vs Win1250)
My base scenario is that I want to make an excel report with data from a PostgreSQL DB.
I get them via ODBC, making a simple linked table with PowerQuery.
For DSN I choose (None), then I write the connectio string and the SQL statement. Generally it works fine, but with one column, it doesn't. I recive the following error message:

```<code>ODBC: ERROR [22P05] ERROR: character with byte sequence 0xc2 0xb2 in encoding "UTF8" has no equivalent in encoding "WIN1250";Error while executing the query
</code>```

So that is clear, the source is in UTF-8 with characters that are not compatible with Win1250.

What I am looking for is a general solution either on DB or excel site.

The used SQL statement is a simple SELECT * FROM [view], so I can use any replacement or converting or anything just to be able to hanle it with transformations on the column. I can replace the view with function if that is better.

But it would be better, if you can suggest an excel site solution.
With it there is some criteria. That scenario, when "I get the data first in text, then I convert it to Win1250, then import to excel" wont't fit, and I need something which connects to the excel file itself, so if I move it to an other pc, it need to work too without any more modification.

Thanks for all the help!

Body:
My base scenario is that I want to make an excel report with data from a PostgreSQL DB.
I get them via ODBC, making a simple linked table with PowerQuery.
For DSN I choose (None), then I write the connectio string and the SQL statement. Generally it works fine, but with one column, it doesn't. I recive the following error message:

ODBC: ERROR [22P05] ERROR: character with byte sequence 0xc2 0xb2 in encoding "UTF8" has no equivalent in encoding "WIN1250";Error while executing the query

So that is clear, the source is in UTF-8 with characters that are not compatible with Win1250.

What I am looking for is a general solution either on DB or excel site.

The used SQL statement is a simple SELECT * FROM [view], so I can use any replacement or converting or anything just to be able to hanle it with transformations on the column. I can replace the view with function if that is better.

But it would be better, if you can suggest an excel site solution.
With it there is some criteria. That scenario, when "I get the data first in text, then I convert it to Win1250, then import to excel" wont't fit, and I need something which connects to the excel file itself, so if I move it to an other pc, it need to work too without any more modification.

Thanks for all the help!


问:
Discord.js command handling. Command handling dont work
I copied the code exactly from the official Discord.JS Guide. But the bot does not respond to the command in any way. How to solve it?

index.js:

```<code>const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

client.once(Events.ClientReady, () => {
    console.log('Ready!');
});

client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

client.login(token);
</code>```

config.json:

```<code>{
    "clientId": "my id",
    "guildId": "my id",
    "token": "my token"
}
</code>```

ping.js:

```<code>const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        return interaction.reply('Pong!');
    },
};
</code>```

I searched on the Internet, and even found something, but in an attempt to repeat this, the bot did not respond to commands, although it turned on calmly.

Body:
I copied the code exactly from the official Discord.JS Guide. But the bot does not respond to the command in any way. How to solve it?

index.js:

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

client.once(Events.ClientReady, () => {
    console.log('Ready!');
});

client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if (!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

client.login(token);

config.json:

{
    "clientId": "my id",
    "guildId": "my id",
    "token": "my token"
}

ping.js:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        return interaction.reply('Pong!');
    },
};

I searched on the Internet, and even found something, but in an attempt to repeat this, the bot did not respond to commands, although it turned on calmly.


问:
Binning via `geom_hex` an `geom_bin_2d` produce conflicting plots
I am trying to use binning to deal with overplotting with geom_hex an geom_bin_2d.

But I am getting conflicting plots with different areas of the plot showing more counts.

I understand that the binning by these two methods are different, but why are the plots so different ? How can I get more standardized plots for both so that the interpretation is not messed up?

Example 1

```<code>library(ggplot2)
bks = seq(from = 0, to = 10000, by = 1000)
d <- ggplot(diamonds, aes(carat, price))
d + geom_point(alpha = 0.01)
</code>```

```<code>d + geom_hex(bins = 40) + scale_fill_distiller(palette = "Spectral", breaks = bks)
d + geom_bin_2d(bins = 40) + scale_fill_distiller(palette = "Spectral", breaks = bks)
</code>```

```<code>d + geom_hex() + scale_fill_gradient(low = "blue", high = "red", limits = c(0, 6000))
d + geom_bin_2d() + scale_fill_gradient(low = "blue", high = "red", limits = c(0, 6000))
</code>```

Example 2

```<code>library(sf)
library(ggplot2)
library(rgbif)
library(maps)

# get gbif data
gdata <- occ_data(scientificName = "Aix sponsa", country = "US",
                  year="2020", limit = 5000)
gdata <- gdata$data

# prepare map
usa <- sf::st_as_sf(map('usa', plot = FALSE, fill = TRUE))
usa <- sf::st_transform(usa, sp::CRS("+init=epsg:4326"))

ggplot() +
  geom_sf(data = usa)

# Convert occurence data to sf
gdata_sf <- st_as_sf(gdata, coords = c('decimalLongitude', 'decimalLatitude'),
                     crs = st_crs(usa))

# Plot points
ggplot(usa) +
  geom_sf() +
  geom_sf(data = gdata_sf, alpha = 0.1)

</code>```

```<code>bks = seq(from = 0, to = 200, by = 50)

ggplot(usa) +
  geom_sf() +
  geom_bin_2d(data = gdata, aes(x = decimalLongitude, y = decimalLatitude,
                                fill = after_stat(count)),
              alpha = 0.8, colour = "white", bins = 40) +
  scale_fill_distiller(palette = "Spectral", limits = c(0, 200)) +
  geom_sf(data = gdata_sf, alpha = 0.1) +
  theme_void()

ggplot(usa) +
  geom_sf() +
  geom_hex(data = gdata, aes(x = decimalLongitude, y = decimalLatitude,
                             fill = after_stat(count)),
           alpha = 0.8, colour = "white", bins = 40) +
  scale_fill_distiller(palette = "Spectral", limits = c(0, 200)) +
  geom_sf(data = gdata_sf, alpha = 0.1) +
  theme_void()

</code>```

Body:
I am trying to use binning to deal with overplotting with geom_hex an geom_bin_2d.

But I am getting conflicting plots with different areas of the plot showing more counts.

I understand that the binning by these two methods are different, but why are the plots so different ? How can I get more standardized plots for both so that the interpretation is not messed up?

Example 1

library(ggplot2)
bks = seq(from = 0, to = 10000, by = 1000)
d <- ggplot(diamonds, aes(carat, price))
d + geom_point(alpha = 0.01)

d + geom_hex(bins = 40) + scale_fill_distiller(palette = "Spectral", breaks = bks)
d + geom_bin_2d(bins = 40) + scale_fill_distiller(palette = "Spectral", breaks = bks)

d + geom_hex() + scale_fill_gradient(low = "blue", high = "red", limits = c(0, 6000))
d + geom_bin_2d() + scale_fill_gradient(low = "blue", high = "red", limits = c(0, 6000))

Example 2

library(sf)
library(ggplot2)
library(rgbif)
library(maps)

# get gbif data
gdata <- occ_data(scientificName = "Aix sponsa", country = "US",
                  year="2020", limit = 5000)
gdata <- gdata$data

# prepare map
usa <- sf::st_as_sf(map('usa', plot = FALSE, fill = TRUE))
usa <- sf::st_transform(usa, sp::CRS("+init=epsg:4326"))

ggplot() +
  geom_sf(data = usa)

# Convert occurence data to sf
gdata_sf <- st_as_sf(gdata, coords = c('decimalLongitude', 'decimalLatitude'),
                     crs = st_crs(usa))

# Plot points
ggplot(usa) +
  geom_sf() +
  geom_sf(data = gdata_sf, alpha = 0.1)

bks = seq(from = 0, to = 200, by = 50)

ggplot(usa) +
  geom_sf() +
  geom_bin_2d(data = gdata, aes(x = decimalLongitude, y = decimalLatitude,
                                fill = after_stat(count)),
              alpha = 0.8, colour = "white", bins = 40) +
  scale_fill_distiller(palette = "Spectral", limits = c(0, 200)) +
  geom_sf(data = gdata_sf, alpha = 0.1) +
  theme_void()

ggplot(usa) +
  geom_sf() +
  geom_hex(data = gdata, aes(x = decimalLongitude, y = decimalLatitude,
                             fill = after_stat(count)),
           alpha = 0.8, colour = "white", bins = 40) +
  scale_fill_distiller(palette = "Spectral", limits = c(0, 200)) +
  geom_sf(data = gdata_sf, alpha = 0.1) +
  theme_void()


问:
How can I change the RGB channels from pointclouds.ply file with relative luminance?
I have separated the rgb channel into a new dataframe from x,y, z coord. Now I am stuck at iterating thw conversion calculations over 800k rows within the rgb dataframe. I dont know how to go through each of the element and convert them.

I have tried creating a loop over the dataframe and calculate them accordingly, but it doesnt change the values idk.

I have used the formulas given here: https://stackoverflow.com/a/56678483/12059118

p.s: I am a rookie so I know how ugly&stupıd my code looks like but that's just my starting :P

```<code>from pyntcloud import PyntCloud
import numpy as np
import pandas as pd

cloud = PyntCloud.from_file("longdress_vox10_1051.ply")
#print(cloud)

#scene = cloud.plot(return_scene=True)
data = cloud.points

df1 = data.iloc[:, 3:6]

df1= df1/255

for index, row in df1.iterrows():
    if row <= 0.04045:
        print(row)
        row = row/12.92
        print(row)
    else:
        row = ((row + 0.055)/1.055)**2.4
        print(row)
    print(row)

for i in range(len(df1)):
    print(i.type())

    if df1['red'][i] <= 0.04045:
        df1['red'][i]= df1['red']/12.92
    else:
        df1['red'][i] = ((df1['red'][i] + 0.055)/1.055)**2.4

            #print(df1.head(:3))

#df1['red'] = df1['red']*0.2126
#df1['green'] = df1['green']*0.7152
#df1['blue'] = df1['blue']*0.0722

</code>```

Body:
I have separated the rgb channel into a new dataframe from x,y, z coord. Now I am stuck at iterating thw conversion calculations over 800k rows within the rgb dataframe. I dont know how to go through each of the element and convert them.

I have tried creating a loop over the dataframe and calculate them accordingly, but it doesnt change the values idk.

I have used the formulas given here: https://stackoverflow.com/a/56678483/12059118

p.s: I am a rookie so I know how ugly&stupıd my code looks like but that's just my starting :P

from pyntcloud import PyntCloud
import numpy as np
import pandas as pd

cloud = PyntCloud.from_file("longdress_vox10_1051.ply")
#print(cloud)

#scene = cloud.plot(return_scene=True)
data = cloud.points

df1 = data.iloc[:, 3:6]

df1= df1/255

for index, row in df1.iterrows():
    if row <= 0.04045:
        print(row)
        row = row/12.92
        print(row)
    else:
        row = ((row + 0.055)/1.055)**2.4
        print(row)
    print(row)

for i in range(len(df1)):
    print(i.type())

    if df1['red'][i] <= 0.04045:
        df1['red'][i]= df1['red']/12.92
    else:
        df1['red'][i] = ((df1['red'][i] + 0.055)/1.055)**2.4

            #print(df1.head(:3))

#df1['red'] = df1['red']*0.2126
#df1['green'] = df1['green']*0.7152
#df1['blue'] = df1['blue']*0.0722


问:
How to create Firebase Dynamic Links using Maui.iOS?
I'm using .Net Maui with firebase to create a dynamic link for iOS. The error I'm getting is this one:

"Safari can not open this page because address is invalid"

Safari's alert

I entered the team id and created a random app store id, since the app is not deployed on app store. The URL: https://example.page.link/apple-app-site-association, is working just fine.
I added GoogleService-Info.plist in platform directory, iOS folder, just as instructed. I also added apple-app-site-association that looks like this:

```<code>{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appIDs": [ "TeamID.com.companyname.example"],
        "paths": [ "NOT /_/*", "/*" ]

      }
    ]
  },
  "webcredentials": {
    "apps": [ "TeamID.com.companyname.example" ]
  },

  "appclips": {
    "apps": [ "TeamID.com.companyname.example" ]
  }
}
</code>```

I don't know if i missed any step until now. Recently I added Entitlements.plist that looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:example.page.link</string>
    </array>
</dict>
</plist>
</code>```

With this I should do some sort of provisioning, but the apple account I have needs to be paid for that to work. Is there some tutorial that I can use for Maui with free provisioning? Or am i headed in the wrong direction? Did I miss a step?

Body:
I'm using .Net Maui with firebase to create a dynamic link for iOS. The error I'm getting is this one:

"Safari can not open this page because address is invalid"

Safari's alert

I entered the team id and created a random app store id, since the app is not deployed on app store. The URL: https://example.page.link/apple-app-site-association, is working just fine.
I added GoogleService-Info.plist in platform directory, iOS folder, just as instructed. I also added apple-app-site-association that looks like this:

{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appIDs": [ "TeamID.com.companyname.example"],
        "paths": [ "NOT /_/*", "/*" ]

      }
    ]
  },
  "webcredentials": {
    "apps": [ "TeamID.com.companyname.example" ]
  },

  "appclips": {
    "apps": [ "TeamID.com.companyname.example" ]
  }
}

I don't know if i missed any step until now. Recently I added Entitlements.plist that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:example.page.link</string>
    </array>
</dict>
</plist>

With this I should do some sort of provisioning, but the apple account I have needs to be paid for that to work. Is there some tutorial that I can use for Maui with free provisioning? Or am i headed in the wrong direction? Did I miss a step?


问:
Python calculator using tokens
I'm trying to figure out how to write a calculator program in python.
This is what we got to work with

Note: The program is only working for a very tiny set of operations.
You have to add and/or modify code in ALL functions as well as add
some new functions. Use the syntax charts when you write the
functions! However, the class SyntaxError is complete as well as
handling in main of SyntaxError and TokenError.

```<code>import math
from tokenize import TokenError
from MA2tokenizer import TokenizeWrapper

class SyntaxError(Exception):
    def __init__(self, arg):
        self.arg = arg
        super().__init__(self.arg)

def statement(wtok, variables):
    """ See syntax chart for statement"""
    result = assignment(wtok, variables)
    return result

def assignment(wtok, variables):
    """ See syntax chart for assignment"""
    result = expression(wtok, variables)
    return result

def expression(wtok, variables):
    """ See syntax chart for expression"""
    result = term(wtok, variables)
    while wtok.get_current() == '+':
        wtok.next()
        result = result + term(wtok, variables)
    return result

def term(wtok, variables):
    """ See syntax chart for term"""
    result = factor(wtok, variables)
    while wtok.get_current() == '*':
        wtok.next()
        result = result * factor(wtok, variables)
    return result

def factor(wtok, variables):
    """ See syntax chart for factor"""
    if wtok.get_current() == '(':
        wtok.next()
        result = assignment(wtok, variables)
        if wtok.get_current() != ')':
            raise SyntaxError("Expected ')'")
        else:
            wtok.next()

    elif wtok.is_number():
        result = float(wtok.get_current())
        wtok.next()

    else:
        raise SyntaxError(
            "Expected number or '('")
    return result

def main():
    """
    Handles:
       the iteration over input lines,
       commands like 'quit' and 'vars' and
       raised exceptions.
    Starts with reading the init file
    """

    print("Numerical calculator")
    variables = {"ans": 0.0, "E": math.e, "PI": math.pi}
    # Note: The unit test file initiate variables in this way. If your implementation
    # requires another initiation you have to update the test file accordingly.
    init_file = 'MA2init.txt'
    lines_from_file = ''
    try:
        with open(init_file, 'r') as file:
            lines_from_file = file.readlines()
    except FileNotFoundError:
        pass

    while True:
        if lines_from_file:
            line = lines_from_file.pop(0).strip()
            print('init  :', line)
        else:
            line = input('\nInput : ')
        if line == '' or line[0]=='#':
            continue
        wtok = TokenizeWrapper(line)

        if wtok.get_current() == 'quit':
            print('Bye')
            exit()
        else:
            try:
                result = statement(wtok, variables)
                variables['ans'] = result
                print('Result:', result)

            except SyntaxError as se:
                print("*** Syntax error: ", se)
                print(
                f"Error occurred at '{wtok.get_current()}' just after '{wtok.get_previous()}'")

            except TokenError as te:
                print('*** Syntax error: Unbalanced parentheses')

if __name__ == "__main__":
    main()

</code>```

I want to start with extending the program to work for - and /, and I tried to change expression to this:

```<code>def expression(wtok, variables):
    """ See syntax chart for expression"""
    result = term(wtok, variables)
    while wtok.get_current() == '+' or wtok.get_current() == '-':
        if wtok.get_current() == '+'
        wtok.next()
        result = result + term(wtok, variables)
        else
        wtok.next()
        result = result - term(wtok,variables)
    return result

def term(wtok, variables):
    """ See syntax chart for term"""
    result = factor(wtok, variables)
    while wtok.get_current() == '*' or wtok.get_current() == '/':
        if wtok.get_current() == '*'
        wtok.next()
        result = result * factor(wtok, variables)
        if wtok.get_current() == '/'
        wtok.next()
        result = result / factor(wtok, variables)
    return result
</code>```

just to see what happens, but it I write 4-3 I get 4.0. And if I write 6-4 I get 6.0. Why? And how do I do to make the calculator acctually calculate with the - ?

Title: Python calculator using tokens

Body:
I'm trying to figure out how to write a calculator program in python.
This is what we got to work with

Note: The program is only working for a very tiny set of operations.
You have to add and/or modify code in ALL functions as well as add
some new functions. Use the syntax charts when you write the
functions! However, the class SyntaxError is complete as well as
handling in main of SyntaxError and TokenError.

import math
from tokenize import TokenError
from MA2tokenizer import TokenizeWrapper

class SyntaxError(Exception):
    def __init__(self, arg):
        self.arg = arg
        super().__init__(self.arg)

def statement(wtok, variables):
    """ See syntax chart for statement"""
    result = assignment(wtok, variables)
    return result

def assignment(wtok, variables):
    """ See syntax chart for assignment"""
    result = expression(wtok, variables)
    return result

def expression(wtok, variables):
    """ See syntax chart for expression"""
    result = term(wtok, variables)
    while wtok.get_current() == '+':
        wtok.next()
        result = result + term(wtok, variables)
    return result

def term(wtok, variables):
    """ See syntax chart for term"""
    result = factor(wtok, variables)
    while wtok.get_current() == '*':
        wtok.next()
        result = result * factor(wtok, variables)
    return result

def factor(wtok, variables):
    """ See syntax chart for factor"""
    if wtok.get_current() == '(':
        wtok.next()
        result = assignment(wtok, variables)
        if wtok.get_current() != ')':
            raise SyntaxError("Expected ')'")
        else:
            wtok.next()

    elif wtok.is_number():
        result = float(wtok.get_current())
        wtok.next()

    else:
        raise SyntaxError(
            "Expected number or '('")
    return result

def main():
    """
    Handles:
       the iteration over input lines,
       commands like 'quit' and 'vars' and
       raised exceptions.
    Starts with reading the init file
    """

    print("Numerical calculator")
    variables = {"ans": 0.0, "E": math.e, "PI": math.pi}
    # Note: The unit test file initiate variables in this way. If your implementation
    # requires another initiation you have to update the test file accordingly.
    init_file = 'MA2init.txt'
    lines_from_file = ''
    try:
        with open(init_file, 'r') as file:
            lines_from_file = file.readlines()
    except FileNotFoundError:
        pass

    while True:
        if lines_from_file:
            line = lines_from_file.pop(0).strip()
            print('init  :', line)
        else:
            line = input('\nInput : ')
        if line == '' or line[0]=='#':
            continue
        wtok = TokenizeWrapper(line)

        if wtok.get_current() == 'quit':
            print('Bye')
            exit()
        else:
            try:
                result = statement(wtok, variables)
                variables['ans'] = result
                print('Result:', result)

            except SyntaxError as se:
                print("*** Syntax error: ", se)
                print(
                f"Error occurred at '{wtok.get_current()}' just after '{wtok.get_previous()}'")

            except TokenError as te:
                print('*** Syntax error: Unbalanced parentheses')

if __name__ == "__main__":
    main()

I want to start with extending the program to work for - and /, and I tried to change expression to this:

def expression(wtok, variables):
    """ See syntax chart for expression"""
    result = term(wtok, variables)
    while wtok.get_current() == '+' or wtok.get_current() == '-':
        if wtok.get_current() == '+'
        wtok.next()
        result = result + term(wtok, variables)
        else
        wtok.next()
        result = result - term(wtok,variables)
    return result

def term(wtok, variables):
    """ See syntax chart for term"""
    result = factor(wtok, variables)
    while wtok.get_current() == '*' or wtok.get_current() == '/':
        if wtok.get_current() == '*'
        wtok.next()
        result = result * factor(wtok, variables)
        if wtok.get_current() == '/'
        wtok.next()
        result = result / factor(wtok, variables)
    return result

just to see what happens, but it I write 4-3 I get 4.0. And if I write 6-4 I get 6.0. Why? And how do I do to make the calculator acctually calculate with the - ?


问:
How do I insert a wordpress post with '&' in the title
If I programmatically add a wordpress post with wp_insert_post and the title contains a & the & is converted to a &

For example: Tips & Tricks becomes Tips & Tricks

My only working solution is to do a $wpdb->update with the post title after the wp_insert_post. The parameters for the title are passed 1:1.

Is there a better way?


问:
Django add constraint for foreign key fields to match
In Django I have a model that links a tenant to a facility (house). The tenant and the facility needs to be in the same site (city) for this link to be valid. To enforce this I want to add a constraint that checks if the tenant's site and the facility's site matches.

I have tried to add a CheckConstraint to the model, but this compiles to a migration that is always false.

Model:

class TenantInFacility(models.Model):
    tenant = models.ForeignKey(Tenant, on_delete=models.DO_NOTHING)
    facility = models.ForeignKey(Facility, on_delete=models.DO_NOTHING)
    percentage_used = models.DecimalField(default=100, max_digits=6, decimal_places=3)
    start = models.DateTimeField(default=datetime.datetime.fromtimestamp(0))
    end = models.DateTimeField(default=None, blank=True, null=True)

    class Meta:
        verbose_name_plural = "tenants in facilities"
        constraints = [
            models.CheckConstraint(check=models.Q(models.F("tenant__site") == models.F("facility__site")),
                                   name='tenant_facility_sites_match')
        ]

    def __str__(self):
        return self.tenant.site.name + ": " + self.tenant.name + " in " + self.facility.name
```
<p>Migration:</p>
<pre class="lang-py prettyprint-override"><code>operations = [
    migrations.AddConstraint(
        model_name='tenantinfacility',
        constraint=models.CheckConstraint(check=models.Q(False), name='tenant_facility_sites_match'),
    ),
]
</code>```

Is there a way in Django to require a foreign key's foreign key to match another foreign key's foreign key.

In diagram form:

```<code>                        +----------+
                        | Tenant   |
                        +----------+
                       /            \
                      /              \
+--------------------+                +------+
| Tenant in Facility |                | Site |
+--------------------+                +------+
                      \              /
                       \            /
                        +----------+
                        | Facility |
                        +----------+
</code>```

Body:
In Django I have a model that links a tenant to a facility (house). The tenant and the facility needs to be in the same site (city) for this link to be valid. To enforce this I want to add a constraint that checks if the tenant's site and the facility's site matches.

I have tried to add a CheckConstraint to the model, but this compiles to a migration that is always false.

Model:

class TenantInFacility(models.Model):
    tenant = models.ForeignKey(Tenant, on_delete=models.DO_NOTHING)
    facility = models.ForeignKey(Facility, on_delete=models.DO_NOTHING)
    percentage_used = models.DecimalField(default=100, max_digits=6, decimal_places=3)
    start = models.DateTimeField(default=datetime.datetime.fromtimestamp(0))
    end = models.DateTimeField(default=None, blank=True, null=True)

    class Meta:
        verbose_name_plural = "tenants in facilities"
        constraints = [
            models.CheckConstraint(check=models.Q(models.F("tenant__site") == models.F("facility__site")),
                                   name='tenant_facility_sites_match')
        ]

    def __str__(self):
        return self.tenant.site.name + ": " + self.tenant.name + " in " + self.facility.name

Migration:

operations = [
    migrations.AddConstraint(
        model_name='tenantinfacility',
        constraint=models.CheckConstraint(check=models.Q(False), name='tenant_facility_sites_match'),
    ),
]

Is there a way in Django to require a foreign key's foreign key to match another foreign key's foreign key.

In diagram form:

                        +----------+
                        | Tenant   |
                        +----------+
                       /            \
                      /              \
+--------------------+                +------+
| Tenant in Facility |                | Site |
+--------------------+                +------+
                      \              /
                       \            /
                        +----------+
                        | Facility |
                        +----------+


问:
How to make all key values different when set all key values to be the same, when collecting json data
```<code>{
"a":{"b":14},
"a":{"b":36},
"a":{"b":123},
"a":{"b":635}
}
</code>```

About 500,000 key values are all "a", so data processing is difficult.
I want to change "a" to "a1","a2","a3","a4" in order.

I tried to solve it with python, but it was difficult.

Body:
{
"a":{"b":14},
"a":{"b":36},
"a":{"b":123},
"a":{"b":635}
}

About 500,000 key values are all "a", so data processing is difficult.
I want to change "a" to "a1","a2","a3","a4" in order.

I tried to solve it with python, but it was difficult.


问:
Find empty column
I want to find out what column of first row is empty.

```<code>Call getEmptyColumnFirstRow("E:\file.xlsx")

Function getEmptyColumnFirstRow(path)

Dim wks As Worksheet
Dim oApp_Excel As Excel.Application
Dim oBook As Excel.Workbook

Set oApp_Excel = CreateObject("EXCEL.APPLICATION")
oApp_Excel.DisplayAlerts = False
Set oBook = oApp_Excel.Workbooks.Open(path)
wks = oBook.Sheets("Sheet1")
Dim FirstEmptyCol As Long: FirstEmptyCol = wks.Cells.Find(What:="").column

End Function
</code>```

But I got this  error:

Object variable or with block variable not set.

Title: Find empty column

Body:
I want to find out what column of first row is empty.

Call getEmptyColumnFirstRow("E:\file.xlsx")

Function getEmptyColumnFirstRow(path)

Dim wks As Worksheet
Dim oApp_Excel As Excel.Application
Dim oBook As Excel.Workbook

Set oApp_Excel = CreateObject("EXCEL.APPLICATION")
oApp_Excel.DisplayAlerts = False
Set oBook = oApp_Excel.Workbooks.Open(path)
wks = oBook.Sheets("Sheet1")
Dim FirstEmptyCol As Long: FirstEmptyCol = wks.Cells.Find(What:="").column

End Function

But I got this  error:

Object variable or with block variable not set.


问:
apigateway couldn't display swagger-ui documentations with spring boot 3
I'm building microservices project using spring boot 3 and I have found some problems from api gateway.
when I type each service port I get swagger ui documentation but when I try access it's documentation from api the gateway I get this error "Failed to load remote configuration."

here is my springdoc config for
api-gatway :

```<code><!--    Swagger documentation Dependencies -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-common</artifactId>
    <version>3.0.0</version>
    <scope>compile</scope>
</dependency>
</code>```

gateway config:

```<code>@Configuration
@Primary
public class SwaggerConfig {
    public static final String API_URI = "/v3/api-docs";
    private final RouteDefinitionLocator routeLocator;
    public SwaggerConfig(RouteDefinitionLocator routeLocator) {
        this.routeLocator = routeLocator;
    }
    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("1.0");
        return swaggerResource;
    }
}

</code>```

gateway routing :

```<code>@Bean
DiscoveryClientRouteDefinitionLocator dynamicRoutes(ReactiveDiscoveryClient rdc, DiscoveryLocatorProperties dlp){
    return new DiscoveryClientRouteDefinitionLocator(rdc,dlp);
}

</code>```

backend services :

```<code><dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.9</version>
</dependency>
</code>```

expecting : enter image description here
but what i get
enter image description here
enter image description here

Body:
I'm building microservices project using spring boot 3 and I have found some problems from api gateway.
when I type each service port I get swagger ui documentation but when I try access it's documentation from api the gateway I get this error "Failed to load remote configuration."

here is my springdoc config for
api-gatway :

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-common</artifactId>
    <version>3.0.0</version>
    <scope>compile</scope>
</dependency>

gateway config:

@Configuration
@Primary
public class SwaggerConfig {
    public static final String API_URI = "/v3/api-docs";
    private final RouteDefinitionLocator routeLocator;
    public SwaggerConfig(RouteDefinitionLocator routeLocator) {
        this.routeLocator = routeLocator;
    }
    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("1.0");
        return swaggerResource;
    }
}

gateway routing :

@Bean
DiscoveryClientRouteDefinitionLocator dynamicRoutes(ReactiveDiscoveryClient rdc, DiscoveryLocatorProperties dlp){
    return new DiscoveryClientRouteDefinitionLocator(rdc,dlp);
}

backend services :

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.6.9</version>
</dependency>

expecting : enter image description here
but what i get
enter image description here
enter image description here


问:
SQL - Find duplicates within two separate groups of the same dataset within a lot of data
I have a table setup as this:

exportables

id
exportable_type
exportable_id
export_id

1
user
1
1

2
user
2
1

3
user
3
1

4
customer
1
2

5
customer
2
2

6
customer
3
2

7
customer
4
2

addressables (a morph table to attach addresses to different records)

id
exportable_type
exportable_id
address_id

1
user
1
1

2
user
2
2

3
user
3
2

4
customer
1
1

5
customer
2
3

6
customer
3
2

7
customer
4
2

These two tables can be joined on matching exportable_type and exportable_id. What I need to find are duplicates, based on the addressables.address_id between any two groups of exports, e.g. duplicates between export_id=1 and export_id IN (2,3,4). Ideally the query would return exportables.id of the duplicate in the first group and addressables.id (possibly multiple) found in the second group. In this case, it would return:

exportable_id
addressable_ids

1
4

2
6,7

3
6,7

I have written queries with like 4 convoluting LEFT JOINs, but the query took over 30 minutes to run - I need this to run in minutes against a dataset of 100+ million, so I am sure there is a smarter way to go about this?

Appreciate any help!


问:
Fast API + PySpark Deployment on Kuberentes
We are developing a FASTApi Rest project which will get a JSON in POST method and base don the inputs will run a transformation logic using PySpark.

```<code>def sparkConnection():

      conf = SparkConf().setAppName("PySpark App").setMaster("spark://XX.XXX.XX.XXX:7077).setAll([('spark.executor.cores', '4'),
     ('spark.cores.max', '80'),('spark.app.name','eio_kpi_dashboard'),
     ('spark.sql.execution.arrow.enabled', 'false'),])
     spark = SparkSession.builder.config(conf=conf).getOrCreate()
     return spark
</code>```

and then this context is called by the

```<code>  @network_kpis.post('/top-kpis', status_code=status.HTTP_201_CREATED)
  async def topkpisService(request: pydantic.Schema, db : Session = Depends(get_db)):
       results = serviceImpl.getTopKpis(request, DR, VTRC, KFR, db)
       return responseSchema(code=200, status='SUCCESS', message='API executed successfully',
                             result= results)

  def getTopKpis(request, DR, VTRC, kpi_table, db):

     try:

         jsonbody=jsonable_encoder(request)
         print(jsonbody)
         startDate = jsonbody['startDate'].split(' ')[0]
         spark = utils.sparkConnection()
</code>```

Then we are deploying this FastAPI service using DockerFile over Google Kubernetes cluster

```<code>   FROM ubuntu:22.04
   RUN apt-get update && \
       apt-get install libpq-dev && \
       apt-get install python3-dev && \
       apt-get -y install python3-pip

  WORKDIR /home/usr/app/
  COPY . .
  RUN pip install -r /home/usr/app/requirements.txt
  CMD ["uvicorn", "controller.main:app",  "--host", "0.0.0.0", "--port", "6098"]
  EXPOSE 6098
</code>```

However when we hit the service we are getting the following error of RuntimeError: Java gateway process exited before sending its port number.

Please note the Spark Master is running in a different Pod and FastAPI is running in a different pod.

Body:
We are developing a FASTApi Rest project which will get a JSON in POST method and base don the inputs will run a transformation logic using PySpark.

def sparkConnection():

      conf = SparkConf().setAppName("PySpark App").setMaster("spark://XX.XXX.XX.XXX:7077).setAll([('spark.executor.cores', '4'),
     ('spark.cores.max', '80'),('spark.app.name','eio_kpi_dashboard'),
     ('spark.sql.execution.arrow.enabled', 'false'),])
     spark = SparkSession.builder.config(conf=conf).getOrCreate()
     return spark

and then this context is called by the

  @network_kpis.post('/top-kpis', status_code=status.HTTP_201_CREATED)
  async def topkpisService(request: pydantic.Schema, db : Session = Depends(get_db)):
       results = serviceImpl.getTopKpis(request, DR, VTRC, KFR, db)
       return responseSchema(code=200, status='SUCCESS', message='API executed successfully',
                             result= results)

  def getTopKpis(request, DR, VTRC, kpi_table, db):

     try:

         jsonbody=jsonable_encoder(request)
         print(jsonbody)
         startDate = jsonbody['startDate'].split(' ')[0]
         spark = utils.sparkConnection()

Then we are deploying this FastAPI service using DockerFile over Google Kubernetes cluster

   FROM ubuntu:22.04
   RUN apt-get update && \
       apt-get install libpq-dev && \
       apt-get install python3-dev && \
       apt-get -y install python3-pip

  WORKDIR /home/usr/app/
  COPY . .
  RUN pip install -r /home/usr/app/requirements.txt
  CMD ["uvicorn", "controller.main:app",  "--host", "0.0.0.0", "--port", "6098"]
  EXPOSE 6098

However when we hit the service we are getting the following error of RuntimeError: Java gateway process exited before sending its port number.

Please note the Spark Master is running in a different Pod and FastAPI is running in a different pod.


问:
AIC criterion on a felm regression model
I have a regression model which was computed using the felm package.
Hence i have a "large felm" object in the environment

I want to compute the AIC criterion on it, how can i ?

i tried using this function which doesn't appear to work, it returns a "numeric(empty)" result

```<code>AIC_adj <- function(mod){
  # Number of observations
  n.N   <- nrow(mod$model)
  # Residuals vector
  u.hat <- residuals(mod)
  # Variance estimation
  s.sq  <- log( (sum(u.hat^2)/(n.N)))
  # Number of parameters (incl. constant) + one additional for variance estimation
  p     <-  length(coef(mod)) + 1

  # Note: minus sign cancels in log likelihood
  aic <- 2*p  +  n.N * (  log(2*pi) + s.sq  + 1 )

  return(aic)
}
</code>```

the model is given by

```<code>        G         D1         D2         D4         D5         D6   posratio     sd_ret       G:D1
 0.0832205 -0.0030118 -0.0006392  0.0007287  0.0004233 -0.0013440  0.0059718  0.2344416  0.0087144
      G:D2       G:D4       G:D5       G:D6 G:posratio   G:sd_ret
 0.0046054 -0.0028214 -0.0033844 -0.0076368 -0.0881973  0.6204865
</code>```

Body:
I have a regression model which was computed using the felm package.
Hence i have a "large felm" object in the environment

I want to compute the AIC criterion on it, how can i ?

i tried using this function which doesn't appear to work, it returns a "numeric(empty)" result

AIC_adj <- function(mod){
  # Number of observations
  n.N   <- nrow(mod$model)
  # Residuals vector
  u.hat <- residuals(mod)
  # Variance estimation
  s.sq  <- log( (sum(u.hat^2)/(n.N)))
  # Number of parameters (incl. constant) + one additional for variance estimation
  p     <-  length(coef(mod)) + 1

  # Note: minus sign cancels in log likelihood
  aic <- 2*p  +  n.N * (  log(2*pi) + s.sq  + 1 )

  return(aic)
}

the model is given by

        G         D1         D2         D4         D5         D6   posratio     sd_ret       G:D1
 0.0832205 -0.0030118 -0.0006392  0.0007287  0.0004233 -0.0013440  0.0059718  0.2344416  0.0087144
      G:D2       G:D4       G:D5       G:D6 G:posratio   G:sd_ret
 0.0046054 -0.0028214 -0.0033844 -0.0076368 -0.0881973  0.6204865


问:
Error starting the reexec.Command - fork/exec /proc/self/exe: operation not permitted
I want to start two sub-container processes in the main function and it work when there is only one.

I don't know how to use golang to accomplish this method

Execute the following code， the first “/bin/sh” is ok. second occurs  "Error starting the reexec.Command - fork/exec /proc/self/exe: operation not permitted"

I really appreciate your help

```<code>func main() {

   container.StartFunction("/bin/sh")

   container.StartFunctionB("/bin/sh")

   time.Sleep(100 * time.Second)

  }

</code>```
```<code>package container

import (
   "fmt"
   "github.com/docker/docker/pkg/reexec"
   "io/ioutil"
   "os"
   "os/exec"
   "path/filepath"
   "strconv"
   "syscall"
)

func initFunction() {
   reexec.Register("nsInitialisation", nsInitialisation)
   if reexec.Init() {
      os.Exit(0)
   }
}

func nsInitialisation() {
   fmt.Printf("\n>> namespace setup code goes hereA <<\n\n")

   setMount("./container/ubuntu")

   if err := syscall.Sethostname([]byte("container")); err != nil {
      fmt.Printf("Error setting hostname - %s\n", err)
      os.Exit(1)
   }

   set_cgroups()

   nsRun()
}

func initFunctionB() {
   reexec.Register("nsInitialisationB", nsInitialisationB)
   if reexec.Init() {
      os.Exit(0)
   }
}

func nsInitialisationB() {
   fmt.Printf("\n>> namespace setup code goes hereB <<\n\n")

   setMount("./container/ubuntu")

   if err := syscall.Sethostname([]byte("container")); err != nil {
      fmt.Printf("Error setting hostname - %s\n", err)
      os.Exit(1)
   }

   set_cgroups()

   nsRunB()
}

func set_cgroups() {
   cgroups := "/sys/fs/cgroup/"
   pids := filepath.Join(cgroups, "pids")
   os.MkdirAll(filepath.Join(pids, "ourContainer"), 0755)
   ioutil.WriteFile(filepath.Join(pids, "ourContainer/pids.max"), []byte("10"), 0700)
   //up here we limit the number of child processes to 10

   ioutil.WriteFile(filepath.Join(pids, "ourContainer/notify_on_release"), []byte("1"), 0700)

   ioutil.WriteFile(filepath.Join(pids, "ourContainer/cgroup.procs"), []byte(strconv.Itoa(os.Getpid())), 0700)
   // up here we write container PIDs to cgroup.procs
}

func setMount(root string) error {
   if err := syscall.Chroot(root); err != nil {
      return err
   }

   if err := syscall.Chdir("/"); err != nil {
      return err
   }

   if err := syscall.Mount("proc", "proc", "proc", 0, ""); err != nil {
      return err
   }

   return nil
}

func nsRun() {
   cmd := exec.Command(os.Getenv("function"))

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.Env = []string{"PS1=-[container]- # "}

   if err := cmd.Run(); err != nil {
      fmt.Printf("Error running the %s command - %s\n", os.Getenv("function"), err)
      os.Exit(1)
   }

   syscall.Unmount("/proc", 0)
}

func nsRunB() {
   cmd := exec.Command(os.Getenv("functionB"))

   fmt.Println(os.Getenv("functionB"))

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.Env = []string{"PS1=-[container]- # "}

   if err := cmd.Run(); err != nil {
      fmt.Printf("Error running the %s command - %s\n", os.Getenv("function"), err)
      os.Exit(1)
   }

   syscall.Unmount("/proc", 0)
}

func StartFunction(functionPath string) {
   os.Setenv("function", functionPath)
   //os.Setenv("function", "/bin/bash")
   initFunction()
   cmd := reexec.Command(append([]string{"nsInitialisation"},
      os.Getenv("function"))...)
   run(cmd)
}

func StartFunctionB(functionPath string) {
   os.Setenv("functionB", functionPath)
   //os.Setenv("function", "/bin/bash")
   initFunctionB()
   cmd := reexec.Command(append([]string{"nsInitialisationB"},
      os.Getenv("functionB"))...)
   run(cmd)
}

func run(cmd *exec.Cmd) {

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.SysProcAttr = &syscall.SysProcAttr{
      Cloneflags: syscall.CLONE_NEWNS |
         syscall.CLONE_NEWUTS |
         syscall.CLONE_NEWIPC |
         syscall.CLONE_NEWPID |
         //syscall.CLONE_NEWNET |
         syscall.CLONE_NEWUSER,
      Unshareflags: syscall.CLONE_NEWNS,
      UidMappings: []syscall.SysProcIDMap{
         {
            ContainerID: 0,
            HostID:      os.Getuid(),
            Size:        1,
         },
      },
      GidMappings: []syscall.SysProcIDMap{
         {
            ContainerID: 0,
            HostID:      os.Getgid(),
            Size:        1,
         },
      },
   }

   if err := cmd.Start(); err != nil {
      fmt.Printf("Error starting the reexec.Command - %s\n", err)
      os.Exit(1)
   }

   //if err := cmd.Wait(); err != nil {
   // fmt.Printf("Error running the reexec.Command - %s\n", err)
   // os.Exit(1)
   //}

}

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

container.StartFunction("/bin/sh")  one by one is ok, time.Sleep(100 * time.Second) can run.

I feel that it should not be in the first sub-container processes.

my ecpecting:

I want to start two sub-container processes in the main function, and the sub-container processes can execute other logic.

Body:
I want to start two sub-container processes in the main function and it work when there is only one.

I don't know how to use golang to accomplish this method

Execute the following code， the first “/bin/sh” is ok. second occurs  "Error starting the reexec.Command - fork/exec /proc/self/exe: operation not permitted"

I really appreciate your help

func main() {

   container.StartFunction("/bin/sh")

   container.StartFunctionB("/bin/sh")

   time.Sleep(100 * time.Second)

  }

package container

import (
   "fmt"
   "github.com/docker/docker/pkg/reexec"
   "io/ioutil"
   "os"
   "os/exec"
   "path/filepath"
   "strconv"
   "syscall"
)

func initFunction() {
   reexec.Register("nsInitialisation", nsInitialisation)
   if reexec.Init() {
      os.Exit(0)
   }
}

func nsInitialisation() {
   fmt.Printf("\n>> namespace setup code goes hereA <<\n\n")

   setMount("./container/ubuntu")

   if err := syscall.Sethostname([]byte("container")); err != nil {
      fmt.Printf("Error setting hostname - %s\n", err)
      os.Exit(1)
   }

   set_cgroups()

   nsRun()
}

func initFunctionB() {
   reexec.Register("nsInitialisationB", nsInitialisationB)
   if reexec.Init() {
      os.Exit(0)
   }
}

func nsInitialisationB() {
   fmt.Printf("\n>> namespace setup code goes hereB <<\n\n")

   setMount("./container/ubuntu")

   if err := syscall.Sethostname([]byte("container")); err != nil {
      fmt.Printf("Error setting hostname - %s\n", err)
      os.Exit(1)
   }

   set_cgroups()

   nsRunB()
}

func set_cgroups() {
   cgroups := "/sys/fs/cgroup/"
   pids := filepath.Join(cgroups, "pids")
   os.MkdirAll(filepath.Join(pids, "ourContainer"), 0755)
   ioutil.WriteFile(filepath.Join(pids, "ourContainer/pids.max"), []byte("10"), 0700)
   //up here we limit the number of child processes to 10

   ioutil.WriteFile(filepath.Join(pids, "ourContainer/notify_on_release"), []byte("1"), 0700)

   ioutil.WriteFile(filepath.Join(pids, "ourContainer/cgroup.procs"), []byte(strconv.Itoa(os.Getpid())), 0700)
   // up here we write container PIDs to cgroup.procs
}

func setMount(root string) error {
   if err := syscall.Chroot(root); err != nil {
      return err
   }

   if err := syscall.Chdir("/"); err != nil {
      return err
   }

   if err := syscall.Mount("proc", "proc", "proc", 0, ""); err != nil {
      return err
   }

   return nil
}

func nsRun() {
   cmd := exec.Command(os.Getenv("function"))

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.Env = []string{"PS1=-[container]- # "}

   if err := cmd.Run(); err != nil {
      fmt.Printf("Error running the %s command - %s\n", os.Getenv("function"), err)
      os.Exit(1)
   }

   syscall.Unmount("/proc", 0)
}

func nsRunB() {
   cmd := exec.Command(os.Getenv("functionB"))

   fmt.Println(os.Getenv("functionB"))

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.Env = []string{"PS1=-[container]- # "}

   if err := cmd.Run(); err != nil {
      fmt.Printf("Error running the %s command - %s\n", os.Getenv("function"), err)
      os.Exit(1)
   }

   syscall.Unmount("/proc", 0)
}

func StartFunction(functionPath string) {
   os.Setenv("function", functionPath)
   //os.Setenv("function", "/bin/bash")
   initFunction()
   cmd := reexec.Command(append([]string{"nsInitialisation"},
      os.Getenv("function"))...)
   run(cmd)
}

func StartFunctionB(functionPath string) {
   os.Setenv("functionB", functionPath)
   //os.Setenv("function", "/bin/bash")
   initFunctionB()
   cmd := reexec.Command(append([]string{"nsInitialisationB"},
      os.Getenv("functionB"))...)
   run(cmd)
}

func run(cmd *exec.Cmd) {

   cmd.Stdin = os.Stdin
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr

   cmd.SysProcAttr = &syscall.SysProcAttr{
      Cloneflags: syscall.CLONE_NEWNS |
         syscall.CLONE_NEWUTS |
         syscall.CLONE_NEWIPC |
         syscall.CLONE_NEWPID |
         //syscall.CLONE_NEWNET |
         syscall.CLONE_NEWUSER,
      Unshareflags: syscall.CLONE_NEWNS,
      UidMappings: []syscall.SysProcIDMap{
         {
            ContainerID: 0,
            HostID:      os.Getuid(),
            Size:        1,
         },
      },
      GidMappings: []syscall.SysProcIDMap{
         {
            ContainerID: 0,
            HostID:      os.Getgid(),
            Size:        1,
         },
      },
   }

   if err := cmd.Start(); err != nil {
      fmt.Printf("Error starting the reexec.Command - %s\n", err)
      os.Exit(1)
   }

   //if err := cmd.Wait(); err != nil {
   // fmt.Printf("Error running the reexec.Command - %s\n", err)
   // os.Exit(1)
   //}

}

container.StartFunction("/bin/sh")  one by one is ok, time.Sleep(100 * time.Second) can run.

I feel that it should not be in the first sub-container processes.

my ecpecting:

I want to start two sub-container processes in the main function, and the sub-container processes can execute other logic.


问:
Get and insert bit in MySQL by input:radio
I need to insert a bit value in my MySQL, but I don't understand how.
I use Django so I get the input value by

```<code>employing = request.POST.get('employing')
</code>```

and I send by

```<code>QuerySet(employing=employing)
</code>```
```<code> <input
              class="form-check-input"
              type="radio"
              name="employing"
              id="employingTrue"
              value="01"
              checked
              required
            />
</code>```

I've tried value="1", value="b'1'", value="true", but I always got :

```<code>(1406, "Data too long for column 'employing' at row 1")
</code>```

Body:
I need to insert a bit value in my MySQL, but I don't understand how.
I use Django so I get the input value by

employing = request.POST.get('employing')

and I send by

QuerySet(employing=employing)

 <input
              class="form-check-input"
              type="radio"
              name="employing"
              id="employingTrue"
              value="01"
              checked
              required
            />

I've tried value="1", value="b'1'", value="true", but I always got :

(1406, "Data too long for column 'employing' at row 1")


问:
How to merge or convert JSONArray to JSONObject Java/ Spring Boot?
I am trying to achieve of converting or merging JSONArray and JSONObject together.
This is my original JSON response that I get from using RestTemplate.

```<code>   {
     "links": {
                "RCDSO - Production Environment Cost": {
                    "href": "href 1"
                },
                "RCDSO - Development & UAT Environment Cost": {
                    "href": "href 2"
                },
                "RCDSO - Total Cost for Prod - Compugen Managed": {
                    "href": "href 3"
                },
                "RCDSO - Virtual Machine Cost": {
                    "href": "href 4"
                },
                "RCDSO - Azure File Storage Cost": {
                    "href": "href 5"
                },
                "RCDSO - Azure Backup and Site Recovery": {
                    "href": "href 6"
                },
                "RCDSO - Azure App Services Cost": {
                    "href": "href 7"
                }
          }
    }
</code>```

I wan above JSON data to look like below :

```<code>{
  "links": [
    {
      "RCDSO - Development & UAT Environment Cost": {
        "href": "href 1"
      },
      "RCDSO - Virtual Machine Cost": {
        "href": "href 2"
      },
      "RCDSO - Azure File Storage Cost": {
        "href": "href 3"
      },
      "RCDSO - Azure Backup and Site Recovery": {
        "href": "href 4"
      },
      "RCDSO - Total Cost for Prod - Compugen Managed": {
        "href": "href 5"
      },
      "RCDSO - Azure App Services Cost": {
        "href": "href 6"
      },
      "RCDSO - Production Environment Cost": {
        "href": "href 7"
      }
    }
  ]
}
</code>```

Is there any way to convert or merge JSONArray and JSONObject together in Java?

I tried to have it this way but getting JSONException:

```<code>public CustomOlapReports getReportListByClientId(String clientId) {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        CustomOlapReports reportList = null;
        try {
            List<String> list = new ArrayList<String>();
            OlapCustomReportResponse reportResponse = null;
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports/custom?client_api_id="+clientId;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");

            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            jsonResponse =  responseEntity.getBody();

            JSONObject jsonObj = new JSONObject(jsonResponse);

            JSONObject obj = jsonObj.getJSONObject("links");

            JSONArray jsonArr = new JSONArray();
            jsonArr.put(obj);

            System.out.println("Response : "+jsonArr);

            JSONObject ob = jsonArr.toJSONObject(jsonArr);
            System.out.println("OBJECT : "+ob);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportList;
    }
</code>```

I am getting below error:

```<code>org.json.JSONException: JSONArray[0] is not a String (class org.json.JSONObject).
    at org.json.JSONArray.wrongValueFormatException(JSONArray.java:1689)
    at org.json.JSONArray.getString(JSONArray.java:500)
    at com.example.apidemo.service.CspPartnerCustomerService.getReportListByClientId(CspPartnerCustomerService.java:137)
    at com.example.apidemo.controller.CustomerRestController.getReportListByClientId(CustomerRestController.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)........and so on.
</code>```

Body:
I am trying to achieve of converting or merging JSONArray and JSONObject together.
This is my original JSON response that I get from using RestTemplate.

   {
     "links": {
                "RCDSO - Production Environment Cost": {
                    "href": "href 1"
                },
                "RCDSO - Development & UAT Environment Cost": {
                    "href": "href 2"
                },
                "RCDSO - Total Cost for Prod - Compugen Managed": {
                    "href": "href 3"
                },
                "RCDSO - Virtual Machine Cost": {
                    "href": "href 4"
                },
                "RCDSO - Azure File Storage Cost": {
                    "href": "href 5"
                },
                "RCDSO - Azure Backup and Site Recovery": {
                    "href": "href 6"
                },
                "RCDSO - Azure App Services Cost": {
                    "href": "href 7"
                }
          }
    }

I wan above JSON data to look like below :

{
  "links": [
    {
      "RCDSO - Development & UAT Environment Cost": {
        "href": "href 1"
      },
      "RCDSO - Virtual Machine Cost": {
        "href": "href 2"
      },
      "RCDSO - Azure File Storage Cost": {
        "href": "href 3"
      },
      "RCDSO - Azure Backup and Site Recovery": {
        "href": "href 4"
      },
      "RCDSO - Total Cost for Prod - Compugen Managed": {
        "href": "href 5"
      },
      "RCDSO - Azure App Services Cost": {
        "href": "href 6"
      },
      "RCDSO - Production Environment Cost": {
        "href": "href 7"
      }
    }
  ]
}

Is there any way to convert or merge JSONArray and JSONObject together in Java?

I tried to have it this way but getting JSONException:

public CustomOlapReports getReportListByClientId(String clientId) {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        CustomOlapReports reportList = null;
        try {
            List<String> list = new ArrayList<String>();
            OlapCustomReportResponse reportResponse = null;
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports/custom?client_api_id="+clientId;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");

            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            jsonResponse =  responseEntity.getBody();

            JSONObject jsonObj = new JSONObject(jsonResponse);

            JSONObject obj = jsonObj.getJSONObject("links");

            JSONArray jsonArr = new JSONArray();
            jsonArr.put(obj);

            System.out.println("Response : "+jsonArr);

            JSONObject ob = jsonArr.toJSONObject(jsonArr);
            System.out.println("OBJECT : "+ob);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportList;
    }

I am getting below error:

org.json.JSONException: JSONArray[0] is not a String (class org.json.JSONObject).
    at org.json.JSONArray.wrongValueFormatException(JSONArray.java:1689)
    at org.json.JSONArray.getString(JSONArray.java:500)
    at com.example.apidemo.service.CspPartnerCustomerService.getReportListByClientId(CspPartnerCustomerService.java:137)
    at com.example.apidemo.controller.CustomerRestController.getReportListByClientId(CustomerRestController.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)........and so on.


问:
Extend gradle plugin usage for library users
Using gradle, if we have an android library that declares a dependency as:

```<code>api("some dependency")
</code>```

apps that use this library also have access to that dependency.

Is it possible to declare plugins the same way?
E.g.
In the library:

```<code>plugins {
    id("my plugin")
}
</code>```

And then have my plugin also applied to the app using that library?

Body:
Using gradle, if we have an android library that declares a dependency as:

api("some dependency")

apps that use this library also have access to that dependency.

Is it possible to declare plugins the same way?
E.g.
In the library:

plugins {
    id("my plugin")
}

And then have my plugin also applied to the app using that library?


问:
contenteditable pre scrollbars not showing correct cursor
I have a contenteditable, and in it I can have pre tags, which I have stylized to show a thinner scrollbar. But now the scrollbar cursor (seen when hovering over the scrollbar) remains as a text style instead of pointer. I have tried adding the obvious cursor:pointer to the -webkit settings but nothing seems to work.
How do I make the pre scrollbar use a pointer cursor instead of text?

    pre {
      padding: 10px;
      width: calc(100% - 70px);
      overflow-x: scroll;
    }

    pre::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }

    pre::-webkit-scrollbar-thumb {
      background: #9c9c9c;
      -webkit-border-radius: 18px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div contenteditable>

    ```Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc eget lorem dolor sed viverra ipsum. Quis varius quam quisque id diam vel quam elementum pulvinar. Turpis egestas sed tempus urna et pharetra pharetra massa. Sed risus pretium quam vulputate```

    </div></code>```

Use https://jsfiddle.net/Lhmsf38k/ to have a fiddle.

Body:
I have a contenteditable, and in it I can have pre tags, which I have stylized to show a thinner scrollbar. But now the scrollbar cursor (seen when hovering over the scrollbar) remains as a text style instead of pointer. I have tried adding the obvious cursor:pointer to the -webkit settings but nothing seems to work.
How do I make the pre scrollbar use a pointer cursor instead of text?

    pre {
      padding: 10px;
      width: calc(100% - 70px);
      overflow-x: scroll;
    }

    pre::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }

    pre::-webkit-scrollbar-thumb {
      background: #9c9c9c;
      -webkit-border-radius: 18px;
    }

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc eget lorem dolor sed viverra ipsum. Quis varius quam quisque id diam vel quam elementum pulvinar. Turpis egestas sed tempus urna et pharetra pharetra massa. Sed risus pretium quam vulputate

Use https://jsfiddle.net/Lhmsf38k/ to have a fiddle.


问:
ASP.NET CORE: Turn multi-area single project into multi-project solution?
We have a single ASP.NET Core MVC project, constituted by different features.
Each feature is an MVC Area.
For example, we have an area for "Personal data", an area for "Communications", an area for "Projects Management" ecc...
Each area contains its models, views, services and controllers.
We would like to split this single project solution into a multi project one, in which each project is a .NET Core MVC project for a specific area.

How could we do this?


问:
flyback power board is failed and not working, how to repaire?
I have a power board is5/ip5a that is failed. I test it and see that the output voltage when there is no load is ok but when the board is connected to the load, output voltage reach to zero and can't work. what should check to repaire it?

Switching mosfet and isolated feedback is tested and is ok.


问:
Unity cannot export to android when folder is not empty
Recently I upgrade my unity to 2021.3.15. When first time I export the project to a folder, it works. But when I am trying to export again to the same folder (it's already have the content exported before), it shows me the error like below. With Unity 2019, it works perfectly without this issue. I know I can clean the folder everytime export but for some reason I cannot.(I have a lot of plugin code in the project I dont want to rebuild them every time export.)

it gives the error:

```<code>Gradle project template version mismatch, expected 3 was 0, this means Unity's gradle template files were changed.
Please export to an empty folder and review the changes in gradle project files.
</code>```

here is the error stack trace:

```<code>UnityEditor.Android.PostProcessor.Tasks.CheckGradleProjectCollisions.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PrepareForBuildProgram (UnityEditor.Modules.BuildPostProcessArgs args) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.Int32 subtarget, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:370)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:189)
</code>```

Can anyone help?

Body:
Recently I upgrade my unity to 2021.3.15. When first time I export the project to a folder, it works. But when I am trying to export again to the same folder (it's already have the content exported before), it shows me the error like below. With Unity 2019, it works perfectly without this issue. I know I can clean the folder everytime export but for some reason I cannot.(I have a lot of plugin code in the project I dont want to rebuild them every time export.)

it gives the error:

Gradle project template version mismatch, expected 3 was 0, this means Unity's gradle template files were changed.
Please export to an empty folder and review the changes in gradle project files.

here is the error stack trace:

UnityEditor.Android.PostProcessor.Tasks.CheckGradleProjectCollisions.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PrepareForBuildProgram (UnityEditor.Modules.BuildPostProcessArgs args) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <571d7b726d0947b3bdeba29b35054968>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.Int32 subtarget, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:370)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&) (at /Users/bokken/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:189)

Can anyone help?


问:
msvs_version not set from command line or npm config
I am trying to run this command to fix problem in ionic project

npx cap sync android

but I am getting the following error

```<code>gyp ERR! find VS
gyp ERR! find VS msvs_version not set from command line or npm config
gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
gyp ERR! find VS checking VS2019 (16.11.31727.386) found at:
gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community"
gyp ERR! find VS - "Visual Studio C++ core features" missing
gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use
gyp ERR! find VS looking for Visual Studio 2015
gyp ERR! find VS - not found
gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
gyp ERR! find VS
gyp ERR! find VS **************************************************************
gyp ERR! find VS You need to install the latest version of Visual Studio
gyp ERR! find VS including the "Desktop development with C++" workload.
gyp ERR! find VS For more information consult the documentation at:
gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
gyp ERR! find VS **************************************************************
gyp ERR! find VS
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Visual Studio installation to use
gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:315:5)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! System Windows_NT 10.0.14393
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\smacrsadmin\AppData\Roaming\npm-cache\_npx\315112\node_modules\cap
gyp ERR! node -v v14.15.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cap@0.2.1 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cap@0.2.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

can anyone advice what should I do please ?

Body:
I am trying to run this command to fix problem in ionic project

npx cap sync android

but I am getting the following error

gyp ERR! find VS
gyp ERR! find VS msvs_version not set from command line or npm config
gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
gyp ERR! find VS checking VS2019 (16.11.31727.386) found at:
gyp ERR! find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community"
gyp ERR! find VS - "Visual Studio C++ core features" missing
gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use
gyp ERR! find VS looking for Visual Studio 2015
gyp ERR! find VS - not found
gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
gyp ERR! find VS
gyp ERR! find VS **************************************************************
gyp ERR! find VS You need to install the latest version of Visual Studio
gyp ERR! find VS including the "Desktop development with C++" workload.
gyp ERR! find VS For more information consult the documentation at:
gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
gyp ERR! find VS **************************************************************
gyp ERR! find VS
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Visual Studio installation to use
gyp ERR! stack     at VisualStudioFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:315:5)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! System Windows_NT 10.0.14393
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\smacrsadmin\AppData\Roaming\npm-cache\_npx\315112\node_modules\cap
gyp ERR! node -v v14.15.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cap@0.2.1 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cap@0.2.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

can anyone advice what should I do please ?


问:
Restrict users to allow build when parameter value in null
In Jenkins, I had already put up a job with string parameter(mandatory values). However, users were forget to provide mandatory parameter values when building. I need to put restrictions on users so they shouldn't build with empty mandatory parameter values. Can someone please advise in a better way.