问:
Facing issue while building next app using npm run build
```<code>Error occurred prerendering page "/actions/user". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bdata%2C%20error%2C%20loading%2C%20mutate%2C%20isValidating%7D for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

    at a.b.read (D:\Portfolio\portfolio\portfolioapp\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (D:\Portfolio\portfolio\portfolioapp\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\server\render.js:751:45)
    at Object.defaultGetInitialProps (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\server\render.js:389:51)
    at Function.getInitialProps (D:\Portfolio\portfolio\portfolioapp\.next\server\pages\_document.js:502:20)
    at Object.loadGetInitialProps (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\shared\lib\utils.js:69:29)
</code>```

I am trying to build project and triigered npm run build command for generating production app build but seems like thier is issue with prerendering of some the pages

Body:
Error occurred prerendering page "/actions/user". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bdata%2C%20error%2C%20loading%2C%20mutate%2C%20isValidating%7D for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

    at a.b.read (D:\Portfolio\portfolio\portfolioapp\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (D:\Portfolio\portfolio\portfolioapp\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\server\render.js:751:45)
    at Object.defaultGetInitialProps (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\server\render.js:389:51)
    at Function.getInitialProps (D:\Portfolio\portfolio\portfolioapp\.next\server\pages\_document.js:502:20)
    at Object.loadGetInitialProps (D:\Portfolio\portfolio\portfolioapp\node_modules\next\dist\shared\lib\utils.js:69:29)

I am trying to build project and triigered npm run build command for generating production app build but seems like thier is issue with prerendering of some the pages


来源: stackexchange

问:
Deploy ASP.NET Core Web API on CPanel
I have been looking for a solution to deploy ASP.NET Core Web API Project on my CPanel Server.
I am using MySQL Database for APIs.
But couldn't find a way to do so. Basically, I want my APIs on my Sub Domain.

I did Research on Internet on different forums like Stack Overflow, MSDN, Code Project but couldn't find a way to do so.
Any Help would be appreciated

ContentLicense: CC BY-SA 4.0

Title: Deploy ASP.NET Core Web API on CPanel


问:
Python kivy event processing
```<code>from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivymd.uix.screen import Screen, MDScreen
from kivymd.uix.fitimage import FitImage
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.card import MDCard
from kivy.uix.image import Image
from kivy.animation import Animation
from kivymd.uix.snackbar import Snackbar
from kivy.clock import Clock
from kivy.uix.label import Label
from kivymd.uix.label import MDLabel
from kivy.core.audio import SoundLoader
from kivy.uix.popup import Popup
from kivy.core.window import Window
from skpy import SkypeEventLoop
from skpy import SkypeEvent
from skpy import SkypeNewMessageEvent
from skpy import SkypeCallMsg
from skpy import Skype
import subprocess

from kivymd.uix.selectioncontrol import MDSwitch
import random

class SkypeRecordApp(MDApp):

        def func(self, dt):

            class MySkype(SkypeEventLoop):

                  def onEvent(self, event):
                      print('Проверка...')

                      try:
                         print(event.msg.content)
                         if event.type == 'NewMessage':

                             print(event.msg.content)
                             check_for_call = event.msg.content[:6]
                         if check_for_call == """{"cp":""":
                             print("Входящий звонок")
                      except:
                            pass

            if __name__ == "__main__":
                  sk = MySkype("email", 'password', autoAck=True)
                  sk.subscribePresence() # Only if you need contact presence events.
                  sk.loop()
                  #problem here

        def click(self, switch, value):

                if (value):

                        self.www = Clock.schedule_interval(self.func, 1)

                else:
                        print('off')
                        self.www.cancel()

        def __init__(self, **kwargs):
                super().__init__(**kwargs)

                Window.clearcolor = (100, 100, 100, 100)

                self.window = MDBoxLayout(opacity=0, md_bg_color=[.2, .68, .93, 1], orientation='vertical')

                anim = Animation()
                anim = Animation(opacity=1)

                anim.start(self.window)

        def build(self):
                self.theme_cls.material_style = "M3"
                Window.size = (450, 600)

                logo_screen = MDBoxLayout(orientation="vertical")
                logo_image = Image(source='skype.png',pos_hint={"center_x":.3, "center_y":.19})
                logo_screen.add_widget(logo_image)

                logo_screen.add_widget(Label(text="Skyper", font_name="Segoe UI Bold.ttf", font_size=58, pos_hint={"center_x":.3, "center_y":.1}))

                self.window.add_widget(logo_screen)
                switch = MDSwitch(pos_hint={"center_x":.28, "center_y":.1}, track_color_active="white", on_active=self.click)
                self.window.add_widget(switch)
                switch.bind(active=self.click)
                rec = Label(text="Record", font_size=28, pos_hint={"center_x":.3, "center_y":.1}, size_hint_y=None)
                self.window.add_widget(rec)

                self.window.add_widget(BoxLayout(orientation="vertical"))
                return self.window

SkypeRecordApp().run()
</code>```

I trying to get events of SkPy with kivymd MDSwitch (when is active), but im already create python kivy loop with
self.www = Clock.schedule_interval(self.func, 1)

problem in because is that loop, Python kivy app stopping when this work, I know about cycles in kivy (can't use in kivy), but how I can do this?

sk.loop()

How I can get events of SkPy in Python kivy?

Title: Python kivy event processing

Body:
from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivymd.uix.screen import Screen, MDScreen
from kivymd.uix.fitimage import FitImage
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivymd.uix.card import MDCard
from kivy.uix.image import Image
from kivy.animation import Animation
from kivymd.uix.snackbar import Snackbar
from kivy.clock import Clock
from kivy.uix.label import Label
from kivymd.uix.label import MDLabel
from kivy.core.audio import SoundLoader
from kivy.uix.popup import Popup
from kivy.core.window import Window
from skpy import SkypeEventLoop
from skpy import SkypeEvent
from skpy import SkypeNewMessageEvent
from skpy import SkypeCallMsg
from skpy import Skype
import subprocess

from kivymd.uix.selectioncontrol import MDSwitch
import random

class SkypeRecordApp(MDApp):

        def func(self, dt):

            class MySkype(SkypeEventLoop):

                  def onEvent(self, event):
                      print('Проверка...')

                      try:
                         print(event.msg.content)
                         if event.type == 'NewMessage':

                             print(event.msg.content)
                             check_for_call = event.msg.content[:6]
                         if check_for_call == """{"cp":""":
                             print("Входящий звонок")
                      except:
                            pass

            if __name__ == "__main__":
                  sk = MySkype("email", 'password', autoAck=True)
                  sk.subscribePresence() # Only if you need contact presence events.
                  sk.loop()
                  #problem here

        def click(self, switch, value):

                if (value):

                        self.www = Clock.schedule_interval(self.func, 1)

                else:
                        print('off')
                        self.www.cancel()

        def __init__(self, **kwargs):
                super().__init__(**kwargs)

                Window.clearcolor = (100, 100, 100, 100)

                self.window = MDBoxLayout(opacity=0, md_bg_color=[.2, .68, .93, 1], orientation='vertical')

                anim = Animation()
                anim = Animation(opacity=1)

                anim.start(self.window)

        def build(self):
                self.theme_cls.material_style = "M3"
                Window.size = (450, 600)

                logo_screen = MDBoxLayout(orientation="vertical")
                logo_image = Image(source='skype.png',pos_hint={"center_x":.3, "center_y":.19})
                logo_screen.add_widget(logo_image)

                logo_screen.add_widget(Label(text="Skyper", font_name="Segoe UI Bold.ttf", font_size=58, pos_hint={"center_x":.3, "center_y":.1}))

                self.window.add_widget(logo_screen)
                switch = MDSwitch(pos_hint={"center_x":.28, "center_y":.1}, track_color_active="white", on_active=self.click)
                self.window.add_widget(switch)
                switch.bind(active=self.click)
                rec = Label(text="Record", font_size=28, pos_hint={"center_x":.3, "center_y":.1}, size_hint_y=None)
                self.window.add_widget(rec)

                self.window.add_widget(BoxLayout(orientation="vertical"))
                return self.window

SkypeRecordApp().run()

I trying to get events of SkPy with kivymd MDSwitch (when is active), but im already create python kivy loop with
self.www = Clock.schedule_interval(self.func, 1)

problem in because is that loop, Python kivy app stopping when this work, I know about cycles in kivy (can't use in kivy), but how I can do this?

sk.loop()

How I can get events of SkPy in Python kivy?


问:
Application works with docker command but not with docker compose
I created tests for my application using docker inside the dotnet tests. It pulls an image from rabbitmq and starts it before testing and it works fine.

Now I'm trying to add these tests to docker, but to run docker inside a container I'm using volumes in docker.sock to transmit the commands to the host machine.

```<code>-v /var/run/docker.sock:/var/run/docker.sock
</code>```

and to make it easier I would like to add this command in docker compose.

the problem is that the tests run correctly using the command

```<code>docker run -v /var/run/docker.sock:/var/run/docker.sock -ti rabbitmq-dotnet-app-tests
</code>```

but it gives the following error using docker-compose

rabbitmq-dotnet-app-tests-1  |   Failed
tests.DummyTests.RabbitMqTest1.test1 [1 ms]
rabbitmq-dotnet-app-tests-1  |   Error Message:
rabbitmq-dotnet-app-tests-1  |    System.AggregateException : One or
more errors occurred. (One or more errors occurred. (Initialization
has been cancelled.)) (The following constructor parameters did not
have matching fixture data: RabbitMqFixture rabbitMqFixture)
rabbitmq-dotnet-app-tests-1  | ---- System.AggregateException : One or
more errors occurred. (Initialization has been cancelled.)
rabbitmq-dotnet-app-tests-1  | --------
DotNet.Testcontainers.Containers.ResourceReaperException :
Initialization has been cancelled. rabbitmq-dotnet-app-tests-1  | ----
The following constructor parameters did not have matching fixture
data: RabbitMqFixture rabbitMqFixture

my docker compose file

```<code>version: "3.8"

services:
  app-tests:
    image: rabbitmq-dotnet-app-tests
    build:
      context: .
      dockerfile: Dockerfile.Tests
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
</code>```

here is the github link of this application

Im using docker desktop for windows and the test connectionstring is here

Body:
I created tests for my application using docker inside the dotnet tests. It pulls an image from rabbitmq and starts it before testing and it works fine.

Now I'm trying to add these tests to docker, but to run docker inside a container I'm using volumes in docker.sock to transmit the commands to the host machine.

-v /var/run/docker.sock:/var/run/docker.sock

and to make it easier I would like to add this command in docker compose.

the problem is that the tests run correctly using the command

docker run -v /var/run/docker.sock:/var/run/docker.sock -ti rabbitmq-dotnet-app-tests

but it gives the following error using docker-compose

rabbitmq-dotnet-app-tests-1  |   Failed
tests.DummyTests.RabbitMqTest1.test1 [1 ms]
rabbitmq-dotnet-app-tests-1  |   Error Message:
rabbitmq-dotnet-app-tests-1  |    System.AggregateException : One or
more errors occurred. (One or more errors occurred. (Initialization
has been cancelled.)) (The following constructor parameters did not
have matching fixture data: RabbitMqFixture rabbitMqFixture)
rabbitmq-dotnet-app-tests-1  | ---- System.AggregateException : One or
more errors occurred. (Initialization has been cancelled.)
rabbitmq-dotnet-app-tests-1  | --------
DotNet.Testcontainers.Containers.ResourceReaperException :
Initialization has been cancelled. rabbitmq-dotnet-app-tests-1  | ----
The following constructor parameters did not have matching fixture
data: RabbitMqFixture rabbitMqFixture

my docker compose file

version: "3.8"

services:
  app-tests:
    image: rabbitmq-dotnet-app-tests
    build:
      context: .
      dockerfile: Dockerfile.Tests
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

here is the github link of this application

Im using docker desktop for windows and the test connectionstring is here


问:
"SSL connection error: protocol version mismatch QMYSQL: Unable to connect"
my Qt application, when running on Windows, returns the title error when connecting to a remote MySql database on my server. This does not happen when compiled for Linux. The application uses ssl certificates to login to the database. Seems that the problem started few weeks ago when on my archlinux server openssl updated from 1.1.1.q to 3.0.7. I tried to downgrade the installation to a date prior to new openssl release and my application works again in Windows too. But I would prefer keep the server update.

Can anyone give me some clue about the problem? If needed I can give more info about server settings.

Very thanks


问:
Receiving null values in entity in my web api in POST, PATCH, PUT
I am send in a request from postman, this is my body and header

But when I check my API the values are null.

Can someone tell me what I am doing wrong here. This is started happening after I added Microsoft.AspNetCore.JsonPatch and NewtonsoftJson libraries. I am getting the same null values in PUT and PATCH as well.


问:
Build docker image - submodules not working
I am trying to create a docker image for my .net core based application and a build is working fine with blow command where I pull the submodule but as soon as I try to build the docker image on GitHub actions, it always fail with this error. Strangely when my developer tried to create a docker image in local( where submodule is a local folder of that app), it worked

Folder strcucture

```<code>UseManagementAPI
--user.API
--user.Application
--user.Domain
--user.Grpc
--user.Infrastructure
--Buildingbock-Submodule

Error
fatal: not a git repository (or any of the parent directories): .git
</code>```

I have even tried to enter below line of code in my docker file

```<code>RUN mkdir -p $HOME/.ssh
RUN echo '${{ secrets.CAT_KEY }}' > $HOME/.ssh/ssh.key
RUN chmod 600 $HOME/.ssh/ssh.key
RUN export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/ssh.key"
RUN git submodule set-url BuildingBlocks-SubModule git@github.com:Oranization/BuildingBlocks-SubModule.git
#RUN git submodule update --init --recursive
#RUN git submodule set-url BuildingBlocks-SubModule
RUN git submodule init && git submodule update
https://github.com/Oranization/BuildingBlocks-SubModule.git
</code>```

Tried few combination on above line...

I also tried to follow other stackoverflow links but no luck so far

Body:
I am trying to create a docker image for my .net core based application and a build is working fine with blow command where I pull the submodule but as soon as I try to build the docker image on GitHub actions, it always fail with this error. Strangely when my developer tried to create a docker image in local( where submodule is a local folder of that app), it worked

Folder strcucture

UseManagementAPI
--user.API
--user.Application
--user.Domain
--user.Grpc
--user.Infrastructure
--Buildingbock-Submodule

Error
fatal: not a git repository (or any of the parent directories): .git

I have even tried to enter below line of code in my docker file

RUN mkdir -p $HOME/.ssh
RUN echo '${{ secrets.CAT_KEY }}' > $HOME/.ssh/ssh.key
RUN chmod 600 $HOME/.ssh/ssh.key
RUN export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/ssh.key"
RUN git submodule set-url BuildingBlocks-SubModule git@github.com:Oranization/BuildingBlocks-SubModule.git
#RUN git submodule update --init --recursive
#RUN git submodule set-url BuildingBlocks-SubModule
RUN git submodule init && git submodule update
https://github.com/Oranization/BuildingBlocks-SubModule.git

Tried few combination on above line...

I also tried to follow other stackoverflow links but no luck so far


问:
How do I move the project tab to the left or right side of the editor window in IntelliJ IDEA, and how can I show tabs in the Distraction-free mode?
Almost every time I use distraction free mode on Intellij, but when I open project tab it's open always left side and it is distractive. So I want to move it left to right permanently.Example:
Also is there is any way to show tabs in Distraction-free mode? It will me helpful for me. Example:


问:
JavaFx - Kotlin - How to get Item value from ListView?
So I have a basic "app", basically all it does it loads users from a cvs files.

Now I am dysplaing these user onto a ListView. However I can't figure out how to get the value (The users are stored as Strings in the ListView) and either print it in the console or do something else with it.

So this Is my Code for storing the users. It just saves the User string into a mutableList and adds it to the ListView.

```<code>fun addUsser(name: String, age: Int, date: LocalDate) {
    val user= Uzivatel(name, age, date);
    userList.add(user);

    usersListView.items.add(0, user.toString());
}
</code>```

I had tried using usersListView.selectionMode and usersListView.selectionMode.selectedItem etc.. however I can't get it to work

Body:
So I have a basic "app", basically all it does it loads users from a cvs files.

Now I am dysplaing these user onto a ListView. However I can't figure out how to get the value (The users are stored as Strings in the ListView) and either print it in the console or do something else with it.

So this Is my Code for storing the users. It just saves the User string into a mutableList and adds it to the ListView.

fun addUsser(name: String, age: Int, date: LocalDate) {
    val user= Uzivatel(name, age, date);
    userList.add(user);

    usersListView.items.add(0, user.toString());
}

I had tried using usersListView.selectionMode and usersListView.selectionMode.selectedItem etc.. however I can't get it to work


问:
How to read excel bottom up in python
How can I read excel rows from bottom up.

Reading them top to bottom with the following code has no problem at all

```<code>for row in range(2, ws.max_row+1):
            print(ws.cell(row, 1).value)
</code>```

But doing for loop in reverse doesn't print a thing. Is there anything wrong with the below code?

```<code>for row in range(ws.max_row, 1):
            print(ws.cell(row, 1).value)
            row -= 1
</code>```

Appreciate any help, newbie here..

Title: How to read excel bottom up in python

Body:
How can I read excel rows from bottom up.

Reading them top to bottom with the following code has no problem at all

for row in range(2, ws.max_row+1):
            print(ws.cell(row, 1).value)

But doing for loop in reverse doesn't print a thing. Is there anything wrong with the below code?

for row in range(ws.max_row, 1):
            print(ws.cell(row, 1).value)
            row -= 1

Appreciate any help, newbie here..


问:
Error 'utf-8' when connecting qiwi payment
I pay via kiwi in telegram, but there is always an error associated with the token.
Tried through different libraries, but this turned out to be the best for payment. Previously found similar questions on other sites, but there were no answers.
Code:

```<code>import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types
import gspread
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.types.message import ContentType

import config
import logging

print(api.balance)
TOKEN = "bot token"

logging.basicConfig(level=logging.INFO)
bot = Bot(token=TOKEN)

dp = Dispatcher(bot, storage=MemoryStorage())
dp.middleware.setup(LoggingMiddleware())

#logging.basicConfig(level=logging.INFO)

@dp.message_handler(commands ='start')
async def start(message: types.Message):

    await message.answer("Hello")

from pyqiwip2p import QiwiP2P
from pyqiwip2p.p2p_types import QiwiCustomer, QiwiDatetime, PaymentMethods

QIWI_PRIV_KEY = "  "

p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY)

# Выставим счет на сумму 228 рублей который будет работать 45 минут
new_bill = p2p.bill(bill_id=212332030, amount=228, lifetime=45)

print(new_bill.bill_id, new_bill.pay_url)

# Проверим статус выставленного счета
print(p2p.check(bill_id=new_bill.bill_id).status)

# Потеряли ссылку на оплату счета? Не проблема!
print(p2p.check(bill_id=245532).pay_url)

# Клиент отменил заказ? Тогда и счет надо закрыть
p2p.reject(bill_id=new_bill.bill_id)

# Если планируете выставлять счета с одинаковой суммой,
# можно воспользоваться параметром default_amount
p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY, default_amount=148)

# Теперь, если не указывать в методе p2p.bill() значение суммы заказа,
# будет применяться указанная базовая сумма
new_bill = p2p.bill(bill_id=6627358)

# А ещё можно не указывать bill_id, тогда значение сгенерируется автоматически.
# Его можно будет посмотреть в объекте ответа Bill
# В комбинации со стандартным значением суммы будет вот так
new_bill = p2p.bill()
print(new_bill.bill_id, new_bill.pay_url)

# Чтобы запретить приём платежей через какой-то метод оплаты, например, карты,
# необходимо передать paySourcesFilter в fields. Туда же можно передать themeCode

fields = {
    "paySourcesFilter": "qw,card",
    "themeCode": "MalchikGay",
}
p2p.bill(fields=fields)

# Либо же воспользоваться удобными полями

p2p.bill(pay_sources=[PaymentMethods.qiwi, PaymentMethods.card])
p2p.bill(pay_sources=[PaymentMethods.qiwi], theme_code="MalchikGay")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)
</code>```

Example code taken from the Internet. The error is on the qiwi token

```<code>  File "register_schoolcain_bot.py", line 70, in <module>
    p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY)
  File "C:\Users\nmash\AppData\Local\Programs\Python\Python38\lib\site-packages\pyqiwip2p\Qiwip2p.py", line 42, in __init__
    self.validate_privkey(auth_key)
  File "C:\Users\nmash\AppData\Local\Programs\Python\Python38\lib\site-packages\pyqiwip2p\Qiwip2p.py", line 94, in validate_privkey
    key_decoded = b64decode(privkey).decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xeb in position 0: invalid continuation byte
</code>```

Tried several ways to fix it, googled, but still no answer to my question.

Body:
I pay via kiwi in telegram, but there is always an error associated with the token.
Tried through different libraries, but this turned out to be the best for payment. Previously found similar questions on other sites, but there were no answers.
Code:

import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types
import gspread
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.types.message import ContentType

import config
import logging

print(api.balance)
TOKEN = "bot token"

logging.basicConfig(level=logging.INFO)
bot = Bot(token=TOKEN)

dp = Dispatcher(bot, storage=MemoryStorage())
dp.middleware.setup(LoggingMiddleware())

#logging.basicConfig(level=logging.INFO)

@dp.message_handler(commands ='start')
async def start(message: types.Message):

    await message.answer("Hello")

from pyqiwip2p import QiwiP2P
from pyqiwip2p.p2p_types import QiwiCustomer, QiwiDatetime, PaymentMethods

QIWI_PRIV_KEY = "  "

p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY)

# Выставим счет на сумму 228 рублей который будет работать 45 минут
new_bill = p2p.bill(bill_id=212332030, amount=228, lifetime=45)

print(new_bill.bill_id, new_bill.pay_url)

# Проверим статус выставленного счета
print(p2p.check(bill_id=new_bill.bill_id).status)

# Потеряли ссылку на оплату счета? Не проблема!
print(p2p.check(bill_id=245532).pay_url)

# Клиент отменил заказ? Тогда и счет надо закрыть
p2p.reject(bill_id=new_bill.bill_id)

# Если планируете выставлять счета с одинаковой суммой,
# можно воспользоваться параметром default_amount
p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY, default_amount=148)

# Теперь, если не указывать в методе p2p.bill() значение суммы заказа,
# будет применяться указанная базовая сумма
new_bill = p2p.bill(bill_id=6627358)

# А ещё можно не указывать bill_id, тогда значение сгенерируется автоматически.
# Его можно будет посмотреть в объекте ответа Bill
# В комбинации со стандартным значением суммы будет вот так
new_bill = p2p.bill()
print(new_bill.bill_id, new_bill.pay_url)

# Чтобы запретить приём платежей через какой-то метод оплаты, например, карты,
# необходимо передать paySourcesFilter в fields. Туда же можно передать themeCode

fields = {
    "paySourcesFilter": "qw,card",
    "themeCode": "MalchikGay",
}
p2p.bill(fields=fields)

# Либо же воспользоваться удобными полями

p2p.bill(pay_sources=[PaymentMethods.qiwi, PaymentMethods.card])
p2p.bill(pay_sources=[PaymentMethods.qiwi], theme_code="MalchikGay")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

Example code taken from the Internet. The error is on the qiwi token

  File "register_schoolcain_bot.py", line 70, in <module>
    p2p = QiwiP2P(auth_key=QIWI_PRIV_KEY)
  File "C:\Users\nmash\AppData\Local\Programs\Python\Python38\lib\site-packages\pyqiwip2p\Qiwip2p.py", line 42, in __init__
    self.validate_privkey(auth_key)
  File "C:\Users\nmash\AppData\Local\Programs\Python\Python38\lib\site-packages\pyqiwip2p\Qiwip2p.py", line 94, in validate_privkey
    key_decoded = b64decode(privkey).decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xeb in position 0: invalid continuation byte

Tried several ways to fix it, googled, but still no answer to my question.


问:
Why is the model I am trying to use not working?

I keep getting an error when I enter this code. I even returned to the original csv, replaced the spaces in the headings with underscores (ex: "Property_Damage"),and the code still did not work. I'm not sure what I am doing wrong.

I've tried eliminating the spaces in my headings.


问:
CA1416: Validate platform compatibility in Resource.Image.Save
I'm using dotnet 7.0

I have an image in my resources, and I want to convert it to byte array in all platforms.
I wrote the following:

```<code> await using var memoryStream = new MemoryStream();
 Resources.user_image_default.Save(memoryStream, ImageFormat.Png); // CA1416: Validate platform compatibility
</code>```

But it has a warning that compiles just for windows.

How can I fix it to work in all platforms?

P.S:

I also installed SixLabors.ImageSharp.Drawing package in my project.

Body:
I'm using dotnet 7.0

I have an image in my resources, and I want to convert it to byte array in all platforms.
I wrote the following:

 await using var memoryStream = new MemoryStream();
 Resources.user_image_default.Save(memoryStream, ImageFormat.Png); // CA1416: Validate platform compatibility

But it has a warning that compiles just for windows.

How can I fix it to work in all platforms?

P.S:

I also installed SixLabors.ImageSharp.Drawing package in my project.


问:
export data tabular from scanned pdf to excell
i have a data tabular scanned pdf file consist of 20 pages. and I want to take export excell with python

export data tabular from scanned pdf to excell


问:
Cannot read the array length because "this.runs" is null
I am writing a simple console program for Minecraft in javaFX. Sometimes it works fine but sometimes when the console is updating ill randomly get spammed with this error:

```<code>Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.runs" is null
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.addTextRun(PrismTextLayout.java:770)
    at javafx.graphics@18.0.1/com.sun.javafx.text.GlyphLayout.addTextRun(GlyphLayout.java:140)
    at javafx.graphics@18.0.1/com.sun.javafx.text.GlyphLayout.breakRuns(GlyphLayout.java:210)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.buildRuns(PrismTextLayout.java:785)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1036)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
    at javafx.graphics@18.0.1/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
    at javafx.graphics@18.0.1/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
    at javafx.graphics@18.0.1/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
    at javafx.graphics@18.0.1/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
    at javafx.graphics@18.0.1/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:116)
    at javafx.graphics@18.0.1/javafx.scene.Node.updateGeomBounds(Node.java:3818)
    at javafx.graphics@18.0.1/javafx.scene.Node.getGeomBounds(Node.java:3780)
    at javafx.graphics@18.0.1/javafx.scene.Node.getLocalBounds(Node.java:3728)
    at javafx.graphics@18.0.1/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6818)
    at javafx.graphics@18.0.1/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9712)
    at javafx.graphics@18.0.1/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9682)
    at javafx.graphics@18.0.1/javafx.scene.Node.getBoundsInLocal(Node.java:3408)
    at javafx.controls@18.0.1/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1207)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Scene.doLayoutPass(Scene.java:579)
    at javafx.graphics@18.0.1/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2499)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:405)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:404)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:434)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
    at javafx.graphics@18.0.1/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@18.0.1/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@18.0.1/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

The error message is not even remotely helpful and I cant figure out whats triggering the error. If anyone knows what triggers this error please let me know so I can fix it. Thanks.

Edit: Heres my source code

```<code>package com.koolade446.mconsole;

import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class MainController {

    @FXML
    public ComboBox<String> typeBox;
    @FXML
    public ComboBox<String> versionBox;
    @FXML
    public TextArea console;
    @FXML
    public Button startStopButton;
    @FXML
    public Button killButton;
    @FXML
    Button changeVersionButton;
    @FXML
    Label pathContainer;
    @FXML
    TextField commandBox;

    private final Map<String, List<String>> typeMap = new HashMap<>();

    private boolean serverIsStarted = false;
    private ExecutorService executorService;

    private Path directoryPath = Path.of(new File(".").getCanonicalPath());
    private final String[] endpoints = new String[]{
            "servers/spigot",
            "vanilla/vanilla",
            "vanilla/snapshot",
            "modded/forge",
            "modded/fabric"
    };
    File serverJar = new File(directoryPath + "/server.jar");
    private PrintWriter outputStreamWriter = null;

    public MainController() throws IOException {
    }

    public void initialize() throws IOException, URISyntaxException {

        startStopButton.setStyle("-fx-background-image: url('power.png')");
        killButton.setStyle("-fx-background-image: url('kill.png')");
        pathContainer.setText(directoryPath.toString());

        Platform.runLater(() -> {
            try {
                for (String endpoint : endpoints) {
                    List<String> l = new ArrayList<>();
                    URL url = new URL("https://serverjars.com/api/fetchAll/" + endpoint);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("GET");
                    con.connect();

                    JSONObject responseJson = new JSONObject(new BufferedReader(new InputStreamReader(con.getInputStream())).lines().collect(Collectors.joining()));

                    con.disconnect();

                    for (Object obj : responseJson.getJSONArray("response")) {
                        JSONObject jsonObject = (JSONObject) obj;
                        l.add(jsonObject.getString("version"));
                    }
                    typeMap.put(endpoint.split("/")[1].replace("/", ""), l);
                }
                typeBox.getItems().addAll(typeMap.keySet());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void changeVersionOptions() {
        versionBox.getItems().clear();
        versionBox.setValue(null);
        versionBox.getItems().addAll(typeMap.get(typeBox.getValue()));
    }

    public void updateVersion(ActionEvent actionEvent) throws MalformedURLException {
        printToConsole("INFO", "Attempting to update to " + typeBox.getValue() + " " + versionBox.getValue());
        Platform.runLater(() -> {
            try {
                URL url = new URL("https://serverjars.com/api/fetchJar/" + endpoints[getClosestIndex(endpoints, typeBox.getValue())] + "/" + versionBox.getValue());
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                printToConsole("INFO", "Connecting to servers...");
                con.connect();

                printToConsole("INFO", "Downloading new jar file...");
                InputStream is = con.getInputStream();
                FileOutputStream fos = new FileOutputStream(serverJar);

                printToConsole("INFO", "Writing new jar file...");
                byte[] jarFileData = is.readAllBytes();

                System.out.println(serverJar.getPath());

                fos.write(jarFileData, 0, jarFileData.length);

                is.close();
                fos.close();
                con.disconnect();

                printToConsole("INFO", "Version successfully updated!");
            } catch (Exception e) {
                printToConsole("ERROR", "Error when updating version. Please make sure you select a type and version");
                e.printStackTrace();
            }
        });
    }

    public void changeFolder(ActionEvent event) throws IOException {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("Select minecraft server folder");
        File file = directoryChooser.showDialog(null);

        directoryPath = Path.of(file.getCanonicalPath());
        pathContainer.setText(directoryPath.toString());
        serverJar = new File(directoryPath + "/server.jar");
    }

    private int getClosestIndex(String[] array, String option) throws Exception {
        int index = -1;
        for (String str : array) {
            index++;
            if (str.contains(option)) return index;
        }
        return 0;
    }

    private void printToConsole(String sender, String message) {
        console.appendText(String.format(
                "[%s] %s\n",
                sender,
                message
        ));
    }

    public void togglePowerState(ActionEvent actionEvent) {
        if (executorService == null || executorService.isTerminated()) {
            //This is the bit that I think is causing it but idk how or how to fix it
            Task<Boolean> runnable = new Task() {
                @Override
                protected Boolean call() {
                    try {
                        Process process;
                        ProcessBuilder pb = new ProcessBuilder("java", "-jar", "-Xmx5G", "-Xms1G", "server.jar", "nogui");
                        pb.directory(new File(directoryPath.toString()));
                        process = pb.start();
                        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                        setOutputStreamWriter(new PrintWriter(process.getOutputStream()));
                        String line;
                        while (process.isAlive()) {
                            if ((line = br.readLine()) != null) {
                                printToConsole("MINECRAFT", line);
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return true;
                }
            };

            executorService = Executors.newFixedThreadPool(1);
            executorService.execute(runnable);
            executorService.shutdown();

        } else if (!executorService.isTerminated()) {
            outputStreamWriter.println("stop");
            outputStreamWriter.flush();
        }
    }

    public void killServer(ActionEvent actionEvent) {
        if (!executorService.isTerminated()) executorService.shutdownNow();
    }

    public void sendCommand(ActionEvent event) throws IOException {
        outputStreamWriter.println(commandBox.getText());
        outputStreamWriter.flush();
        commandBox.setText("");
    }

    public void onKeyPress(KeyEvent keyEvent) throws IOException {
        if (keyEvent.getCode().equals(KeyCode.ENTER)) {
            outputStreamWriter.println(commandBox.getText());
            outputStreamWriter.flush();
            commandBox.setText("");
        }
    }

    public void setOutputStreamWriter(PrintWriter outputStreamWriter) {
        this.outputStreamWriter = outputStreamWriter;
    }
}
</code>```

Body:
I am writing a simple console program for Minecraft in javaFX. Sometimes it works fine but sometimes when the console is updating ill randomly get spammed with this error:

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.runs" is null
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.addTextRun(PrismTextLayout.java:770)
    at javafx.graphics@18.0.1/com.sun.javafx.text.GlyphLayout.addTextRun(GlyphLayout.java:140)
    at javafx.graphics@18.0.1/com.sun.javafx.text.GlyphLayout.breakRuns(GlyphLayout.java:210)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.buildRuns(PrismTextLayout.java:785)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1036)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
    at javafx.graphics@18.0.1/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
    at javafx.graphics@18.0.1/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
    at javafx.graphics@18.0.1/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
    at javafx.graphics@18.0.1/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
    at javafx.graphics@18.0.1/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
    at javafx.graphics@18.0.1/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:116)
    at javafx.graphics@18.0.1/javafx.scene.Node.updateGeomBounds(Node.java:3818)
    at javafx.graphics@18.0.1/javafx.scene.Node.getGeomBounds(Node.java:3780)
    at javafx.graphics@18.0.1/javafx.scene.Node.getLocalBounds(Node.java:3728)
    at javafx.graphics@18.0.1/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6818)
    at javafx.graphics@18.0.1/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9712)
    at javafx.graphics@18.0.1/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9682)
    at javafx.graphics@18.0.1/javafx.scene.Node.getBoundsInLocal(Node.java:3408)
    at javafx.controls@18.0.1/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1207)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@18.0.1/javafx.scene.Scene.doLayoutPass(Scene.java:579)
    at javafx.graphics@18.0.1/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2499)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:405)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:404)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:434)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
    at javafx.graphics@18.0.1/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
    at javafx.graphics@18.0.1/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@18.0.1/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@18.0.1/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:833)

The error message is not even remotely helpful and I cant figure out whats triggering the error. If anyone knows what triggers this error please let me know so I can fix it. Thanks.

Edit: Heres my source code

package com.koolade446.mconsole;

import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class MainController {

    @FXML
    public ComboBox<String> typeBox;
    @FXML
    public ComboBox<String> versionBox;
    @FXML
    public TextArea console;
    @FXML
    public Button startStopButton;
    @FXML
    public Button killButton;
    @FXML
    Button changeVersionButton;
    @FXML
    Label pathContainer;
    @FXML
    TextField commandBox;

    private final Map<String, List<String>> typeMap = new HashMap<>();

    private boolean serverIsStarted = false;
    private ExecutorService executorService;

    private Path directoryPath = Path.of(new File(".").getCanonicalPath());
    private final String[] endpoints = new String[]{
            "servers/spigot",
            "vanilla/vanilla",
            "vanilla/snapshot",
            "modded/forge",
            "modded/fabric"
    };
    File serverJar = new File(directoryPath + "/server.jar");
    private PrintWriter outputStreamWriter = null;

    public MainController() throws IOException {
    }

    public void initialize() throws IOException, URISyntaxException {

        startStopButton.setStyle("-fx-background-image: url('power.png')");
        killButton.setStyle("-fx-background-image: url('kill.png')");
        pathContainer.setText(directoryPath.toString());

        Platform.runLater(() -> {
            try {
                for (String endpoint : endpoints) {
                    List<String> l = new ArrayList<>();
                    URL url = new URL("https://serverjars.com/api/fetchAll/" + endpoint);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod("GET");
                    con.connect();

                    JSONObject responseJson = new JSONObject(new BufferedReader(new InputStreamReader(con.getInputStream())).lines().collect(Collectors.joining()));

                    con.disconnect();

                    for (Object obj : responseJson.getJSONArray("response")) {
                        JSONObject jsonObject = (JSONObject) obj;
                        l.add(jsonObject.getString("version"));
                    }
                    typeMap.put(endpoint.split("/")[1].replace("/", ""), l);
                }
                typeBox.getItems().addAll(typeMap.keySet());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void changeVersionOptions() {
        versionBox.getItems().clear();
        versionBox.setValue(null);
        versionBox.getItems().addAll(typeMap.get(typeBox.getValue()));
    }

    public void updateVersion(ActionEvent actionEvent) throws MalformedURLException {
        printToConsole("INFO", "Attempting to update to " + typeBox.getValue() + " " + versionBox.getValue());
        Platform.runLater(() -> {
            try {
                URL url = new URL("https://serverjars.com/api/fetchJar/" + endpoints[getClosestIndex(endpoints, typeBox.getValue())] + "/" + versionBox.getValue());
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                printToConsole("INFO", "Connecting to servers...");
                con.connect();

                printToConsole("INFO", "Downloading new jar file...");
                InputStream is = con.getInputStream();
                FileOutputStream fos = new FileOutputStream(serverJar);

                printToConsole("INFO", "Writing new jar file...");
                byte[] jarFileData = is.readAllBytes();

                System.out.println(serverJar.getPath());

                fos.write(jarFileData, 0, jarFileData.length);

                is.close();
                fos.close();
                con.disconnect();

                printToConsole("INFO", "Version successfully updated!");
            } catch (Exception e) {
                printToConsole("ERROR", "Error when updating version. Please make sure you select a type and version");
                e.printStackTrace();
            }
        });
    }

    public void changeFolder(ActionEvent event) throws IOException {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("Select minecraft server folder");
        File file = directoryChooser.showDialog(null);

        directoryPath = Path.of(file.getCanonicalPath());
        pathContainer.setText(directoryPath.toString());
        serverJar = new File(directoryPath + "/server.jar");
    }

    private int getClosestIndex(String[] array, String option) throws Exception {
        int index = -1;
        for (String str : array) {
            index++;
            if (str.contains(option)) return index;
        }
        return 0;
    }

    private void printToConsole(String sender, String message) {
        console.appendText(String.format(
                "[%s] %s\n",
                sender,
                message
        ));
    }

    public void togglePowerState(ActionEvent actionEvent) {
        if (executorService == null || executorService.isTerminated()) {
            //This is the bit that I think is causing it but idk how or how to fix it
            Task<Boolean> runnable = new Task() {
                @Override
                protected Boolean call() {
                    try {
                        Process process;
                        ProcessBuilder pb = new ProcessBuilder("java", "-jar", "-Xmx5G", "-Xms1G", "server.jar", "nogui");
                        pb.directory(new File(directoryPath.toString()));
                        process = pb.start();
                        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                        setOutputStreamWriter(new PrintWriter(process.getOutputStream()));
                        String line;
                        while (process.isAlive()) {
                            if ((line = br.readLine()) != null) {
                                printToConsole("MINECRAFT", line);
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return true;
                }
            };

            executorService = Executors.newFixedThreadPool(1);
            executorService.execute(runnable);
            executorService.shutdown();

        } else if (!executorService.isTerminated()) {
            outputStreamWriter.println("stop");
            outputStreamWriter.flush();
        }
    }

    public void killServer(ActionEvent actionEvent) {
        if (!executorService.isTerminated()) executorService.shutdownNow();
    }

    public void sendCommand(ActionEvent event) throws IOException {
        outputStreamWriter.println(commandBox.getText());
        outputStreamWriter.flush();
        commandBox.setText("");
    }

    public void onKeyPress(KeyEvent keyEvent) throws IOException {
        if (keyEvent.getCode().equals(KeyCode.ENTER)) {
            outputStreamWriter.println(commandBox.getText());
            outputStreamWriter.flush();
            commandBox.setText("");
        }
    }

    public void setOutputStreamWriter(PrintWriter outputStreamWriter) {
        this.outputStreamWriter = outputStreamWriter;
    }
}


问:
How can I Insert a graph into a .pdf report?
I want to create a .pdf with one table and with a graph already created in the previous step

Code to create the graph:

```<code>    #Quality control chart
    #Create the data plot
    CC1=plt.plot(Obs1, color='black',marker='o')
    #Add title and labels
    CC1=plt.title('Quality control chart')
    CC1=plt.xlabel('Sample number')
    CC1=plt.ylabel('Measurement')
    #Add the control limits
    CC1=plt.axhline(y=USL, color='r', linestyle='--')
    CC1=plt.axhline(y=LSL, color='r', linestyle='--')
    CC1=plt.axhline(y=Target, color='b', linestyle='-')
    plt.show(CC1)
</code>```

Code to create the pdf output, I am trying to use reportlab with the following command line:

```<code>    !pip install reportlab
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Image
    from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
    from reportlab.graphics.charts.lineplots import linePlot
    from reportlab.graphics.widgets.markers import makeMarker

    #Create the PDF document
    doc=SimpleDocTemplate("Output.pdf",pagesize=letter)

    #Create the data
    data=[
        ['Target',Target],
        ['Media',sample_mean1],
    ]

    #Create the table
          table = Table(data)
    #Set the table style
    style=TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.lightgrey),
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
    ])
    table.setStyle(style)

    #Add the table
    elements=[table,CC1]
    doc.build(elements)
</code>```

I am able to create the pdf with the table, but I have an error when I try to insert the CC1 chart into the pdf.

Where is my error?
Can you help me?

Body:
I want to create a .pdf with one table and with a graph already created in the previous step

Code to create the graph:

    #Quality control chart
    #Create the data plot
    CC1=plt.plot(Obs1, color='black',marker='o')
    #Add title and labels
    CC1=plt.title('Quality control chart')
    CC1=plt.xlabel('Sample number')
    CC1=plt.ylabel('Measurement')
    #Add the control limits
    CC1=plt.axhline(y=USL, color='r', linestyle='--')
    CC1=plt.axhline(y=LSL, color='r', linestyle='--')
    CC1=plt.axhline(y=Target, color='b', linestyle='-')
    plt.show(CC1)

Code to create the pdf output, I am trying to use reportlab with the following command line:

    !pip install reportlab
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Image
    from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
    from reportlab.graphics.charts.lineplots import linePlot
    from reportlab.graphics.widgets.markers import makeMarker

    #Create the PDF document
    doc=SimpleDocTemplate("Output.pdf",pagesize=letter)

    #Create the data
    data=[
        ['Target',Target],
        ['Media',sample_mean1],
    ]

    #Create the table
          table = Table(data)
    #Set the table style
    style=TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.lightgrey),
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
    ])
    table.setStyle(style)

    #Add the table
    elements=[table,CC1]
    doc.build(elements)

I am able to create the pdf with the table, but I have an error when I try to insert the CC1 chart into the pdf.

Where is my error?
Can you help me?


问:
What kind of commands are given to a device by a controller that every game works the way the controler is maped
I want to know that when you plug a usb controller into your pc then what kind of signals or command is given to the device that the game responds the same way with different controller and controller works the same way with many games

How can I make such commands via my laptop or phone wirelessly which I can use to make a full fletched wireless controller via python


问:
How can I export my "message error log" detail to CSV file?
How can I CSV export my error log (https://console.twilio.com/us1/monitor/logs/debugger/errors)?

I can view the log of individual message errors on the screen, but would like to export the details...


问:
Query HTML with -Com "HTMLFile"
I have this code to get all the DIVs based on a CSS selector:

```<code>param(
    [string]$File
)

# Read the HTML file
$htmlFile = Get-Content -Path $File -Raw

$html = New-Object -Com "HTMLFile"

try
{
    # This works in PowerShell 4
    $html.IHTMLDocument2_write($htmlFile)
}
catch
{
    # This works in PowerShell 5
    $html.write($htmlFile)
}

# Select all DIV elements that match the XPath expression
$divElements = $html.querySelectorAll("body > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > main:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)")

</code>```

The problem is the querySelectorAll method is not available for the $html object.

What's the next possible option to get all the DIVs without using third-party modules to install with Powershell?

Title: Query HTML with -Com "HTMLFile"

Body:
I have this code to get all the DIVs based on a CSS selector:

param(
    [string]$File
)

# Read the HTML file
$htmlFile = Get-Content -Path $File -Raw

$html = New-Object -Com "HTMLFile"

try
{
    # This works in PowerShell 4
    $html.IHTMLDocument2_write($htmlFile)
}
catch
{
    # This works in PowerShell 5
    $html.write($htmlFile)
}

# Select all DIV elements that match the XPath expression
$divElements = $html.querySelectorAll("body > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > main:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)")

The problem is the querySelectorAll method is not available for the $html object.

What's the next possible option to get all the DIVs without using third-party modules to install with Powershell?


问:
Error creating 3 different graphics in the same png file using gnuplot and java.lang.Runtime and without any Library
```<code>public static void main(String[] args) throws IOException, InterruptedException {
        // Set up the gnuplot command and arguments
        String[] cmd = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; plot 'graficoS.txt' using 1:2 with lines"};
        String[] cmd2 = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; replot 'graficoI.txt' using 1:3 with lines"};
        String[] cmd3 = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; replot 'graficoR.txt' using 1:4 with lines"};

        // Start the processes
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        Process process2 = Runtime.getRuntime().exec(cmd2);
        process2.waitFor();
        Process process3 = Runtime.getRuntime().exec(cmd3);
        process3.waitFor();

        // Read the output from the processes
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
</code>```

Not showing nothing on the png file , even the gnuplot graphic.
In different png files its working , but in the same it isn't.

Body:
public static void main(String[] args) throws IOException, InterruptedException {
        // Set up the gnuplot command and arguments
        String[] cmd = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; plot 'graficoS.txt' using 1:2 with lines"};
        String[] cmd2 = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; replot 'graficoI.txt' using 1:3 with lines"};
        String[] cmd3 = {"gnuplot", "-e", "set terminal png; set output 'plotS.png'; replot 'graficoR.txt' using 1:4 with lines"};

        // Start the processes
        Process process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        Process process2 = Runtime.getRuntime().exec(cmd2);
        process2.waitFor();
        Process process3 = Runtime.getRuntime().exec(cmd3);
        process3.waitFor();

        // Read the output from the processes
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();

Not showing nothing on the png file , even the gnuplot graphic.
In different png files its working , but in the same it isn't.


问:
Slicing wavefront file for different rendering scenarios
I am super new to play around with 3D objects. My goal is to put a glass (OBJ_Glass.obj) on a canonical face (canonical_face_model.obj) provided by mediapipe. I am using python for accomplishing the task. I have successfully appended the glass on the face but still struggling with some issues

I am unable to figure out

How to divide obj.faces for different rendering scenarios.

How to use the canonical face as an occluder to hide glass arms behind facial points.

Thanks for any suggestions.


问:
Correlation in Python DataFrame - What I’m doing wrong? (beginning)
I have two columns in data frame with numerical variables. To check correlation between them I created separate dataframe and checked correlation.

Result is: - 0.258, so Pearson’s correlation coefficient is saying there is weak negative link but scatterplot is saying opposite ? That’s correct?

I just created DataFrame to check correlation and plotted scatterplot

```<code>df2=df[['D','H']]
df2.corr(method='pearson')
df2.plot.scatter('H','D')
</code>```

Body:
I have two columns in data frame with numerical variables. To check correlation between them I created separate dataframe and checked correlation.

Result is: - 0.258, so Pearson’s correlation coefficient is saying there is weak negative link but scatterplot is saying opposite ? That’s correct?

I just created DataFrame to check correlation and plotted scatterplot

df2=df[['D','H']]
df2.corr(method='pearson')
df2.plot.scatter('H','D')


问:
How to pin the location and save?
I want to pin the seller location. Then, save the location, and also, I want to appear the location on the text field. The purpose of my question is because I want to apply the geofencing at user side so that user can get the nearest shop at their location with the radius set.</p>

Title: How to pin the location and save?


问:
How to accept request with selenium in python
Im doing a project for my school project and my project is talking about auto google meet but i stuck when login meeting .The meet wants me to Allowing Camera and Mic access in Chrome 64  .how can i do

here is my code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.by import By
import requests

#your google account
mail_address=''
password=''
mp = ''

options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])

#open google meet
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://accounts.google.com/ServiceLogin?ltmpl=meet&continue=https%3A%2F%2Fmeet.google.com%3Fhs%3D193&')
time.sleep(5)

#deal with account problem and login meeting
Gmail = driver.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(mail_address)
driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button/span').click()
time.sleep(2)
Password = driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password)
driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()
time.sleep(2)
meetpath = driver.find_element(By.XPATH, '//*[@id="i6"]').send_keys(mp)
driver.find_element(By.XPATH, '//*[@id="yDmH0d"]/c-wiz/div/div[2]/div/div[1]/div[3]/div/div[2]/div[2]/button/span').click()
time.sleep(5)

</code>```

i tried to load cookies but i failed
btw i am a programming noob

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

Body:
Im doing a project for my school project and my project is talking about auto google meet but i stuck when login meeting .The meet wants me to Allowing Camera and Mic access in Chrome 64  .how can i do

here is my code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.by import By
import requests

#your google account
mail_address=''
password=''
mp = ''

options = Options()
options.add_experimental_option('excludeSwitches', ['enable-logging'])

#open google meet
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://accounts.google.com/ServiceLogin?ltmpl=meet&continue=https%3A%2F%2Fmeet.google.com%3Fhs%3D193&')
time.sleep(5)

#deal with account problem and login meeting
Gmail = driver.find_element(By.XPATH, '//*[@id="identifierId"]').send_keys(mail_address)
driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button/span').click()
time.sleep(2)
Password = driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password)
driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()
time.sleep(2)
meetpath = driver.find_element(By.XPATH, '//*[@id="i6"]').send_keys(mp)
driver.find_element(By.XPATH, '//*[@id="yDmH0d"]/c-wiz/div/div[2]/div/div[1]/div[3]/div/div[2]/div[2]/button/span').click()
time.sleep(5)

i tried to load cookies but i failed
btw i am a programming noob


问:
SignatureDoesNotMatch when calling PutObject with Django, Django-Storage, AWS S3, boto3
I created a Django App and host it on Heroku where I specified all setting vars such as Access Key ID (see Settings file).

# Amazon S3 Settings
AWS_ACCESS_KEY_ID= config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY_ID= config("AWS_SECRET_ACCESS_KEY_ID")
AWS_STORAGE_BUCKET_NAME= config("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN=f"{AWS_STORAGE_BUCKET_NAME}.s3.us-west-1.amazonaws.com" # this is the default storage class to generate url for storage
AWS_DEFAULT_ACL="public-read"
AWS_S3_OBJECT_PARAMETERS = {
    "CacheControl": "max-age=86400"
}
AWS_LOCATION= "static"  #A path prefix that will be prepended to all uploads
AWS_S3_REGION_NAME = "eu-west-1"
AWS_QUERYSTRING_AUTH=False
AWS_HEADERS={
    "Access-Control-Allow-Origin":"*",
}
DEFAULT_FILE_STORAGE= "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE= "storages.backends.s3boto3.S3StaticStorage"
STATIC_URL= f"https://{AWS_S3_CUSTOM_DOMAIN}/static/"
MEDIA_URL= f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"

# Heroku Logging
DEBUG_PROPAGATE_EXCEPTIONS = True
# Assets Management
ASSETS_ROOT = os.getenv('ASSETS_ROOT', f"https://{AWS_S3_CUSTOM_DOMAIN}/static/assets")
```
<blockquote>
<p>Relevant requirements:</p>
```django-storages==1.12.3
boto3==1.26.31
```
</blockquote>
<p>Anyone any ideas on how to solve this?</p>
<p>I tried the IAM user with full access, only S3 Full access, the Access Keys of the global account and I just keep geeting the error: <strong>"botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when cagettinghe the PutObject operation:  The request signature we calculated does not match the signature you provided. Check your key and signing method."</strong> when trying to upload something to S3. The website then outputs:</p>
<blockquote>
```Internal Server Error

The server encountered an unexpected internal server error

(generated by the waitress)
```
</blockquote>
<p>The logger I added to the settings file on Django is not helpful at all as it just shows me a SignatureDoesNotMatch error.</p>
<p>I tried Access Keys with + and without as this might be the source of the error. I couldn't find any best practices on how to insert the keys to the Heroku settings but a lot of ppl reporting errors when copying the keys from the AWS website. I checked it with the CSV file and the website output.</p>
<p>I tried to add the images through the admin page in case my HTML page is faulty. Same error. The</p>
```
```
<p>the line is added to the HTML page as well. And I save it through</p>
```form.save()
```

on my HTML page.

Body:
I created a Django App and host it on Heroku where I specified all setting vars such as Access Key ID (see Settings file).

# Amazon S3 Settings
AWS_ACCESS_KEY_ID= config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY_ID= config("AWS_SECRET_ACCESS_KEY_ID")
AWS_STORAGE_BUCKET_NAME= config("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN=f"{AWS_STORAGE_BUCKET_NAME}.s3.us-west-1.amazonaws.com" # this is the default storage class to generate url for storage
AWS_DEFAULT_ACL="public-read"
AWS_S3_OBJECT_PARAMETERS = {
    "CacheControl": "max-age=86400"
}
AWS_LOCATION= "static"  #A path prefix that will be prepended to all uploads
AWS_S3_REGION_NAME = "eu-west-1"
AWS_QUERYSTRING_AUTH=False
AWS_HEADERS={
    "Access-Control-Allow-Origin":"*",
}
DEFAULT_FILE_STORAGE= "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE= "storages.backends.s3boto3.S3StaticStorage"
STATIC_URL= f"https://{AWS_S3_CUSTOM_DOMAIN}/static/"
MEDIA_URL= f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"

# Heroku Logging
DEBUG_PROPAGATE_EXCEPTIONS = True
# Assets Management
ASSETS_ROOT = os.getenv('ASSETS_ROOT', f"https://{AWS_S3_CUSTOM_DOMAIN}/static/assets")

Relevant requirements:

django-storages==1.12.3
boto3==1.26.31

Anyone any ideas on how to solve this?

I tried the IAM user with full access, only S3 Full access, the Access Keys of the global account and I just keep geeting the error: "botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when cagettinghe the PutObject operation:  The request signature we calculated does not match the signature you provided. Check your key and signing method." when trying to upload something to S3. The website then outputs:

Internal Server Error

The server encountered an unexpected internal server error

(generated by the waitress)

The logger I added to the settings file on Django is not helpful at all as it just shows me a SignatureDoesNotMatch error.

I tried Access Keys with + and without as this might be the source of the error. I couldn't find any best practices on how to insert the keys to the Heroku settings but a lot of ppl reporting errors when copying the keys from the AWS website. I checked it with the CSV file and the website output.

I tried to add the images through the admin page in case my HTML page is faulty. Same error. The

the line is added to the HTML page as well. And I save it through

form.save()

on my HTML page.


问:
Showing empty PieChart according to interactivity in VueJS
I am implementing the delete method, and when I delete data in my list, it pop that data and send it to my Piechart component. What I want is, when I have a 0 value in my chartData object, just show the empty piechart.

Here is my delete button

<v-btn class="btn" dark md color="error" @click="deleteHandle">
```
<p>DeleteHandle method</p>
<pre class="lang-js prettyprint-override"><code>deleteHandle() {
  this.chartData.labels.pop();
  this.chartData.datasets[0].data.pop();
  this.chartData.datasets[0].backgroundColor.pop();
},
</code>```

And my PieChart.vue component

<template>
  <Pie
    v-if="loaded"
    id="my-chart-id"
    :options="chartOptions"
    :data="chartData"
  />
</template>

```

Body:
I am implementing the delete method, and when I delete data in my list, it pop that data and send it to my Piechart component. What I want is, when I have a 0 value in my chartData object, just show the empty piechart.

Here is my delete button

<v-btn class="btn" dark md color="error" @click="deleteHandle">

DeleteHandle method

deleteHandle() {
  this.chartData.labels.pop();
  this.chartData.datasets[0].data.pop();
  this.chartData.datasets[0].backgroundColor.pop();
},

And my PieChart.vue component

<template>
  <Pie
    v-if="loaded"
    id="my-chart-id"
    :options="chartOptions"
    :data="chartData"
  />
</template>


问:
Find the weakest precondition - Axiomatic Semantics
What exactly is the weakest precondition and how can I find it for a given expression?

Example:

Give the weakest precondition for:

i) WP[x = 5x;](x mod 10 = 0)

ii) WP[x = z - 2;] (x<2)

I tried:

i)
x=0

ii)
z <4

can someone help me please to solve this?


问:
Can IHttpClientFactory working using custom HttpHandler with Typed clients?
I'm learning DI with ASP.Net Core (7.0) and for the best understanding try to develop a simple service.
In my application I scraping a data from one of the sites under a Cloudfare protection. For bypass blocking (429 To many requests) i using a different proxies. For this case I created a couple of a HttpHandler for each proxy and created a new HttpClient per request. Of course it's bad decision.
In many guides and topics give advise to using IHttpClientFactory for implementation.
Now I've simple class InitialService

```<code>

public  class InitialService : IInitialService {

private readonly IHttpClientFactory _httpClientFactory;
public InitialService(IHttpClientFactory httpClientFactory) =>

_httpClientFactory = httpClientFactory;
public async Task <IEnumerable<Cards>> GetAsync()
{

 var _client=_httpClientFactory.CreateClient();
/.../

var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
var response = await httpResponseMessage.Content.ReadAsStringAsync();
}

}
</code>```

In Main() Method of a Program.cs

```<code>
var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddHttpClient<IInitialService>()
    .ConfigurePrimaryHttpMessageHandler(()=> new HttpClientHandler {
        Proxy = new WebProxy ( new Uri("http://"+ProxyIP.IP[rnd.Next(ProxyIP.IP.Length)])){
        Credentials = ( new NetworkCredential {
                    Username="login",
                    Password="pswd"
    })}
});
;
services.AddTransient<InitialService>();

})
.Build();
</code>```

In this case my InitalService:IInitalService dosen't using custom hanlder and send requests without proxies. If I change my service implementation of Typed client AddHttpClient <IInitialService>() to Named client like:

```<code>services.AddHttpClient("proxy")       //in Main()
/.../
 var _client=_httpClientFactory.CreateClient("proxy")     //in InitialService
</code>```

everything is fine. Instance of HttpClient with CreateClient using proxy now. But this
decision doesn't suit me, because every time using a once proxy ip and client working like singleton (probably cause named?).
In case of Typed client - instance doesn't work correctly.
I used this guide. Maybe I don't understood a principle of using DI+IHttpClientFactory or something else, but now I frustrated because can't explain a root of the problem.

So I can't understand in IHttpClientFactory we are can't using custom HttpHandler for instance of HttpClient? A Method CreateClient() doesn't have argument for custom handlers. Only using ConfigurePrimaryHttpMessageHandler(), but I'm not sure, what is correctly.

Body:
I'm learning DI with ASP.Net Core (7.0) and for the best understanding try to develop a simple service.
In my application I scraping a data from one of the sites under a Cloudfare protection. For bypass blocking (429 To many requests) i using a different proxies. For this case I created a couple of a HttpHandler for each proxy and created a new HttpClient per request. Of course it's bad decision.
In many guides and topics give advise to using IHttpClientFactory for implementation.
Now I've simple class InitialService

public  class InitialService : IInitialService {

private readonly IHttpClientFactory _httpClientFactory;
public InitialService(IHttpClientFactory httpClientFactory) =>

_httpClientFactory = httpClientFactory;
public async Task <IEnumerable<Cards>> GetAsync()
{

 var _client=_httpClientFactory.CreateClient();
/.../

var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
var response = await httpResponseMessage.Content.ReadAsStringAsync();
}

}

In Main() Method of a Program.cs

var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddHttpClient<IInitialService>()
    .ConfigurePrimaryHttpMessageHandler(()=> new HttpClientHandler {
        Proxy = new WebProxy ( new Uri("http://"+ProxyIP.IP[rnd.Next(ProxyIP.IP.Length)])){
        Credentials = ( new NetworkCredential {
                    Username="login",
                    Password="pswd"
    })}
});
;
services.AddTransient<InitialService>();

})
.Build();

In this case my InitalService:IInitalService dosen't using custom hanlder and send requests without proxies. If I change my service implementation of Typed client AddHttpClient <IInitialService>() to Named client like:

services.AddHttpClient("proxy")       //in Main()
/.../
 var _client=_httpClientFactory.CreateClient("proxy")     //in InitialService

everything is fine. Instance of HttpClient with CreateClient using proxy now. But this
decision doesn't suit me, because every time using a once proxy ip and client working like singleton (probably cause named?).
In case of Typed client - instance doesn't work correctly.
I used this guide. Maybe I don't understood a principle of using DI+IHttpClientFactory or something else, but now I frustrated because can't explain a root of the problem.

So I can't understand in IHttpClientFactory we are can't using custom HttpHandler for instance of HttpClient? A Method CreateClient() doesn't have argument for custom handlers. Only using ConfigurePrimaryHttpMessageHandler(), but I'm not sure, what is correctly.


问:
Aproblem concerning methylation profiles of gene: how to add gene information below the BSmooth result?
Here is the tutorial (Analyzing WGBS data with bsseq)

I want to use this method to visualize differential dmr regions on the same gene.

Here is my code：

```<code>if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("bsseq")
BiocManager::install("bsseqData")
library(bsseq)
library(bsseqData)

data(BS.cancer.ex.fit)
BS.cancer.ex.fit <- updateObject(BS.cancer.ex.fit)
BS.cancer.ex.fit
class(BS.cancer.ex.fit)

##
data(BS.cancer.ex.fit)
# BS.cancer.ex.fit <- updateObject(BS.cancer.ex.fit)
# BS.cancer.ex.fit
##
BS.cov <- getCoverage(BS.cancer.ex.fit)
keepLoci.ex <- which(rowSums(BS.cov[, BS.cancer.ex$Type == "cancer"] >= 2) >= 2 &
                       rowSums(BS.cov[, BS.cancer.ex$Type == "normal"] >= 2) >= 2)
length(keepLoci.ex)
# [1] 597371
BS.cancer.ex.fit <- BS.cancer.ex.fit[keepLoci.ex,]
length(BS.cancer.ex.fit)
##  (the keepLoci.ex is also available for direct inspection in the bsseqData package.)
##  We are now ready to compute t-statistics, by
BS.cancer.ex.tstat <- BSmooth.tstat(BS.cancer.ex.fit,
                                    group1 = c("C1", "C2", "C3"),
                                    group2 = c("N1", "N2", "N3"),
                                    estimate.var = "group2",
                                    local.correct = TRUE,
                                    verbose = TRUE)
# BS.cancer.ex.tstat
# plot(BS.cancer.ex.tstat)
#####
dmrs0 <- dmrFinder(BS.cancer.ex.tstat, cutoff = c(-4.6, 4.6))
dmrs <- subset(dmrs0, n >= 3 & abs(meanDiff) >= 0.1)
nrow(dmrs)
head(dmrs, n = 3)
######
pData <- pData(BS.cancer.ex.fit)
pData$col <- rep(c("red", "blue"), each = 3)
pData(BS.cancer.ex.fit) <- pData
##  Once this is setup, we can plot a single DMR like
plotRegion(BS.cancer.ex.fit, dmrs[1,], extend = 5000, addRegions = dmrs)
</code>```

I successfully got the figure in the end, but my question is I think a little information is missing on my diagram.

Below is my figure produced by the code above:

The perfect picture below has the gene bar information. I don't know how to add this bar into my plot. Here is the article about this picture (figure 3b).

I don't think the gene bar below the picture is added manually. Because there are other precise information like promoter, exon and methylation regions.

Just like the description in the figure legend:
below plots, gene diagrams, showing gene body (black bars), annotated promoter region (red bar), exons (blue bars), location of individual CpG sites (‘tick marks’) and gene direction (arrow).

I hope somebody could give me some advice or the right way to solve my problem. Very thankful.

Body:
Here is the tutorial (Analyzing WGBS data with bsseq)

I want to use this method to visualize differential dmr regions on the same gene.

Here is my code：

if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("bsseq")
BiocManager::install("bsseqData")
library(bsseq)
library(bsseqData)

data(BS.cancer.ex.fit)
BS.cancer.ex.fit <- updateObject(BS.cancer.ex.fit)
BS.cancer.ex.fit
class(BS.cancer.ex.fit)

##
data(BS.cancer.ex.fit)
# BS.cancer.ex.fit <- updateObject(BS.cancer.ex.fit)
# BS.cancer.ex.fit
##
BS.cov <- getCoverage(BS.cancer.ex.fit)
keepLoci.ex <- which(rowSums(BS.cov[, BS.cancer.ex$Type == "cancer"] >= 2) >= 2 &
                       rowSums(BS.cov[, BS.cancer.ex$Type == "normal"] >= 2) >= 2)
length(keepLoci.ex)
# [1] 597371
BS.cancer.ex.fit <- BS.cancer.ex.fit[keepLoci.ex,]
length(BS.cancer.ex.fit)
##  (the keepLoci.ex is also available for direct inspection in the bsseqData package.)
##  We are now ready to compute t-statistics, by
BS.cancer.ex.tstat <- BSmooth.tstat(BS.cancer.ex.fit,
                                    group1 = c("C1", "C2", "C3"),
                                    group2 = c("N1", "N2", "N3"),
                                    estimate.var = "group2",
                                    local.correct = TRUE,
                                    verbose = TRUE)
# BS.cancer.ex.tstat
# plot(BS.cancer.ex.tstat)
#####
dmrs0 <- dmrFinder(BS.cancer.ex.tstat, cutoff = c(-4.6, 4.6))
dmrs <- subset(dmrs0, n >= 3 & abs(meanDiff) >= 0.1)
nrow(dmrs)
head(dmrs, n = 3)
######
pData <- pData(BS.cancer.ex.fit)
pData$col <- rep(c("red", "blue"), each = 3)
pData(BS.cancer.ex.fit) <- pData
##  Once this is setup, we can plot a single DMR like
plotRegion(BS.cancer.ex.fit, dmrs[1,], extend = 5000, addRegions = dmrs)

I successfully got the figure in the end, but my question is I think a little information is missing on my diagram.

Below is my figure produced by the code above:

The perfect picture below has the gene bar information. I don't know how to add this bar into my plot. Here is the article about this picture (figure 3b).

I don't think the gene bar below the picture is added manually. Because there are other precise information like promoter, exon and methylation regions.

Just like the description in the figure legend:
below plots, gene diagrams, showing gene body (black bars), annotated promoter region (red bar), exons (blue bars), location of individual CpG sites (‘tick marks’) and gene direction (arrow).

I hope somebody could give me some advice or the right way to solve my problem. Very thankful.


问:
I'll create my own TFLITE and the Camera Detector Crash when ill run it on android
`private static final int TF_OD_API_INPUT_SIZE = 512;
private static final boolean TF_OD_API_IS_QUANTIZED = false;
private static final String TF_OD_API_MODEL_FILE = "model.tflite";
private static final String TF_OD_API_LABELS_FILE = "file:///android_asset/LabelsX";
private static final DetectorMode MODE = DetectorMode.TF_OD_API;</p>
```<code>I train my .tflite on google Collab and it is works but when i run it in android studio it can't. Please Help me. Thanks. The size of my model.tflite is 12.88mb`
`
</code>```

Body:
`private static final int TF_OD_API_INPUT_SIZE = 512;
private static final boolean TF_OD_API_IS_QUANTIZED = false;
private static final String TF_OD_API_MODEL_FILE = "model.tflite";
private static final String TF_OD_API_LABELS_FILE = "file:///android_asset/LabelsX";
private static final DetectorMode MODE = DetectorMode.TF_OD_API;

I train my .tflite on google Collab and it is works but when i run it in android studio it can't. Please Help me. Thanks. The size of my model.tflite is 12.88mb`
`


问:
How to share libraries with a iframe?

About my app

I am developing a hybrid desktop application. I use jcef(a chromium embedding framework) to embed a webview inside a java swing application. I currently use just vanilla js with no bundlers.

Problem

I have multiple iframes in my application where I load third-party created-content (served from same domain). These frames will work as UI plugins. I will use libraries like react and ant design(a react component library) and I want third-party iframes to use these libraries as well for consistency. But I need to open around 5 iframes or more at once which concerns me.

Question

Is it possible to load these libraries once and use only one instance of them across all the iframes? If so how?

Title: How to share libraries with a iframe?


问:
Pixel Search Fast How to click colors only when button is pressed? using gdip
```<code>how to use gdip in my code ?
</code>```

loop{

CoordMode, Pixel, Screen

KeyWait, space, D

PixelSearch, FoundX, FoundY, 317, 236, 323, 245, 0xFFFF00, 50, Fast RGB

If (ErrorLevel = 0){

sendinput, {Lbutton down}

sleep, 30

sendinput, {lbutton up}

}

}

return

I have codes that can help but I don't know how to do it

1- CODE

SetBatchLines, -1

#Include Gdip.ahk

pToken := Gdip_Startup()

; Screen area ("X|Y|Width|Height")

pBitmap := Gdip_BitmapFromScreen("500|600|300|100")

; Read RGB color from pixel x290 y65

ARGB := Gdip_GetPixel( pBitmap, 290, 65 )

pixelColor := ARGBtoRGB( ARGB )

MsgBox, % pixelColor

; Read RGB color from pixel x167 y90

ARGB := Gdip_GetPixel( pBitmap, 167, 90 )

pixelColor := ARGBtoRGB( ARGB )

MsgBox, % pixelColor

Gdip_DisposeImage(pBitmap)

Gdip_Shutdown(pToken)

ARGBtoRGB( ARGB ) {

VarSetCapacity( RGB,6,0 )

DllCall( "msvcrt.dll\sprintf", Str,RGB, Str,"%06X", UInt,ARGB<<8 )

Return "0x" RGB

}

2 - CODE

color1 := 0xFFFF00

FastPixel := new FastPixelSearch(0, 0, A_ScreenWidth, A_ScreenHeight)

res1 := FastPixel.Search(color1)

class FastPixelSearch

{

__New(x, y, w, h) {

this.hBM := this.Api.HBitmapFromScreen(x, y, w, h, pvBits)

this.pvBits := pvBits

this.w := w

this.size := w*h

}

Search(colorRGB) {

static bin := 0

(!bin && bin := this.Api.GetBin())

(!(colorRGB >> 24) && colorRGB |= 0xFF000000)

byte := DllCall(bin, "ptr", this.pvBits, "UInt", this.size, "UInt", colorRGB, "Int")

if (byte == this.pvBits + this.size * 4)

Return false

offset := (byte - this.pvBits)//4

Return {x: mod(offset, this.w), y: offset//this.w}

}

class Api

{

GetBin() {

static PAGE_EXECUTE_READWRITE := 0x40, CRYPT_STRING_BASE64 := 0x1

; C source code - https://godbolt.org/z/oYx39nr5s

code := A_PtrSize = 8 ? "idJIjQSRSDnBcw9EOQF1BInI6wZIg8EE6+zD"

: "VYnli1UIi0UMi00QjQSCOcJzDTkKdQSJ0OsFg8IE6+9dww=="

size := StrLen( RTrim(code, "=") )*3//4

bin := DllCall("GlobalAlloc", "UInt", 0, "Ptr", size, "Ptr")

DllCall("VirtualProtect", "Ptr", bin, "Ptr", size, "UInt", PAGE_EXECUTE_READWRITE, "UIntP", old:=0)

DllCall("crypt32\CryptStringToBinary", "Str", code, "UInt", 0, "UInt", CRYPT_STRING_BASE64

, "Ptr", bin, "UIntP", size, "Ptr", 0, "Ptr", 0)

Return bin

}

HBitmapFromScreen(X, Y, W, H, ByRef pvBits) {

static rop := (SRCCOPY := 0x00CC0020) | (CAPTUREBLT := 0x40000000)

hDC := DllCall("GetDC", "Ptr", 0, "Ptr")

hBM := this.CreateDIBSection(W, H, hDC, pvBits)

hMDC := DllCall("CreateCompatibleDC", "Ptr", hDC, "Ptr")

hObj := DllCall("SelectObject", "Ptr", hMDC, "Ptr", hBM, "Ptr")

DllCall("BitBlt", "Ptr", hMDC, "Int", 0, "Int", 0, "Int", W, "Int", H

, "Ptr", hDC, "Int", X, "Int", Y, "UInt", rop)

DllCall("SelectObject", "Ptr", hMDC, "Ptr", hObj, "Ptr")

DllCall("DeleteDC", "Ptr", hMDC)

DllCall("ReleaseDC", "Ptr", 0, "Ptr", hDC)

Return hBM

}

CreateDIBSection(w, h, hDC, ByRef pvBits) {

VarSetCapacity(BITMAPINFO, 40, 0)

NumPut(40, BITMAPINFO,  0)

NumPut( w, BITMAPINFO,  4)

NumPut(-h, BITMAPINFO,  8)

NumPut( 1, BITMAPINFO, 12)

NumPut(32, BITMAPINFO, 14)

hBM := DllCall("CreateDIBSection", "Ptr", hDC, "Ptr", &BITMAPINFO, "UInt", 0

, "PtrP", pvBits, "Ptr", 0, "UInt", 0, "Ptr")

return hBM

}

}

__Delete() {

DllCall("DeleteObject", "Ptr", this.hBM)

}

}

*^NumPad0::ExitApp

Body:
how to use gdip in my code ?

loop{

CoordMode, Pixel, Screen

KeyWait, space, D

PixelSearch, FoundX, FoundY, 317, 236, 323, 245, 0xFFFF00, 50, Fast RGB

If (ErrorLevel = 0){

sendinput, {Lbutton down}

sleep, 30

sendinput, {lbutton up}

}

}

return

I have codes that can help but I don't know how to do it

1- CODE

SetBatchLines, -1

#Include Gdip.ahk

pToken := Gdip_Startup()

; Screen area ("X|Y|Width|Height")

pBitmap := Gdip_BitmapFromScreen("500|600|300|100")

; Read RGB color from pixel x290 y65

ARGB := Gdip_GetPixel( pBitmap, 290, 65 )

pixelColor := ARGBtoRGB( ARGB )

MsgBox, % pixelColor

; Read RGB color from pixel x167 y90

ARGB := Gdip_GetPixel( pBitmap, 167, 90 )

pixelColor := ARGBtoRGB( ARGB )

MsgBox, % pixelColor

Gdip_DisposeImage(pBitmap)

Gdip_Shutdown(pToken)

ARGBtoRGB( ARGB ) {

VarSetCapacity( RGB,6,0 )

DllCall( "msvcrt.dll\sprintf", Str,RGB, Str,"%06X", UInt,ARGB<<8 )

Return "0x" RGB

}

2 - CODE

color1 := 0xFFFF00

FastPixel := new FastPixelSearch(0, 0, A_ScreenWidth, A_ScreenHeight)

res1 := FastPixel.Search(color1)

class FastPixelSearch

{

__New(x, y, w, h) {

this.hBM := this.Api.HBitmapFromScreen(x, y, w, h, pvBits)

this.pvBits := pvBits

this.w := w

this.size := w*h

}

Search(colorRGB) {

static bin := 0

(!bin && bin := this.Api.GetBin())

(!(colorRGB >> 24) && colorRGB |= 0xFF000000)

byte := DllCall(bin, "ptr", this.pvBits, "UInt", this.size, "UInt", colorRGB, "Int")

if (byte == this.pvBits + this.size * 4)

Return false

offset := (byte - this.pvBits)//4

Return {x: mod(offset, this.w), y: offset//this.w}

}

class Api

{

GetBin() {

static PAGE_EXECUTE_READWRITE := 0x40, CRYPT_STRING_BASE64 := 0x1

; C source code - https://godbolt.org/z/oYx39nr5s

code := A_PtrSize = 8 ? "idJIjQSRSDnBcw9EOQF1BInI6wZIg8EE6+zD"

: "VYnli1UIi0UMi00QjQSCOcJzDTkKdQSJ0OsFg8IE6+9dww=="

size := StrLen( RTrim(code, "=") )*3//4

bin := DllCall("GlobalAlloc", "UInt", 0, "Ptr", size, "Ptr")

DllCall("VirtualProtect", "Ptr", bin, "Ptr", size, "UInt", PAGE_EXECUTE_READWRITE, "UIntP", old:=0)

DllCall("crypt32\CryptStringToBinary", "Str", code, "UInt", 0, "UInt", CRYPT_STRING_BASE64

, "Ptr", bin, "UIntP", size, "Ptr", 0, "Ptr", 0)

Return bin

}

HBitmapFromScreen(X, Y, W, H, ByRef pvBits) {

static rop := (SRCCOPY := 0x00CC0020) | (CAPTUREBLT := 0x40000000)

hDC := DllCall("GetDC", "Ptr", 0, "Ptr")

hBM := this.CreateDIBSection(W, H, hDC, pvBits)

hMDC := DllCall("CreateCompatibleDC", "Ptr", hDC, "Ptr")

hObj := DllCall("SelectObject", "Ptr", hMDC, "Ptr", hBM, "Ptr")

DllCall("BitBlt", "Ptr", hMDC, "Int", 0, "Int", 0, "Int", W, "Int", H

, "Ptr", hDC, "Int", X, "Int", Y, "UInt", rop)

DllCall("SelectObject", "Ptr", hMDC, "Ptr", hObj, "Ptr")

DllCall("DeleteDC", "Ptr", hMDC)

DllCall("ReleaseDC", "Ptr", 0, "Ptr", hDC)

Return hBM

}

CreateDIBSection(w, h, hDC, ByRef pvBits) {

VarSetCapacity(BITMAPINFO, 40, 0)

NumPut(40, BITMAPINFO,  0)

NumPut( w, BITMAPINFO,  4)

NumPut(-h, BITMAPINFO,  8)

NumPut( 1, BITMAPINFO, 12)

NumPut(32, BITMAPINFO, 14)

hBM := DllCall("CreateDIBSection", "Ptr", hDC, "Ptr", &BITMAPINFO, "UInt", 0

, "PtrP", pvBits, "Ptr", 0, "UInt", 0, "Ptr")

return hBM

}

}

__Delete() {

DllCall("DeleteObject", "Ptr", this.hBM)

}

}

*^NumPad0::ExitApp


问:
Mutually exclusive types allowing all properties
I am writing a type for nested routes array. The array can contain either a prefixed routes object or a simple route object.

The conditions are:

If it is a simple route object, then it must contain only the properties that are mentioned in IApiRoute.

If it is a prefixed route object that it must contain two keys only

2 a. First key is prefix as mentioned in IPrefixApiRoute.

2 b. Second key is routes array, it can contain an array of objects mentioned in point 2 and point 1.

I have created the typings, but there is a problem, it is not giving a compile time error if I create an object like this

```<code>const array: Array<IRawApiRoute> = [
    {
        prefix: "auth",
        routes: [],
        method: "GET", // This key shouldn't be allowed here, as this object can contain only the keys from IPrefixApiRoute
    },
];
</code>```

The typings that I have prepared are:

```<code>type Method = "GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH";

interface IApiRoute {
    route: string;
    method: Method;
    routeParams: string[];
    queryParams: string[];
    name: string;
}

interface IPrefixApiRoute {
    prefix: string;
    routes: Array<IRawApiRoute>;
}

type IRawApiRoute = IApiRoute | IPrefixApiRoute;
</code>```

I can't seem to figure out the problem. Any help would be appreciated. Thanks

Body:
I am writing a type for nested routes array. The array can contain either a prefixed routes object or a simple route object.

The conditions are:

If it is a simple route object, then it must contain only the properties that are mentioned in IApiRoute.

If it is a prefixed route object that it must contain two keys only

2 a. First key is prefix as mentioned in IPrefixApiRoute.

2 b. Second key is routes array, it can contain an array of objects mentioned in point 2 and point 1.

I have created the typings, but there is a problem, it is not giving a compile time error if I create an object like this

const array: Array<IRawApiRoute> = [
    {
        prefix: "auth",
        routes: [],
        method: "GET", // This key shouldn't be allowed here, as this object can contain only the keys from IPrefixApiRoute
    },
];

The typings that I have prepared are:

type Method = "GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH";

interface IApiRoute {
    route: string;
    method: Method;
    routeParams: string[];
    queryParams: string[];
    name: string;
}

interface IPrefixApiRoute {
    prefix: string;
    routes: Array<IRawApiRoute>;
}

type IRawApiRoute = IApiRoute | IPrefixApiRoute;

I can't seem to figure out the problem. Any help would be appreciated. Thanks


问:
How to show Islamic (Hijri) calendar in datePickerDialog in Android?
I am using below code but this is showing up the gregorian calendar instead of Hijri Calendar...</p>
```<code>val locale = ULocale("@calendar=islamic-umalqura")
val calendar = android.icu.util.Calendar.getInstance(locale)
////tried IslamiCalendar.getInstance(locale) but not working
val date = DatePickerDialog.OnDateSetListener{
        view: DatePicker?, year: Int, month: Int, dayOfMonth: Int ->
        calendar[android.icu.util.IslamicCalendar.YEAR] = year
        calendar[android.icu.util.IslamicCalendar.MONTH] = month
        calendar[android.icu.util.IslamicCalendar.DAY_OF_MONTH] = dayOfMonth
    }
    val datePickerDialog = DatePickerDialog(
        LocalContext.current,
        date,
        calendar[android.icu.util.IslamicCalendar.YEAR],
        calendar[android.icu.util.IslamicCalendar.MONTH],
        calendar[android.icu.util.IslamicCalendar.DAY_OF_MONTH]
    ).show()
</code>```

Body:
I am using below code but this is showing up the gregorian calendar instead of Hijri Calendar...

val locale = ULocale("@calendar=islamic-umalqura")
val calendar = android.icu.util.Calendar.getInstance(locale)
////tried IslamiCalendar.getInstance(locale) but not working
val date = DatePickerDialog.OnDateSetListener{
        view: DatePicker?, year: Int, month: Int, dayOfMonth: Int ->
        calendar[android.icu.util.IslamicCalendar.YEAR] = year
        calendar[android.icu.util.IslamicCalendar.MONTH] = month
        calendar[android.icu.util.IslamicCalendar.DAY_OF_MONTH] = dayOfMonth
    }
    val datePickerDialog = DatePickerDialog(
        LocalContext.current,
        date,
        calendar[android.icu.util.IslamicCalendar.YEAR],
        calendar[android.icu.util.IslamicCalendar.MONTH],
        calendar[android.icu.util.IslamicCalendar.DAY_OF_MONTH]
    ).show()