问:
Ktor Webserver - OutOfDirectMemoryError on large file upload in Netty
I am working on an embedded device. This means that I do not have much system memory (1GB RAM). Now I try to receive a big file (400MB) with KTor (2.1.3) and Netty, which should be stored directly in file system because flash memory is big enough.

I tried:

```<code>call.receiveStream().use { inp ->
  FileOutputStream(targetPath).use { out ->
  bytesWritten = inp.copyTo(out)
  LOGGER.info("Written $bytesWritten bytes")
  }
}
</code>```

"call" is an ApplicationCall. Sometimes it happens, that netty is not able to allocate new direct memory:

```<code>kotlinx.coroutines.JobCancellationException: Parent job is Cancelled
    Suppressed: java.io.IOException: kotlinx.coroutines.JobCancellationException: Parent job is Cancelled; job=CompletableDeferredImpl{Cancelled}@1e8d247
        at io.ktor.utils.io.jvm.javaio.OutputAdapter.close(Blocking.kt:134)
        at kotlin.io.CloseableKt.closeFinally(Closeable.kt:59)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invokeSuspend(OutputStreamContent.kt:27)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invoke(OutputStreamContent.kt)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invoke(OutputStreamContent.kt)
        at io.ktor.http.content.BlockingBridgeKt.withBlocking(BlockingBridge.kt:28)
        at io.ktor.http.content.OutputStreamContent.writeTo(OutputStreamContent.kt:24)
        at io.ktor.server.engine.BaseApplicationResponse$respondWriteChannelContent$2$1.invokeSuspend(BaseApplicationResponseJvm.kt:173)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
        at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Caused by: kotlinx.coroutines.JobCancellationException: Parent job is Cancelled
Caused by: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 4194304 byte(s) of direct memory (used: 197132295, max: 200671232)
    at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:806)
    at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:735)
    at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:649)
    at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:624)
    at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:203)
    at io.netty.buffer.PoolArena.tcacheAllocateNormal(PoolArena.java:187)
    at io.netty.buffer.PoolArena.allocate(PoolArena.java:136)
    at io.netty.buffer.PoolArena.allocate(PoolArena.java:126)
    at io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:396)
    at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:188)
    at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:179)
    at io.netty.buffer.AbstractByteBufAllocator.ioBuffer(AbstractByteBufAllocator.java:140)
    at io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator$MaxMessageHandle.allocate(DefaultMaxMessagesRecvByteBufAllocator.java:120)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:150)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.ktor.server.netty.EventLoopGroupProxy$Companion.create$lambda-1$lambda-0(NettyApplicationEngine.kt:288)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)

</code>```

Increasing the direct memory has the effect that the problem occours less often.

Also in "top" on console I can see that free memory is decreasing and decreasing in this error case until my application is stopped.

I am not sure what the cause of this is. Is it because the "copyTo" is not working fast enough? Which means that writing to flash memory is slowing down - shouldn't there be a flow control back to the client who is uploading the large file?

Is there any other parameter I can play around with?

Thank you very much for any advice!
Thomas

Body:
I am working on an embedded device. This means that I do not have much system memory (1GB RAM). Now I try to receive a big file (400MB) with KTor (2.1.3) and Netty, which should be stored directly in file system because flash memory is big enough.

I tried:

call.receiveStream().use { inp ->
  FileOutputStream(targetPath).use { out ->
  bytesWritten = inp.copyTo(out)
  LOGGER.info("Written $bytesWritten bytes")
  }
}

"call" is an ApplicationCall. Sometimes it happens, that netty is not able to allocate new direct memory:

kotlinx.coroutines.JobCancellationException: Parent job is Cancelled
    Suppressed: java.io.IOException: kotlinx.coroutines.JobCancellationException: Parent job is Cancelled; job=CompletableDeferredImpl{Cancelled}@1e8d247
        at io.ktor.utils.io.jvm.javaio.OutputAdapter.close(Blocking.kt:134)
        at kotlin.io.CloseableKt.closeFinally(Closeable.kt:59)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invokeSuspend(OutputStreamContent.kt:27)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invoke(OutputStreamContent.kt)
        at io.ktor.http.content.OutputStreamContent$writeTo$2.invoke(OutputStreamContent.kt)
        at io.ktor.http.content.BlockingBridgeKt.withBlocking(BlockingBridge.kt:28)
        at io.ktor.http.content.OutputStreamContent.writeTo(OutputStreamContent.kt:24)
        at io.ktor.server.engine.BaseApplicationResponse$respondWriteChannelContent$2$1.invokeSuspend(BaseApplicationResponseJvm.kt:173)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
        at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Caused by: kotlinx.coroutines.JobCancellationException: Parent job is Cancelled
Caused by: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 4194304 byte(s) of direct memory (used: 197132295, max: 200671232)
    at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:806)
    at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:735)
    at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:649)
    at io.netty.buffer.PoolArena$DirectArena.newChunk(PoolArena.java:624)
    at io.netty.buffer.PoolArena.allocateNormal(PoolArena.java:203)
    at io.netty.buffer.PoolArena.tcacheAllocateNormal(PoolArena.java:187)
    at io.netty.buffer.PoolArena.allocate(PoolArena.java:136)
    at io.netty.buffer.PoolArena.allocate(PoolArena.java:126)
    at io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:396)
    at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:188)
    at io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:179)
    at io.netty.buffer.AbstractByteBufAllocator.ioBuffer(AbstractByteBufAllocator.java:140)
    at io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator$MaxMessageHandle.allocate(DefaultMaxMessagesRecvByteBufAllocator.java:120)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:150)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.ktor.server.netty.EventLoopGroupProxy$Companion.create$lambda-1$lambda-0(NettyApplicationEngine.kt:288)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)

Increasing the direct memory has the effect that the problem occours less often.

Also in "top" on console I can see that free memory is decreasing and decreasing in this error case until my application is stopped.

I am not sure what the cause of this is. Is it because the "copyTo" is not working fast enough? Which means that writing to flash memory is slowing down - shouldn't there be a flow control back to the client who is uploading the large file?

Is there any other parameter I can play around with?

Thank you very much for any advice!
Thomas


来源: stackexchange

问:
Multiple x sessions in background using docker
I want to run multiple copies of a game each in a separate docker container. I would then in each docker container control the mouse programatically. I.e. create a program to play the game.

Is this possible? If so, does anyone have any idea about how I would do it?

Thanks,

Shaun.

ContentLicense: CC BY-SA 4.0


问:
How to use MongoDB in Laravel Testing
I have laravel project, which I'm using two database: relational PostgresSQL and MongoDB.

I have to write feature tests to database but. I don't know how to create connection with mongo from laravel testing.

My phpunit.xml fragment file

```<code><php>
        <env name="MONGO_DB_CONNECTION" value="mongodb"/>
        <env name="MONGO_DB_DSN" value="mongodb://localhost:27017"/>
        <env name="MONGO_DB_DATABASE" value="test"/>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>
    </php>
</code>```

config/database.php

```<code>'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGO_DB_DSN'),
        'database' => env('MONGO_DB_DATABASE', 'homestead'),
    ],
</code>```

When I run test I got message:

MongoDB\Driver\Exception\ConnectionTimeoutException : No suitable
servers found (serverSelectionTryOnce set): [connection refused
calling hello on 'localhost:27017']

Can I use MongoDB on memory like env name 'DB_DATABASE' variable

Title: How to use MongoDB in Laravel Testing

Body:
I have laravel project, which I'm using two database: relational PostgresSQL and MongoDB.

I have to write feature tests to database but. I don't know how to create connection with mongo from laravel testing.

My phpunit.xml fragment file

<php>
        <env name="MONGO_DB_CONNECTION" value="mongodb"/>
        <env name="MONGO_DB_DSN" value="mongodb://localhost:27017"/>
        <env name="MONGO_DB_DATABASE" value="test"/>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>
    </php>

config/database.php

'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGO_DB_DSN'),
        'database' => env('MONGO_DB_DATABASE', 'homestead'),
    ],

When I run test I got message:

MongoDB\Driver\Exception\ConnectionTimeoutException : No suitable
servers found (serverSelectionTryOnce set): [connection refused
calling hello on 'localhost:27017']

Can I use MongoDB on memory like env name 'DB_DATABASE' variable


问:
Why are my CSS classes not updating in Blazor WASM?
I'm trying to change the class of a  element based on a bool. I'm saving the value of the bool in the localstorage and the Console.WriteLine shows me that SidenavClass gets the correct value (class name). However, it does not update in the HTML. The classname doesn't get added to the  element.

I also tried using StateHasChanged(), his doesn't seem to work.

It's a component in a component, in a component.

ProductCategoriesNavMenu.razor inside NavMenu.razor inside MainLayout.razor

Can someone help me figure out why it's not updating the classname in the HTML?

ProductCategoriesNavMenu.razor

```<code>@foreach (var productCategory in ProductCategoryDtos)
    {
        var link = "ProductsByCategory/" + productCategory.Id;

        <div class="nav-item px-3">
            <NavLink class="nav-link" href="@link">
                <span class="@productCategory.IconCSS"></span><span class="@SidenavClass">@productCategory.Name</span>
            </NavLink>
        </div>
    }

<div class="@SidenavClass">TEST</div>

@code {
    public bool collapsedMenu { get; set; }
    public string SidenavClass => collapsedMenu ? "collapsed-sidenav" : "";

    public async Task CollapseMenuToggler()
    {
        await Task.Delay(500);
        collapsedMenu = await LocalStorage.GetItemAsync<bool>("Menu Collapsed");
        Console.WriteLine("collapsedMenu: " + collapsedMenu + ", Class: " + SidenavClass);
        StateHasChanged();
    }
}
</code>```

NavMenu.razor

```<code><ProductCategoriesNavMenu/>

@code {
    public static string Class = "collapsed-sidenav";

    [Parameter] public EventCallback<bool> CollapseSidebarEvent { get; set; }

    public void CollapseMenu(MouseEventArgs e)
    {
        collapsedSidenav = !collapsedSidenav;
        LocalStorage.SetItemAsync<bool>("Menu Collapsed", collapsedSidenav);
        if(collapsedSidenav)
        {
            LocalStorage.SetItemAsync<string>("Collapse Class", Class);
        }
        else
        {
            LocalStorage.SetItemAsync<string>("Collapse Class", "");
        }
        CollapseMenuToggler();
        CollapseSidebarEvent.InvokeAsync(collapsedSidenav);
    }
}

</code>```

MainLayout.razor

```<code><NavMenu CollapseSidebarEvent="(e)=>SidenavCollapsedHandler(e)" />
</code>```

Body:
I'm trying to change the class of a  element based on a bool. I'm saving the value of the bool in the localstorage and the Console.WriteLine shows me that SidenavClass gets the correct value (class name). However, it does not update in the HTML. The classname doesn't get added to the  element.

I also tried using StateHasChanged(), his doesn't seem to work.

It's a component in a component, in a component.

ProductCategoriesNavMenu.razor inside NavMenu.razor inside MainLayout.razor

Can someone help me figure out why it's not updating the classname in the HTML?

ProductCategoriesNavMenu.razor

@foreach (var productCategory in ProductCategoryDtos)
    {
        var link = "ProductsByCategory/" + productCategory.Id;

            <NavLink class="nav-link" href="@link">
                @productCategory.Name
            </NavLink>

    }

TEST

@code {
    public bool collapsedMenu { get; set; }
    public string SidenavClass => collapsedMenu ? "collapsed-sidenav" : "";

    public async Task CollapseMenuToggler()
    {
        await Task.Delay(500);
        collapsedMenu = await LocalStorage.GetItemAsync<bool>("Menu Collapsed");
        Console.WriteLine("collapsedMenu: " + collapsedMenu + ", Class: " + SidenavClass);
        StateHasChanged();
    }
}

NavMenu.razor

<ProductCategoriesNavMenu/>

@code {
    public static string Class = "collapsed-sidenav";

    [Parameter] public EventCallback<bool> CollapseSidebarEvent { get; set; }

    public void CollapseMenu(MouseEventArgs e)
    {
        collapsedSidenav = !collapsedSidenav;
        LocalStorage.SetItemAsync<bool>("Menu Collapsed", collapsedSidenav);
        if(collapsedSidenav)
        {
            LocalStorage.SetItemAsync<string>("Collapse Class", Class);
        }
        else
        {
            LocalStorage.SetItemAsync<string>("Collapse Class", "");
        }
        CollapseMenuToggler();
        CollapseSidebarEvent.InvokeAsync(collapsedSidenav);
    }
}

MainLayout.razor

<NavMenu CollapseSidebarEvent="(e)=>SidenavCollapsedHandler(e)" />


问:
Displaying Apple Smart Banner on certain pages only in Next.JS
We're trying to display the Apple Smart Banner on some pages (let's call them page A for simplicity) but not on all of them (as of now we only support Universal Linking on some pages only). So we added this code snippet to these pages:

```<code>{isBannerPromotionActive && config.APPLE_APPSTORE_ID && (
     <meta
       name="apple-itunes-app"
       content={`app-id=${config.APPLE_APPSTORE_ID}, app-argument=${deepLink}`}
       key="smart-banner"
     />
)}
</code>```

However, we're seeing the following behavior in iOS on Safari:

If the user goes straight to page A (e.g. from google goes to mysite.com/page_a) then the banner appears as expected. Although the banner remains visible all the time if the user navigates to any other page, even though that page doesn't have the banner meta tag in its source.

If the user goes to the homepage (e.g. goes to mysite.com) and then navigates to page A then the banner is not visible.

Any idea why is this happening and how can we sort this out?

Body:
We're trying to display the Apple Smart Banner on some pages (let's call them page A for simplicity) but not on all of them (as of now we only support Universal Linking on some pages only). So we added this code snippet to these pages:

{isBannerPromotionActive && config.APPLE_APPSTORE_ID && (
     <meta
       name="apple-itunes-app"
       content={`app-id=${config.APPLE_APPSTORE_ID}, app-argument=${deepLink}`}
       key="smart-banner"
     />
)}

However, we're seeing the following behavior in iOS on Safari:

If the user goes straight to page A (e.g. from google goes to mysite.com/page_a) then the banner appears as expected. Although the banner remains visible all the time if the user navigates to any other page, even though that page doesn't have the banner meta tag in its source.

If the user goes to the homepage (e.g. goes to mysite.com) and then navigates to page A then the banner is not visible.

Any idea why is this happening and how can we sort this out?


问:
SQL Server Agent Cannot Run Job With Croatian Characters
I'm trying to run SSIS package with SQL Server Agent Job, but get a fail message. After analyzing I found that the job fails when trying to run Execute Process Task (EPT), which creates a network file path via cmd.exe.

The argument in Execute Process Task is (username and password are redacted for safety):
/c "NET USE W: "\fs.i.local\kom\Komb\Službenici\korisničke maštarije" /user:--REDACTED-- -REDACTED--"

I'm trying to find a way to allow characters Ž,Č,Š to be inside the EPT argument, because renaming the folder that contains those characters would affect multiple systems and users, so that is my last resort.

I tried to change LocaleId of the task to Croatian


问:
AWS DMS migration Task incorrectly showing total rows in source
Im looking at migrating a on-prem mysql database to aurora via DMS. When i run DMS it brings up warnings about several LOB columns in tables. But i thought it would still import all rows if i set it to Full LOB. The task has completed successfully and shows all tables have all rows copied.

But reviewing the tables rows directly on the source cluster directly i can see there are 1000s of rows in multiple tables that DMS is not seeing. Can someone explain whats happening and how to solve it?


问:
How to extract text with custom cid in pdf
Right now, I want to extract table data from some pdf files. Part of text can be extracted correctly and others could not. It presents like "cid:xxxx".

I program in Python and I decide to use pdfplumber to solve it. I used page.extract_table to extract content. Of course,  the above problem occurred. According to the relationship of font, cid and glyph, OCR is a good way to get the normal encode of this special text. But I do not want OCR whole pdf because half of data could be extracted correctly. So i'd like to use OCR while facing the special text "cid:xxxx".

The problem which I faced is: Although i get the font and cid of a char, how could i get the glyph of this char? I need to convert it to image and then use OCR. I didn't find any relative solution or function in pdfminer. I appreciate your reply in advance.


问:
Hive external location access issue to Azure ADLS with Trino
I have a Trino instance running on a cluster with the need for Trino to connect to ADLS on Azure. For this I have a Hive metastore spinned up in the same cluster.
When I try to connect to the external ALDS container with the following query, I get the below error:

```<code>USE hive.default;
CREATE SCHEMA hive.web
WITH (location = 'abfs://<container_name>@<storage_account_name>.dfs.core.windows.net/')
</code>```
```<code>SQL Error [33]: Query failed (#20221207_104043_00017_jhcwz): Invalid location URI: abfs://<container_name>@<storage_account_name>.dfs.core.windows.net/
</code>```

The hive metastore is configured with the following data in the core-site.xml:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

  <property>
    <name>fs.azure.account.key.<storage_account_name>.dfs.core.windows.net</name>
    <value><access_key></value>
  </property>

  <property>
    <name>fs.trash.interval</name>
    <value>4320</value>
  </property>

</configuration>

</code>```

Body:
I have a Trino instance running on a cluster with the need for Trino to connect to ADLS on Azure. For this I have a Hive metastore spinned up in the same cluster.
When I try to connect to the external ALDS container with the following query, I get the below error:

USE hive.default;
CREATE SCHEMA hive.web
WITH (location = 'abfs://<container_name>@<storage_account_name>.dfs.core.windows.net/')

SQL Error [33]: Query failed (#20221207_104043_00017_jhcwz): Invalid location URI: abfs://<container_name>@<storage_account_name>.dfs.core.windows.net/

The hive metastore is configured with the following data in the core-site.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

  <property>
    <name>fs.azure.account.key.<storage_account_name>.dfs.core.windows.net</name>
    <value><access_key></value>
  </property>

  <property>
    <name>fs.trash.interval</name>
    <value>4320</value>
  </property>

</configuration>


问:
In TypeScript, Is it possible to read the properties defined in a class?
For a defined class:

```<code>class TestClass {
            public testProp: string
            public testProp2: number
            public testProp3: boolean
            public testProp4: Date
            public testProp5: any
        }
</code>```

Is it possible to enumerate all the defined properties in a way?

The idea is that I want to write a generic method to accept different types and iterate their properties:

```<code>function someMethod<T>() {
  // How to get the members of T?
}
</code>```

If it's not possible directly, is it possible to have a way to achieve it similarly?

I tried someMethod<TestClass>(new TestClass()), and tried to use Object.getOwnPerpertyNames(new TestClass()), still get nothing.

Are there some helper built-in functions that can construct an object with default values that I can later enumerate the object's properties?

Body:
For a defined class:

class TestClass {
            public testProp: string
            public testProp2: number
            public testProp3: boolean
            public testProp4: Date
            public testProp5: any
        }

Is it possible to enumerate all the defined properties in a way?

The idea is that I want to write a generic method to accept different types and iterate their properties:

function someMethod<T>() {
  // How to get the members of T?
}

If it's not possible directly, is it possible to have a way to achieve it similarly?

I tried someMethod<TestClass>(new TestClass()), and tried to use Object.getOwnPerpertyNames(new TestClass()), still get nothing.

Are there some helper built-in functions that can construct an object with default values that I can later enumerate the object's properties?


问:
Laravel Telescope - How to add tags to a specific cache for tracking its behaviour
Laravel Telescope seems to be a useful tool to control different requests.

One use I have in mind is to be able to track how often a cache is used.

Imagine a big application and you try to find out if it is worth to store certain database queries in the cache or if the queries in general do not occur too often. Especially if you want to improve an existing project and you want to try out separately if caching a specific database query makes sense.

Therefore I would like to be able to search for the specific cache key or a telescope tag when calling the cache.

If an application already has thousands of cache calls every day, it will probably be hard to search for a specific cache tag in Telescope without this capability.

Telescope's search box under "Cache" doesn't seem to inherently allow you to search for results using the cache key.

Does anyone here have experience how to do this correctly?

```<code>    $no_track_needed = cache()->remember("no_track_needed", 20, function() {
        return "Hello World";
    });

    $track_this = cache()->remember("track_this", 120, function() {
        return "Hello Telescope";
    });
</code>```

Sincerely and thank you for reading through

I have tried via the Laravel documentation to recreate such behavior, but then all cache keys are tagged instead of just the cache keys I want. Unfortunately I don't have much experience with this.

Body:
Laravel Telescope seems to be a useful tool to control different requests.

One use I have in mind is to be able to track how often a cache is used.

Imagine a big application and you try to find out if it is worth to store certain database queries in the cache or if the queries in general do not occur too often. Especially if you want to improve an existing project and you want to try out separately if caching a specific database query makes sense.

Therefore I would like to be able to search for the specific cache key or a telescope tag when calling the cache.

If an application already has thousands of cache calls every day, it will probably be hard to search for a specific cache tag in Telescope without this capability.

Telescope's search box under "Cache" doesn't seem to inherently allow you to search for results using the cache key.

Does anyone here have experience how to do this correctly?

    $no_track_needed = cache()->remember("no_track_needed", 20, function() {
        return "Hello World";
    });

    $track_this = cache()->remember("track_this", 120, function() {
        return "Hello Telescope";
    });

Sincerely and thank you for reading through

I have tried via the Laravel documentation to recreate such behavior, but then all cache keys are tagged instead of just the cache keys I want. Unfortunately I don't have much experience with this.


问:
python plotly scatter (line) conditional formatting
Trying to implement the following code example as a line plot (mode="lines"), whilst keeping the conditional coloring working. Conditional color formatting does not come through with 'line'.

```<code>import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({
    "x": [1, 2, 3, 4, 5, 6, 7],
    "y": [200, 400, 100, 800, 500, 200, 1100]
})

# Condition
colors = ["blue" if y > 600 else "red" for y in df["y"]]

# Scatter plot with conditional colors
fig = go.Figure(
    go.Scatter(
        x=df["x"],
        y=df["y"],
        mode="markers", # coloring does not work with mode="lines"
        marker=dict(color=colors)
    )
)
fig.show()
</code>```

I would rather keep it all in one Scatter, as opposed to subplots with make_subplots.

UPDATE when using when using mode="lines" AND plotly 5.11.0, no error message is through, however coloring doesn't come through:

I'm trying to make the marked lines red in this case as those markers are greater than 600.

Body:
Trying to implement the following code example as a line plot (mode="lines"), whilst keeping the conditional coloring working. Conditional color formatting does not come through with 'line'.

import plotly.graph_objects as go
import pandas as pd

df = pd.DataFrame({
    "x": [1, 2, 3, 4, 5, 6, 7],
    "y": [200, 400, 100, 800, 500, 200, 1100]
})

# Condition
colors = ["blue" if y > 600 else "red" for y in df["y"]]

# Scatter plot with conditional colors
fig = go.Figure(
    go.Scatter(
        x=df["x"],
        y=df["y"],
        mode="markers", # coloring does not work with mode="lines"
        marker=dict(color=colors)
    )
)
fig.show()

I would rather keep it all in one Scatter, as opposed to subplots with make_subplots.

UPDATE when using when using mode="lines" AND plotly 5.11.0, no error message is through, however coloring doesn't come through:

I'm trying to make the marked lines red in this case as those markers are greater than 600.


问:
I have a function in which i and add a class. I want to also change some state but when i do so the class isn't added
In this function i change state and add a class.

```<code>const nextQuestion = (e, state) => {
    if (state === true) {
      setScore((currentState) => currentState + 1);
      e.target.classList.add("quiz__question--true");
    } else {
      e.target.classList.add("quiz__question--false");
    }

    setTimeout(() => {
      setQuestion((currentQuestion) => currentQuestion + 1);
    }, "300");
  };

</code>```

When i add the setScore state line the class isn't added but when i remove it the class is added.

Why is this?

Thanks for your help!

Body:
In this function i change state and add a class.

const nextQuestion = (e, state) => {
    if (state === true) {
      setScore((currentState) => currentState + 1);
      e.target.classList.add("quiz__question--true");
    } else {
      e.target.classList.add("quiz__question--false");
    }

    setTimeout(() => {
      setQuestion((currentQuestion) => currentQuestion + 1);
    }, "300");
  };

When i add the setScore state line the class isn't added but when i remove it the class is added.

Why is this?

Thanks for your help!


问:
Informatica session in success status but have error in session log
My session finished succesfully but only one out of four targets has been inserted. When I looked into the session log, I got some error messages but task haven't failed, on contrary, everything went smoothly.

Does anyone know how it comes that I have error messages throug session log and task haven't been in failed status?

These are error messages I've been dealing with:

error messages


问:
In Django Admin can l set access rights for certain fields?
In Django-admin can l set access rights at field level where l can say this field can not be edited or deleted by a certain user. There is no option to edit a field or to put access rights on a certain field in Django 4.1.

I have tried it but it looks like l can only give rights at Table level.


问:
OpenAI Python API is giving gibberish responses for the query "hi"
I used Python to access the OpenAI API, then used discord.py to integrate it into a Discord bot. My command looks like this:

@bot.command()
async def chat(ctx, *, input: str):
    openai.api_key = os.getenv(envName)

    async with ctx.channel.typing():
        response = openai.Completion.create(
                    engine="text-davinci-003",  # latest model (the one used for GPT-3)
                    prompt=input,
                    temperature=random.randrange(50, 90) / 100,
                    max_tokens=1000,
                    top_p=1,
                    frequency_penalty=0,
                    presence_penalty=0,
                    timeout=10
                )

        output = response.choices[0].text

    await ctx.reply(output)
```

The command works properly as intended. I give it an input, and it gives me a proper output.

However, I recently discovered that for a simple input such as "hi", it gives me some gibberish output. Moreover, this output is completely different for each time.

Please refer to the images below for its output.

Try 1:

Try 2:

Try 3:

Note that this command works completely fine for any other queries: for example,

Correct response:

and another one:

Strangely, it gives a normal response for "hello" also.

What could be the reason why it responds improperly for a simple "hi" query?

Body:
I used Python to access the OpenAI API, then used discord.py to integrate it into a Discord bot. My command looks like this:

@bot.command()
async def chat(ctx, *, input: str):
    openai.api_key = os.getenv(envName)

    async with ctx.channel.typing():
        response = openai.Completion.create(
                    engine="text-davinci-003",  # latest model (the one used for GPT-3)
                    prompt=input,
                    temperature=random.randrange(50, 90) / 100,
                    max_tokens=1000,
                    top_p=1,
                    frequency_penalty=0,
                    presence_penalty=0,
                    timeout=10
                )

        output = response.choices[0].text

    await ctx.reply(output)

The command works properly as intended. I give it an input, and it gives me a proper output.

However, I recently discovered that for a simple input such as "hi", it gives me some gibberish output. Moreover, this output is completely different for each time.

Please refer to the images below for its output.

Try 1:

Try 2:

Try 3:

Note that this command works completely fine for any other queries: for example,

Correct response:

and another one:

Strangely, it gives a normal response for "hello" also.

What could be the reason why it responds improperly for a simple "hi" query?


问:
Gitlab CI/CD: environment variables in concurrent jobs
I wrote a .gitlab-ci file where I defined several jobs.
In that jobs, I am using environment variables from a gitlab repository (below an example):

In my .gitlab job, I do recover theses variables:

```<code># .gitlab-ci.yml
defaut:
  tags:
    - bla
    - blo

stage:
  - build
  - test
  - clean

.global-variables: &global-variables
  variables:
    ENV: "dev"
    TEST_VAR: ${TEST_VAR_DEV}

.global_rules:
  rules:
    - when: always
    <<: *global-variables

build:
  stage: build
  rules:
    - !reference [.global_rules, rules]
  script:
    - # do something to build the app
  environment:
    name: dev
    on_stop: clean

.test_job:
  stage: test
  rules:
    - !reference [.global_rules, rules]
  environment: dev

test_job_1:
  extends: .test_job
  script:
    - echo "This is test1 job to verify app behaviour"

test_job_2:
  extends: .test_job
  script:
    - echo "This is test2 job to verify app behaviour"

clean:
  stage: clean
  rules:
    - !reference [.global_rules, rules]
  script:
    - # do something to clean the app
  environment:
    name: dev
    action: stop

</code>```

Unfortunately, with the previous configuration of the pipeline, one of the jobs: job1 or job2 fails with the following error:

But I don't want these jobs to be seen as "deployement jobs". I need the job to access the variables from the required environment.

Am I missing something?

Body:
I wrote a .gitlab-ci file where I defined several jobs.
In that jobs, I am using environment variables from a gitlab repository (below an example):

In my .gitlab job, I do recover theses variables:

# .gitlab-ci.yml
defaut:
  tags:
    - bla
    - blo

stage:
  - build
  - test
  - clean

.global-variables: &global-variables
  variables:
    ENV: "dev"
    TEST_VAR: ${TEST_VAR_DEV}

.global_rules:
  rules:
    - when: always
    <<: *global-variables

build:
  stage: build
  rules:
    - !reference [.global_rules, rules]
  script:
    - # do something to build the app
  environment:
    name: dev
    on_stop: clean

.test_job:
  stage: test
  rules:
    - !reference [.global_rules, rules]
  environment: dev

test_job_1:
  extends: .test_job
  script:
    - echo "This is test1 job to verify app behaviour"

test_job_2:
  extends: .test_job
  script:
    - echo "This is test2 job to verify app behaviour"

clean:
  stage: clean
  rules:
    - !reference [.global_rules, rules]
  script:
    - # do something to clean the app
  environment:
    name: dev
    action: stop

Unfortunately, with the previous configuration of the pipeline, one of the jobs: job1 or job2 fails with the following error:

But I don't want these jobs to be seen as "deployement jobs". I need the job to access the variables from the required environment.

Am I missing something?


问:
What is the order in which the functions that inherit the Activity are called?
What is the order in which the functions that inherit from Activity are called, in relation to the other functions and in relation to the Activity lifecycle?

functions such as: onCreateOptionsMenu, etc.

I tried a search, but all that came out were results that explain the Activity lifecycle


问:
Jackson ObjectMapper.readValue throws NullPointerException, LRUMap.get(LRUMap.java:68)
I write a hive UDF which looks like below:

```<code>public class DemoUDF extends GenericUDF{
      private ObjectMapper mapper = new ObjectMapper();

      ... initialize() method...

      public Object evaluate(DeferredObject[] deferredObjects) throws HiveException{
           ... ...
           ActionVO vo = mapper.readValue(target_str, ActionVO.class);
           ... ...
      }
}
</code>```

While I add this function into hive,and execute it with some query,there exists the exception below:

Caused by : java.lang.NullPointerException
at com.fasterxml.jackson.databind.util.LRUMap.get(LRUMap.java:68)
at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1255)
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1194)
at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:608)

while I change the ObjectMapper declaration to below,it works fine!

```<code>private static final ObjectMapper mapper = new ObjectMapper();
</code>```

So why? What effect does it make?

Body:
I write a hive UDF which looks like below:

public class DemoUDF extends GenericUDF{
      private ObjectMapper mapper = new ObjectMapper();

      ... initialize() method...

      public Object evaluate(DeferredObject[] deferredObjects) throws HiveException{
           ... ...
           ActionVO vo = mapper.readValue(target_str, ActionVO.class);
           ... ...
      }
}

While I add this function into hive,and execute it with some query,there exists the exception below:

Caused by : java.lang.NullPointerException
at com.fasterxml.jackson.databind.util.LRUMap.get(LRUMap.java:68)
at com.fasterxml.jackson.databind.type.TypeFactory._fromClass(TypeFactory.java:1255)
at com.fasterxml.jackson.databind.type.TypeFactory._fromAny(TypeFactory.java:1194)
at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:608)

while I change the ObjectMapper declaration to below,it works fine!

private static final ObjectMapper mapper = new ObjectMapper();

So why? What effect does it make?


问:
Why aren't C++ libraries showing up for me while trying to set uop VSCode for C++ (MacOS)
hey im trying to set up vscode for c on my mac (MacOS Ventura 13.0, 1.4GHz intel core i5) following this Using Clang in Visual Studio Code guide but when get to the step with the helloworld.ccp file, i get an error for my #includes saying "cannot open source file '[library]'", this is happening for all of the #includes in the given code and ive tried following instructions to install the libraries thru vcpkg but these libraries arent on there. ive followed all previous instructions like installing Xcode

ive tried restarting vscode a number of times, insstalling these libraries from different websites, looking for extensions that might help and for other ways of setting up vscode that dont require this method. im pretty new to coding so its probably something small messing it up but i havent been able to figure it out.


问:
Conditionally hide Google Adsense auto ads in react spa
I have a react spa, in which I am using Google Adsense to display ads. I am using auto ads feature of Google Adsense which intelligently displays ads at appropriate location on the website. I have pro membership on my website and want to hide ads for those people who has pro membership.

I am able to hide the ads if I am explicitly embedding the ads using code snippets in react but I want to use Google Adsense version ads. I want to understand how can I hide ads for pro members only in Google Adsense auto ads mode?


问:
Can we validate octet-stream data using JOI?
I want to validate the payload data from postman which is sending as a octet-stream. Is it possible to validate this data

we use

```<code>  options: {
            validate: {
                query: Joi.object({
                    marketCode: Joi.string().required()
</code>```

like this any way to validate octet-stream data

Body:
I want to validate the payload data from postman which is sending as a octet-stream. Is it possible to validate this data

we use

  options: {
            validate: {
                query: Joi.object({
                    marketCode: Joi.string().required()

like this any way to validate octet-stream data


问:
Debezium SqlServerConnector timezone issue with AvroConverter
I am creating a Debezium connector to retrieve data from a SQL Server table.
In that table, there is a START_DATE column (the type is datetime) that is representing a datetime in local timezone (Euroep/Rome).

The problem is that the connector interpret that as a UTC datetime and convert the column values to timestamps. When I convert back the timestamps to datetime, the datetimes are obviously referring to UTC timezone.

I tried putting "database.serverTimezone": "Europe/Rome" as an option in the connector configuration, but it does not work.

{
  "name": "xxx",
  "config": {
    "name": "xxx",
    "connector.class": "io.debezium.connector.sqlserver.SqlServerConnector",
    "key.converter": "io.confluent.connect.avro.AvroConverter",
    "key.converter.schema.registry.url": "http://schema-registry:8081",
    "key.converter.schemas.enable": "true",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter.schema.registry.url": "http://schema-registry:8081",
    "value.converter.schemas.enable": "true",
    ...
    "database.serverTimezone": "Europe/Rome"
  }
}
```


问:
Read data from file and use it on Angular ssr and csr
I have a config file and I want to use it without HTTP request on angular SSR and then somehow send data to CSR and use it on that too, this config file is a list of links that I want to use in website footer and be able to change them without rebuilding the project or making HTTP request.
The solution I tryed is to read from the config file every 1 hour in server.ts like this:

```<code>fs.readFile('./src/skills.txt', 'utf8', (err, data) => {
    console.log('updated skills');
    if (err) {
      console.error(err);
      return;
    }
    if(data) {
      skills = data;
    }
  });
</code>```

But then for sending this data to response all I could think about which is not really a good way of doing it I guess is to loop around this file and create my output HTML and then replace a key I put in footer HTML with it in returned html as bellow:

```<code>res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
    if(skills) {
      html = html.replace('#skills_placeholder',skills);
    }
    res.send(html);
  });
</code>```

This way I have the output I need in SSR response but I also want to have this response on CSR when user is logged in. I tryed to add an element with and id and select it on CSR but its undefined, Tryed example :

```<code>res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
        if(skills) {
          html = html + '<span class="d-none" id="perfectlancer_skills">' + skills + '</span>';
        }
        res.send(html);
      });
</code>```

And then on CSR I tryed:

```<code>this.doc.getElementById('perfectlancer_skills'.innerHTML
</code>```

but it is undefined althoght it exists on SSR response;

Body:
I have a config file and I want to use it without HTTP request on angular SSR and then somehow send data to CSR and use it on that too, this config file is a list of links that I want to use in website footer and be able to change them without rebuilding the project or making HTTP request.
The solution I tryed is to read from the config file every 1 hour in server.ts like this:

fs.readFile('./src/skills.txt', 'utf8', (err, data) => {
    console.log('updated skills');
    if (err) {
      console.error(err);
      return;
    }
    if(data) {
      skills = data;
    }
  });

But then for sending this data to response all I could think about which is not really a good way of doing it I guess is to loop around this file and create my output HTML and then replace a key I put in footer HTML with it in returned html as bellow:

res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
    if(skills) {
      html = html.replace('#skills_placeholder',skills);
    }
    res.send(html);
  });

This way I have the output I need in SSR response but I also want to have this response on CSR when user is logged in. I tryed to add an element with and id and select it on CSR but its undefined, Tryed example :

res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
        if(skills) {
          html = html + '' + skills + '';
        }
        res.send(html);
      });

And then on CSR I tryed:

this.doc.getElementById('perfectlancer_skills'.innerHTML

but it is undefined althoght it exists on SSR response;


问:
SAML2.0 SP Initiated Single Logout from SP to Okta IDP not redirecting to SP SLO URL
I am trying to implement SAML2 authentication in my java web app.
When trying to login and logout from SP things are working as expected.
In a particular use case, when session on okta is terminated and after that logout request is sent to okta from sp, okta is not redirecting to sp slo url instead it is opening okta login page. Is there any configuration to redirect to slo url from okta in such a case also? Or is this behaviour correct?

As per my understanding this is as per OKTA's inherent logic. But still, wanted to understand if there is any configuration or tag in request to handle this.


问:
Possible to detect if user has "open pdfs in chrome" enabled?
Is it possible to detect the chrome setting "Open pdfs in chrome" with javascript?

Located here chrome://settings/content/pdfDocuments


问:
error when I use jsonpath(python version)
I am trying to extract some info from a list of json files, and I use jsonfiles, it worked well when I extract from a single json file, however when I use for a list of files, it returns False, and all False!!! Here are code

```<code>json_path = "/content/drive/MyDrive/dataset_demo/results"
os.chdir(json_path)

for file_json in os.listdir(json_path):
  if file_json.endswith('.json'):
    nums_comment = jsonpath(file_json, '$.node.edge_media_to_comment[*]')
    nums_likes = jsonpath(file_json, '$.node.edge_media_preview_like[*]')
    print(nums_comment,nums_likes)
</code>```

and it ruturned

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

the number of json files is right, but the result are wrong

Body:
I am trying to extract some info from a list of json files, and I use jsonfiles, it worked well when I extract from a single json file, however when I use for a list of files, it returns False, and all False!!! Here are code

json_path = "/content/drive/MyDrive/dataset_demo/results"
os.chdir(json_path)

for file_json in os.listdir(json_path):
  if file_json.endswith('.json'):
    nums_comment = jsonpath(file_json, '$.node.edge_media_to_comment[*]')
    nums_likes = jsonpath(file_json, '$.node.edge_media_preview_like[*]')
    print(nums_comment,nums_likes)

and it ruturned

False False
False False
False False
False False

the number of json files is right, but the result are wrong


问:
Missing Test Points using .Net sdk GetPointsByQueryAsync
I am using the method "GetPointsByQueryAsync" when I use it for a small number of test cases (as input) it is working fine but when I use it for a large number of test cases (as input), it messes up like some test points will miss, when I try to get miss points separately, it works fine. I have posted this issue on the Visual studio community, they refuse to fix it and said it is not our policy to look into this issue. I have a test case count of 3000 and a test point count of 15000.

https://developercommunity.visualstudio.com/t/Missing-Test-Points-using-Net-sdk/10215409

```<code>using Microsoft.TeamFoundation.TestManagement.WebApi;

public List<TestPoint> GetTestPoints(Uri uri, string oAuthAccessToken, List<int> testcaseIds)
{
    TestPointsQuery outputQuery= null;

    try
    {
        VssOAuthAccessTokenCredential mCredential = new VssOAuthAccessTokenCredential(oAuthAccessToken);

        VssConnection connection =
                        new VssConnection(uri, mCredential);

        TestManagementHttpClient testManagementHttpClient = connection.GetClient<TestManagementHttpClient>();

        TestPointsQuery query = new TestPointsQuery();

        PointsFilter filter = new PointsFilter();

        filter.TestcaseIds = testcaseIds;

        query.PointsFilter = filter;

        outputQuery = testManagementHttpClient.GetPointsByQueryAsync(query, WIProject.Id).Result;

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    return outputQuery.Points;
}
</code>```

Body:
I am using the method "GetPointsByQueryAsync" when I use it for a small number of test cases (as input) it is working fine but when I use it for a large number of test cases (as input), it messes up like some test points will miss, when I try to get miss points separately, it works fine. I have posted this issue on the Visual studio community, they refuse to fix it and said it is not our policy to look into this issue. I have a test case count of 3000 and a test point count of 15000.

https://developercommunity.visualstudio.com/t/Missing-Test-Points-using-Net-sdk/10215409

using Microsoft.TeamFoundation.TestManagement.WebApi;

public List<TestPoint> GetTestPoints(Uri uri, string oAuthAccessToken, List<int> testcaseIds)
{
    TestPointsQuery outputQuery= null;

    try
    {
        VssOAuthAccessTokenCredential mCredential = new VssOAuthAccessTokenCredential(oAuthAccessToken);

        VssConnection connection =
                        new VssConnection(uri, mCredential);

        TestManagementHttpClient testManagementHttpClient = connection.GetClient<TestManagementHttpClient>();

        TestPointsQuery query = new TestPointsQuery();

        PointsFilter filter = new PointsFilter();

        filter.TestcaseIds = testcaseIds;

        query.PointsFilter = filter;

        outputQuery = testManagementHttpClient.GetPointsByQueryAsync(query, WIProject.Id).Result;

    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    return outputQuery.Points;
}


问:
Add custom button along with existing toolbar options ngx quill - angular
I am working on building rich text editor in angular.able to get editor with default existing option, needs to add an new button now in the tool bar tried to add that but its not working along with existing options when added new button only that button is coming not the other configured in the ts file. Can both configuation + custom works at same time if so any snippet will be helpful. If not to add all the configured toolbar options in html any place its configured to get html snippet?</p>


问:
Swiperjs in web component return duplicated items
I'm creating a custom carousel web component with using Swiperjs as part of the element.

The quantity of items is dynamic, it is depend on the value that get from the web component attribute sliderBgImage and sliderCopyImage.

Then, it will loop thru the array and implementing the items with Swiper.js carousel library.
Hope someone can advise on this, thank you!

index.html

```<code>    <div style="width:320px;height:480px;">
        <verticalsliderBgImage="banner1.png,banner2.png" sliderCopyImage="copy1.png,copy2.png" sliderlanding1="http://www.google.com" sliderlanding2="http://www.test.com" sliderlanding3="http://www.test.com" sliderlanding4="" sliderlanding5="" autoplay="true" speed="2000" pagingColor="3eff8a"></vertical>
    </div>
    <script src="vertical.js" type="module"></script>
    <script src="https://s0.2mdn.net/creatives/assets/4671853/swiper.min.js"></script>

</body>
</code>```

Vertical.js

```<code>template.innerHTML = `
<link rel="stylesheet" href="./swiper.min.css"/><link rel="stylesheet" href="./vertical.css"/><div id="mainContainer"><div class="swiper-container"><div class="swiper-wrapper"></div><div class="swiper-pagination"></div></div></div>`;

class Vertical extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }

  handleSliderClick = () => {
    let slides = this.shadowRoot.querySelectorAll(".swiper-slide");

    for (let i = 0; i < slides.length; i++) {
      const slide = slides[i];

      slide.addEventListener("click", () => {
        const getslide = slide.getAttribute("data");
        const landing = getslide.slice(-1);
        Enabler.exitOverride(getslide, this.getAttribute(landing));
      });
    }
  };

  setPaginateColor = () => {
    const activeBullet = this.shadowRoot.querySelector(
      ".swiper-pagination-bullet-active"
    );
    if (activeBullet) {
      activeBullet.style.backgroundColor = `#${this.getAttribute(
        "pagingColor"
      )}`;
    }
  };

  darkNav = () => {
    var slides = this.shadowRoot.querySelectorAll(".swiper-slide");
    var copies = this.shadowRoot.querySelectorAll(".copies");

    for (let i = 0, c = 0; i < slides.length, c < copies.length; i++, c++) {
      const slide = slides[i];
      const copy = copies[c];

      if (
        slide.classList.contains("swiper-slide-active") ||
        slide.classList.contains("swiper-slide-duplicate-active")
      ) {
        slide.classList.add("bubbleslide");
        this.setPaginateColor();
        setTimeout(() => {
          copy.classList.add("slide-top");
        }, 200);
      } else {
        slide.classList.remove("bubbleslide");
        copy.classList.remove("slide-top");
      }
    }
  };

  setSwiper = (ele) => {
    const setAutoplay = this.getAttribute("autoplay");
    const setSpeed = this.getAttribute("speed");

    var swiper = new Swiper(ele, {
      autoplay: {
        delay: setSpeed,
      },
      direction: "vertical",
      pagination: {
        el: this.shadowRoot.querySelector(".swiper-pagination"),
        clickable: true,
      },
      loop: true,
      on: {
        slideChangeTransitionStart: this.darkNav,
      },
    });

    this.setPaginateColor();

    if (setAutoplay === "true" || setAutoplay === "TRUE") {
      swiper.autoplay.start();
    } else {
      swiper.autoplay.stop();
    }

    this.handleSliderClick();

    setTimeout(() => {
      swiper.autoplay.stop();
    }, 30000);
  };

  static get observedAttributes() {
    return [
      "brandLogo",
      "sliderBgImage",
      "sliderCopyImage",
      "pagingColor",
      "autoplay",
      "speed",
    ];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    var bgImgs = this.getAttribute("sliderBgImage").split(",");
    var copyImgs = this.getAttribute("sliderCopyImage").split(",");
    var items = [];

    // clean up each item
    for (let i = 0; i < bgImgs.length; i++) {
      let val1 = bgImgs[i];
      let val2 = copyImgs[i];
      let obj = {
        bg: val1,
        tag: val2,
      };
      items.push(obj);
    }
   }

  connectedCallback() {
    var bgImgs = this.getAttribute("sliderBgImage").split(",");
    var copyImgs = this.getAttribute("sliderCopyImage").split(",");
    var items = [];

    // clean up each item
    for (let i = 0; i < bgImgs.length; i++) {
      let val1 = bgImgs[i];
      let val2 = copyImgs[i];
      let obj = {
        bg: val1,
        tag: val2,
      };
      items.push(obj);
    }

    let checkItem = null;
    const swiperContainer = this.shadowRoot.querySelector(".swiper-wrapper");
    const swiperMain = this.shadowRoot.querySelector(".swiper-container");

    items.map((v, k) => {
      let html = `<div class="swiper-slide slide${k + 1}" data="slide${
        k + 1
      }" style="background-image:url('${v.bg}')"><div class="copies copy${
        k + 1
      }" style="background-image:url('${v.tag}')"></div></div>`;
      checkItem++;
      return (swiperContainer.innerHTML += html);
    });

    let check = setInterval(() => {
      if (checkItem === items.length) {
        this.setSwiper(swiperMain);
        clearInterval(check);
      }
    }, 500);
  }

}

export default Vertical;
</code>```

Body:
I'm creating a custom carousel web component with using Swiperjs as part of the element.

The quantity of items is dynamic, it is depend on the value that get from the web component attribute sliderBgImage and sliderCopyImage.

Then, it will loop thru the array and implementing the items with Swiper.js carousel library.
Hope someone can advise on this, thank you!

index.html

        <verticalsliderBgImage="banner1.png,banner2.png" sliderCopyImage="copy1.png,copy2.png" sliderlanding1="http://www.google.com" sliderlanding2="http://www.test.com" sliderlanding3="http://www.test.com" sliderlanding4="" sliderlanding5="" autoplay="true" speed="2000" pagingColor="3eff8a"></vertical>

Vertical.js

template.innerHTML = `
<link rel="stylesheet" href="./swiper.min.css"/><link rel="stylesheet" href="./vertical.css"/>

`;

class Vertical extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }

  handleSliderClick = () => {
    let slides = this.shadowRoot.querySelectorAll(".swiper-slide");

    for (let i = 0; i < slides.length; i++) {
      const slide = slides[i];

      slide.addEventListener("click", () => {
        const getslide = slide.getAttribute("data");
        const landing = getslide.slice(-1);
        Enabler.exitOverride(getslide, this.getAttribute(landing));
      });
    }
  };

  setPaginateColor = () => {
    const activeBullet = this.shadowRoot.querySelector(
      ".swiper-pagination-bullet-active"
    );
    if (activeBullet) {
      activeBullet.style.backgroundColor = `#${this.getAttribute(
        "pagingColor"
      )}`;
    }
  };

  darkNav = () => {
    var slides = this.shadowRoot.querySelectorAll(".swiper-slide");
    var copies = this.shadowRoot.querySelectorAll(".copies");

    for (let i = 0, c = 0; i < slides.length, c < copies.length; i++, c++) {
      const slide = slides[i];
      const copy = copies[c];

      if (
        slide.classList.contains("swiper-slide-active") ||
        slide.classList.contains("swiper-slide-duplicate-active")
      ) {
        slide.classList.add("bubbleslide");
        this.setPaginateColor();
        setTimeout(() => {
          copy.classList.add("slide-top");
        }, 200);
      } else {
        slide.classList.remove("bubbleslide");
        copy.classList.remove("slide-top");
      }
    }
  };

  setSwiper = (ele) => {
    const setAutoplay = this.getAttribute("autoplay");
    const setSpeed = this.getAttribute("speed");

    var swiper = new Swiper(ele, {
      autoplay: {
        delay: setSpeed,
      },
      direction: "vertical",
      pagination: {
        el: this.shadowRoot.querySelector(".swiper-pagination"),
        clickable: true,
      },
      loop: true,
      on: {
        slideChangeTransitionStart: this.darkNav,
      },
    });

    this.setPaginateColor();

    if (setAutoplay === "true" || setAutoplay === "TRUE") {
      swiper.autoplay.start();
    } else {
      swiper.autoplay.stop();
    }

    this.handleSliderClick();

    setTimeout(() => {
      swiper.autoplay.stop();
    }, 30000);
  };

  static get observedAttributes() {
    return [
      "brandLogo",
      "sliderBgImage",
      "sliderCopyImage",
      "pagingColor",
      "autoplay",
      "speed",
    ];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    var bgImgs = this.getAttribute("sliderBgImage").split(",");
    var copyImgs = this.getAttribute("sliderCopyImage").split(",");
    var items = [];

    // clean up each item
    for (let i = 0; i < bgImgs.length; i++) {
      let val1 = bgImgs[i];
      let val2 = copyImgs[i];
      let obj = {
        bg: val1,
        tag: val2,
      };
      items.push(obj);
    }
   }

  connectedCallback() {
    var bgImgs = this.getAttribute("sliderBgImage").split(",");
    var copyImgs = this.getAttribute("sliderCopyImage").split(",");
    var items = [];

    // clean up each item
    for (let i = 0; i < bgImgs.length; i++) {
      let val1 = bgImgs[i];
      let val2 = copyImgs[i];
      let obj = {
        bg: val1,
        tag: val2,
      };
      items.push(obj);
    }

    let checkItem = null;
    const swiperContainer = this.shadowRoot.querySelector(".swiper-wrapper");
    const swiperMain = this.shadowRoot.querySelector(".swiper-container");

    items.map((v, k) => {
      let html = `

`;
      checkItem++;
      return (swiperContainer.innerHTML += html);
    });

    let check = setInterval(() => {
      if (checkItem === items.length) {
        this.setSwiper(swiperMain);
        clearInterval(check);
      }
    }, 500);
  }

}

export default Vertical;


问:
Python : Usecols do not match columns, columns expected but not found error showing tried the below solutions given in Stack overflow
Reading the CSV file using pandas to get specific column data with parameter usecols=[listofcolumnnames] which is 146 column names and it is showing 16 columns not found (  Usecols do not match columns, columns expected but not found error )

Pandas- ValueError: Usecols do not match columns, columns expected but not found

https://bobbyhadz.com/blog/python-replace-single-with-double-quotes-in-list#:~:text=Use%20the%20str.,double%20quotes%20in%20each%20string.

I have tried this above given stackoverflow steps to solve the problem but not worked .

enter image description here

I have tried below methods to get the columns :

Method one:

```<code>file1DF=pd.read_csv(pathoffile[0],usecols=file1column)
print(file1DF)
</code>```

Method Two:

```<code>file1DF=pd.read_csv(pathoffile[0],usecols=file1column,sep=',').columns.tolist()
print(file1DF)
</code>```

Method Three:

```<code>e1=pd.read_csv(pathoffile[0],sep=',')
e2=pd.DataFrame(exam1)
e3=e2[listofcolumns]
</code>```

Method Four:

```<code>e1=pd.read_csv(pathoffile[0],sep=',')
e2=pd.DataFrame(exam1)
e3=e2[listofcolumns]
jstrlist=Json.dumps(listofcolumns)
e3=e2[jstrlist]
</code>```

but it shows keyerror and mentioned all 146 column names in double quotes in list of string '["146 column names"]'

Body:
Reading the CSV file using pandas to get specific column data with parameter usecols=[listofcolumnnames] which is 146 column names and it is showing 16 columns not found (  Usecols do not match columns, columns expected but not found error )

Pandas- ValueError: Usecols do not match columns, columns expected but not found

https://bobbyhadz.com/blog/python-replace-single-with-double-quotes-in-list#:~:text=Use%20the%20str.,double%20quotes%20in%20each%20string.

I have tried this above given stackoverflow steps to solve the problem but not worked .

enter image description here

I have tried below methods to get the columns :

Method one:

file1DF=pd.read_csv(pathoffile[0],usecols=file1column)
print(file1DF)

Method Two:

file1DF=pd.read_csv(pathoffile[0],usecols=file1column,sep=',').columns.tolist()
print(file1DF)

Method Three:

e1=pd.read_csv(pathoffile[0],sep=',')
e2=pd.DataFrame(exam1)
e3=e2[listofcolumns]

Method Four:

e1=pd.read_csv(pathoffile[0],sep=',')
e2=pd.DataFrame(exam1)
e3=e2[listofcolumns]
jstrlist=Json.dumps(listofcolumns)
e3=e2[jstrlist]

but it shows keyerror and mentioned all 146 column names in double quotes in list of string '["146 column names"]'


问:
What is the need/use for enable annotation processing for Lombok?
I am new to maven and was looking into using Lombok.

I added the following to my pom:

```<code><dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.24</version>
</dependency>
</code>```

I also added the following class:

```<code>import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class User {
        private String firstName;
        private String lastName;
        private String email;
    }
</code>```

Now what is not clear to me is how from this class code is generated. I have tried an example with json to pojo conversion and for that to work I had to add a plugin to the build cycle.

But in this case with Lombok when I clicked on package and then checked under target/classes I found that the User.class has a bunch of code added based on the anotations.

But how exactly was that code added? I googled a bit and it seems that this code generation happens because of enabling annotation processing in the InteliJ preferences but when I checked my IDE that was not set. So how was the code generated?

Body:
I am new to maven and was looking into using Lombok.

I added the following to my pom:

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.24</version>
</dependency>

I also added the following class:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class User {
        private String firstName;
        private String lastName;
        private String email;
    }

Now what is not clear to me is how from this class code is generated. I have tried an example with json to pojo conversion and for that to work I had to add a plugin to the build cycle.

But in this case with Lombok when I clicked on package and then checked under target/classes I found that the User.class has a bunch of code added based on the anotations.

But how exactly was that code added? I googled a bit and it seems that this code generation happens because of enabling annotation processing in the InteliJ preferences but when I checked my IDE that was not set. So how was the code generated?


问:
After toggling ant design theme from "light" to "realDark" in ant design SettingsDrawer the changes are not visible until I refresh the page
I am using zustand for the global state. When I toggle the switch for the dark mode state changes but the page still has the same theme until I refresh the page.

```<code><SettingDrawer
            pathname={location.pathname}
            enableDarkTheme
            getContainer={() => document.getElementById('test-pro-layout')}
            settings={settings}
            onSettingChange={(changeSetting) => {
              setSetting({
                ...changeSetting,
                navTheme: isDark? 'realDark': 'light',
              });
            }}
            disableUrlParams={false}
/>
</code>```

isDark is the the global state variable which is either true or false.

Do you know what can cause this problem and how to fix it?

Body:
I am using zustand for the global state. When I toggle the switch for the dark mode state changes but the page still has the same theme until I refresh the page.

<SettingDrawer
            pathname={location.pathname}
            enableDarkTheme
            getContainer={() => document.getElementById('test-pro-layout')}
            settings={settings}
            onSettingChange={(changeSetting) => {
              setSetting({
                ...changeSetting,
                navTheme: isDark? 'realDark': 'light',
              });
            }}
            disableUrlParams={false}
/>

isDark is the the global state variable which is either true or false.

Do you know what can cause this problem and how to fix it?