问:
Scraped data have different numbers of columns in rows, how do I keep the values in line?
I am scraping data with selenium. I have managed to export the data into a csv file and in Excel I split it into columns.
The issue is that some items in the data set have two statuses and others just one. Thus, the statuses each occupy a column which moves the following columns and thus the date for example is not staying within the same column and I cannot sort the table based on the date.

Here is the code and the excel to see the problem:

```<code>#call packages

import random
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import pandas as pd

# define driver etc.
#browser = webdriver.Chrome("C:\\Users\\JRGN1\\PycharmProjects\\dynamic2\\chromedriver.exe")
service_obj = Service("C:\\Users\\JRGN1\\PycharmProjects\\dynamic2\\chromedriver.exe")
browser = webdriver.Chrome(service=service_obj)
#browser.get("https://www.google.com")

# create loop
initiative_list = []
for i in range(0, 2):
    url = 'https://ec.europa.eu/info/law/better-regulation/have-your-say/initiatives_de?page='+str(i)
    browser.get(url)
    time.sleep(random.randint(5, 10))
    initiative_item = browser.find_elements(By.CSS_SELECTOR, "initivative-item")
    initiatives = [item.text for item in initiative_item]
    initiative_list.extend(initiatives)

df = pd.DataFrame(initiative_list)

#create csv

print(df)
df.to_csv('Initiativen.csv')

#df = pd.DataFrame(list_all)
df.columns = ['tosplit']
new_df = df['tosplit'].str.split('\n', expand=True)

print(new_df)
new_df.to_csv('Initiativennew.csv')

</code>```

The split has helped to bring all scraped values of one item in one cell instead of one cell per value.
Excel output

I have reversed the columns in Excel, but that does not help to align the dates in one columns.

The status is in column 0 and in row 2 in column 1 as well.
Is there a way for example to make a condition, when the values of column 0 and 1 are merged into cell 0 based on the content of column 1?
Like there are just 5 different statuses and thus one could maybe use that information.

But if you have better solutions, please just go ahead and thanks in advance.

Body:
I am scraping data with selenium. I have managed to export the data into a csv file and in Excel I split it into columns.
The issue is that some items in the data set have two statuses and others just one. Thus, the statuses each occupy a column which moves the following columns and thus the date for example is not staying within the same column and I cannot sort the table based on the date.

Here is the code and the excel to see the problem:

#call packages

import random
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import pandas as pd

# define driver etc.
#browser = webdriver.Chrome("C:\\Users\\JRGN1\\PycharmProjects\\dynamic2\\chromedriver.exe")
service_obj = Service("C:\\Users\\JRGN1\\PycharmProjects\\dynamic2\\chromedriver.exe")
browser = webdriver.Chrome(service=service_obj)
#browser.get("https://www.google.com")

# create loop
initiative_list = []
for i in range(0, 2):
    url = 'https://ec.europa.eu/info/law/better-regulation/have-your-say/initiatives_de?page='+str(i)
    browser.get(url)
    time.sleep(random.randint(5, 10))
    initiative_item = browser.find_elements(By.CSS_SELECTOR, "initivative-item")
    initiatives = [item.text for item in initiative_item]
    initiative_list.extend(initiatives)

df = pd.DataFrame(initiative_list)

#create csv

print(df)
df.to_csv('Initiativen.csv')

#df = pd.DataFrame(list_all)
df.columns = ['tosplit']
new_df = df['tosplit'].str.split('\n', expand=True)

print(new_df)
new_df.to_csv('Initiativennew.csv')

The split has helped to bring all scraped values of one item in one cell instead of one cell per value.
Excel output

I have reversed the columns in Excel, but that does not help to align the dates in one columns.

The status is in column 0 and in row 2 in column 1 as well.
Is there a way for example to make a condition, when the values of column 0 and 1 are merged into cell 0 based on the content of column 1?
Like there are just 5 different statuses and thus one could maybe use that information.

But if you have better solutions, please just go ahead and thanks in advance.


来源: stackexchange

问:
Download image created by the PHP Exif Library from browser
Im using PEL - the PHP Exif Library to add metadata to my image.
the script work well and i can do online view my image with browser.

```<code>$jpeg = new PelJpeg($inputfile);
$jpeg->setExif($exif);
header("Content-Type: image/jpeg");
echo $jpeg->getBytes();
</code>```

but when i tried to download it, script did not work.

```<code>$jpeg = new PelJpeg($inputfile);
$jpeg->setExif($exif);
header("Content-Type: image/jpeg");
header('Content-Disposition: attachment; filename=nature.jpg');

</code>```

Please help.

Thank you!

im trying to allow user download the file from browser but the file i got has 0 byte and said corrupted.

ContentLicense: CC BY-SA 4.0

Body:
Im using PEL - the PHP Exif Library to add metadata to my image.
the script work well and i can do online view my image with browser.

$jpeg = new PelJpeg($inputfile);
$jpeg->setExif($exif);
header("Content-Type: image/jpeg");
echo $jpeg->getBytes();

but when i tried to download it, script did not work.

$jpeg = new PelJpeg($inputfile);
$jpeg->setExif($exif);
header("Content-Type: image/jpeg");
header('Content-Disposition: attachment; filename=nature.jpg');

Please help.

Thank you!

im trying to allow user download the file from browser but the file i got has 0 byte and said corrupted.


问:
Data overwrites from fetched url's javascript
I've built my own rest api (http://localhost:8080/weatherapi/{city}) this fetches simple data from an other api. If I call the data separate it works but if I loop through it it overwrites with the last fetched data.

```<code>let arrayOfUrls = ["http://localhost:8080/weatherapi/mechelen","http://localhost:8080/weatherapi/denbosch","http://localhost:8080/weatherapi/antwerp"];

for (let word of arrayOfUrls){
  console.log(word)
  let {data: weather} = useFetch(word);
  console.log(weather)
}
</code>```

My question is how do I get individual data from every link :)

Body:
I've built my own rest api (http://localhost:8080/weatherapi/{city}) this fetches simple data from an other api. If I call the data separate it works but if I loop through it it overwrites with the last fetched data.

let arrayOfUrls = ["http://localhost:8080/weatherapi/mechelen","http://localhost:8080/weatherapi/denbosch","http://localhost:8080/weatherapi/antwerp"];

for (let word of arrayOfUrls){
  console.log(word)
  let {data: weather} = useFetch(word);
  console.log(weather)
}

My question is how do I get individual data from every link :)


问:
is there any idea about how to put percentage value in Sankey graph?
can anyone please tell me how to put percentage value or percentage sign in the Sankey graph using pandas code?

enter image description here
i am trying this graph but expecting each category with percentage


问:
How to export the the canvas content into postscript with High Quality in Tkinter python
I tried to use Canvas.postscript to export all the canvas object into *.ps file but some of the objects are not visible it is showing in black color see the output Picture. I tried many option but nothing resolved. Could anyone please suggest some solution ?</p>
```<code>`
from tkinter import *
from PIL import Image

app = Tk()

app.geometry("1200x900")

app.title("Canvas")

C = Canvas(app)

C.create_rectangle(100, 50, 800 ,800,  outline='black', fill = 'white')
C.create_text(450,375,text = "Checking",font=('Arial',10,'bold'))

Y_axis = 85
for z in range(20):
    x = Button(C, text = "X1234578978514"+str(z), anchor = W,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#E0E1F5')
    P = C.create_window(100, Y_axis, window=x,anchor = W)
    Y= Button(C, text = "+", anchor = E,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#C4BDFA')
    C.create_window(100, Y_axis, window=Y,anchor = E)
    Y_axis = Y_axis+35

Y_axis = 85
for z in range(20):
    x = Button(C, text = "+", anchor = W,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#C4BDFA')
    P = C.create_window(800, Y_axis, window=x,anchor = W)
    Y= Button(C, text = "X1234578978514"+str(z), anchor = E,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#E0E1F5')
    C.create_window(800, Y_axis, window=Y,anchor = E)
    Y_axis = Y_axis+35

def postUpdate(event):
    ScrollregionCanvas = C.bbox('all')
    w = ScrollregionCanvas[2] - ScrollregionCanvas[0]+C.winfo_rootx()
    h = ScrollregionCanvas[3] - ScrollregionCanvas[1]+C.winfo_rooty()
    C.update()
    C.postscript(file='screenshot.ps', colormode='color',pagewidth=w*2,pageheight=h*2,width=w,height=h)
    psimage=Image.open('screenshot.ps')
    psimage.show()

C.pack(fill=BOTH,expand=True)
app.bind("<Control-p>",postUpdate )
#C.update()

# Make the loop for displaying app
app.mainloop()`
</code>```

Body:
I tried to use Canvas.postscript to export all the canvas object into *.ps file but some of the objects are not visible it is showing in black color see the output Picture. I tried many option but nothing resolved. Could anyone please suggest some solution ?

`
from tkinter import *
from PIL import Image

app = Tk()

app.geometry("1200x900")

app.title("Canvas")

C = Canvas(app)

C.create_rectangle(100, 50, 800 ,800,  outline='black', fill = 'white')
C.create_text(450,375,text = "Checking",font=('Arial',10,'bold'))

Y_axis = 85
for z in range(20):
    x = Button(C, text = "X1234578978514"+str(z), anchor = W,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#E0E1F5')
    P = C.create_window(100, Y_axis, window=x,anchor = W)
    Y= Button(C, text = "+", anchor = E,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#C4BDFA')
    C.create_window(100, Y_axis, window=Y,anchor = E)
    Y_axis = Y_axis+35

Y_axis = 85
for z in range(20):
    x = Button(C, text = "+", anchor = W,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#C4BDFA')
    P = C.create_window(800, Y_axis, window=x,anchor = W)
    Y= Button(C, text = "X1234578978514"+str(z), anchor = E,font = ("Arial", 10),borderwidth=0, cursor='hand2',bg='#E0E1F5')
    C.create_window(800, Y_axis, window=Y,anchor = E)
    Y_axis = Y_axis+35

def postUpdate(event):
    ScrollregionCanvas = C.bbox('all')
    w = ScrollregionCanvas[2] - ScrollregionCanvas[0]+C.winfo_rootx()
    h = ScrollregionCanvas[3] - ScrollregionCanvas[1]+C.winfo_rooty()
    C.update()
    C.postscript(file='screenshot.ps', colormode='color',pagewidth=w*2,pageheight=h*2,width=w,height=h)
    psimage=Image.open('screenshot.ps')
    psimage.show()

C.pack(fill=BOTH,expand=True)
app.bind("<Control-p>",postUpdate )
#C.update()

# Make the loop for displaying app
app.mainloop()`


问:
Xamarin Forms Shell, is it possible to preload pages before the user actually navigates to the page?
I've got a few issues with Xamarin.Communitytoolkit which doesn't load the video and then shows the page it waits for the page to appear to then actually load the video giving a very bad user experience with flicker loading and occasionally stutters or constant pause play effect.

I want to be able to load a page onto a stack way before the user actually clicks the next button which navigates to that page creating a new instance.

I saw this post on How to pre-load pages on SO but the problem is that this doesn't use shell so they don't have to deal with Routing. Also navigation is much different in Shell doing Shell.Current.GoToAsync(URI type navigation string?queries)

Is this possible to do with Shell? And if so how?

Update: After doing more research is that I need to insert a new page to the navigation stack before the user clicks next to then navigate to that page. This way the page will have everything ready for the user without loading anything again. This is actually happening while navigating backwards on the stack and there is nothing to do with the visual glitches which I see.

Many Thanks in advance.

```<code>public AppShell()
{
    InitializeComponent();

    Routing.RegisterRoute(nameof(ListenAndViewPage), typeof(ListenAndViewPage));
    Routing.RegisterRoute(nameof(SpellPage), typeof(SpellPage));
    Routing.RegisterRoute(nameof(CopyWhatIDoPage), typeof(CopyWhatIDoPage));
    Routing.RegisterRoute(nameof(QuizPage), typeof(QuizPage));
}
</code>```

Update-2:
I have a JSON file with Levels for my games and each level contains a Video path.

I have a Json reader which reads the file and then deserialize into my Level obj.

I then made a LevelReader which has methods to extract level data depending on CurrentLevel + other params if needed.

I load the MediaElement source with data binding from my ViewModel for the page.

The videos are part of iOS & Android projects as Android Resource or Bundle Resource.

Body:
I've got a few issues with Xamarin.Communitytoolkit which doesn't load the video and then shows the page it waits for the page to appear to then actually load the video giving a very bad user experience with flicker loading and occasionally stutters or constant pause play effect.

I want to be able to load a page onto a stack way before the user actually clicks the next button which navigates to that page creating a new instance.

I saw this post on How to pre-load pages on SO but the problem is that this doesn't use shell so they don't have to deal with Routing. Also navigation is much different in Shell doing Shell.Current.GoToAsync(URI type navigation string?queries)

Is this possible to do with Shell? And if so how?

Update: After doing more research is that I need to insert a new page to the navigation stack before the user clicks next to then navigate to that page. This way the page will have everything ready for the user without loading anything again. This is actually happening while navigating backwards on the stack and there is nothing to do with the visual glitches which I see.

Many Thanks in advance.

public AppShell()
{
    InitializeComponent();

    Routing.RegisterRoute(nameof(ListenAndViewPage), typeof(ListenAndViewPage));
    Routing.RegisterRoute(nameof(SpellPage), typeof(SpellPage));
    Routing.RegisterRoute(nameof(CopyWhatIDoPage), typeof(CopyWhatIDoPage));
    Routing.RegisterRoute(nameof(QuizPage), typeof(QuizPage));
}

Update-2:
I have a JSON file with Levels for my games and each level contains a Video path.

I have a Json reader which reads the file and then deserialize into my Level obj.

I then made a LevelReader which has methods to extract level data depending on CurrentLevel + other params if needed.

I load the MediaElement source with data binding from my ViewModel for the page.

The videos are part of iOS & Android projects as Android Resource or Bundle Resource.


问:
Is there a standard way to interact with my DPDK or C-program through cmdline on linux?
I'm looking for a more "professional" way to interact with my programs written in C through command line(on linux).For example, when I want to modify the values of some of these variables during program runtime, what should I do?

Assume I want to modify values in program cmd_ser, I used to start a UDP client program cmd_cli, which sends UDP datagrams to a specific local port. Then cmd_ser will act like a UDP server, receives the datagram and parses values from it.

To call cmd_cli by command, I added the executable binary, cmd_cli.exe to file:~/.bashrc, using alias to define a custom command — cmd_cli. Thus, once I execute cmd cmd_cli para1 val1, it calls cmd_cli.exe and send a UDP datagram to the local port.

Question is:

To consistently listen messages from local port, I'll have to start a new thread in my program cmd_ser, I was wondering if there were some more convenient and professional ways...

I would like to change the value during a new DPDK program runtime now, then I cannot use kernel networking APIs, is there som DPDK Lib APIs?(I'm totally rookie to DPDK and C programming, thanks!).


问:
Client & Backend deployed separately - 404 error page on refresh despite proxy configuration
My project has a frontend and a backend deployed separately from 2 separate Github repos on "render.com".

It also has a Mongoose database for user credentials. But it is not the subject of this question.

All was working fine until I refreshed any page, I got 404 Not Found despite the configured proxy.

For instance, I redirect all my client-side links to "/" so that the user does not get the 404 Not Found page. At least it is more user friendly.

Here are some more details:

Frontend is a Vite react client:
Client Repo: https://github.com/Catevika/catevika_shoplineart-client
Render static site: https://shoplineart-afbr.onrender.com

Backend is an Express server:
Server Repo: https://github.com/Catevika/catevika_shoplineart-server
Render web service: https://shoplineart-api.onrender.com

Routes are managed client-side with react-router V6 but an authRoute for Login / Register.

File structure:

```<code>root
.. client
.. dist --> build folder with assets: pictures - ok in Render
.. src
.... api --> for Login
.... (...)
.. vite.config.js --> with proxy - ok in Render thanks to a Vite base URL variable
.. index.html --> outside "public" - specific to Vite
.. main.jsx
.. .env --> ok in Render
.. package.json

 .. server
 .. (...)
 .. index.js
 .. .env --> ok in Render
 .. package.json --> type: "module" to use the "import" instead of "require"

</code>```

vite.config.js:

```<code>import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
    server: {
        proxy: {
            '/api': {
                target: 'https://shoplineart-api.onrender.com',
                changeOrigin: true
            }
        }
    },
    plugins: [react()]
});
</code>```

Express index.js:

```<code>import express from 'express';
import mongoose from 'mongoose';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import cors from 'cors';
import path from 'path';

import authRoute from './routes/authRoute.js';

dotenv.config();
const app = express();
app.use(cors());

mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_URI);
console.log('\x1b[33m', 'MongoDB connected successfully');

app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: 'cross-origin' }));
app.use(morgan('common'));

app.use('/', authRoute);

app.listen(process.env.EXPRESS_PORT, () =>
    console.log('\x1b[33m', `Server running on port ${process.env.EXPRESS_PORT}`)
);

if (process.env.NODE_ENV === 'production') {
    app.get('*', (req, res) =>
        res.sendFile(path.resolve(__dirname, '../client', 'dist', 'index.html'))
    );
}

</code>```

I tried adding secure: false in vite.config.js.
It failed.

What am I missing?

Thanks a lot for your precious help. I am stuck...

Body:
My project has a frontend and a backend deployed separately from 2 separate Github repos on "render.com".

It also has a Mongoose database for user credentials. But it is not the subject of this question.

All was working fine until I refreshed any page, I got 404 Not Found despite the configured proxy.

For instance, I redirect all my client-side links to "/" so that the user does not get the 404 Not Found page. At least it is more user friendly.

Here are some more details:

Frontend is a Vite react client:
Client Repo: https://github.com/Catevika/catevika_shoplineart-client
Render static site: https://shoplineart-afbr.onrender.com

Backend is an Express server:
Server Repo: https://github.com/Catevika/catevika_shoplineart-server
Render web service: https://shoplineart-api.onrender.com

Routes are managed client-side with react-router V6 but an authRoute for Login / Register.

File structure:

root
.. client
.. dist --> build folder with assets: pictures - ok in Render
.. src
.... api --> for Login
.... (...)
.. vite.config.js --> with proxy - ok in Render thanks to a Vite base URL variable
.. index.html --> outside "public" - specific to Vite
.. main.jsx
.. .env --> ok in Render
.. package.json

 .. server
 .. (...)
 .. index.js
 .. .env --> ok in Render
 .. package.json --> type: "module" to use the "import" instead of "require"

vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
    server: {
        proxy: {
            '/api': {
                target: 'https://shoplineart-api.onrender.com',
                changeOrigin: true
            }
        }
    },
    plugins: [react()]
});

Express index.js:

import express from 'express';
import mongoose from 'mongoose';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import cors from 'cors';
import path from 'path';

import authRoute from './routes/authRoute.js';

dotenv.config();
const app = express();
app.use(cors());

mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_URI);
console.log('\x1b[33m', 'MongoDB connected successfully');

app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: 'cross-origin' }));
app.use(morgan('common'));

app.use('/', authRoute);

app.listen(process.env.EXPRESS_PORT, () =>
    console.log('\x1b[33m', `Server running on port ${process.env.EXPRESS_PORT}`)
);

if (process.env.NODE_ENV === 'production') {
    app.get('*', (req, res) =>
        res.sendFile(path.resolve(__dirname, '../client', 'dist', 'index.html'))
    );
}

I tried adding secure: false in vite.config.js.
It failed.

What am I missing?

Thanks a lot for your precious help. I am stuck...


问:
ReactJS Material UI Reset Radio Buttons
I have Material UI radio buttons in my ReactJS form :

```<code><FormControl className={ styles.rowControl }>
    <FormLabel>Direction</FormLabel>
    <RadioGroup name="direction" onChange={ this.setOption } ref={ this.directionGroupRef }>
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="North"
            ref={ this.northRef }
            value="North"
        />
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="South"
            value="South"
        />
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="Flip-Flop"
            value="Flip-Flop"
        />
    </RadioGroup>
</FormControl>

</code>```

How can I remove any checked statuses among these radio buttons when the form is submitted?

Title: ReactJS Material UI Reset Radio Buttons

Body:
I have Material UI radio buttons in my ReactJS form :

<FormControl className={ styles.rowControl }>
    <FormLabel>Direction</FormLabel>
    <RadioGroup name="direction" onChange={ this.setOption } ref={ this.directionGroupRef }>
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="North"
            ref={ this.northRef }
            value="North"
        />
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="South"
            value="South"
        />
        <FormControlLabel
            className={ styles.rowFirstLabel }
            control={<Radio />}
            label="Flip-Flop"
            value="Flip-Flop"
        />
    </RadioGroup>
</FormControl>

How can I remove any checked statuses among these radio buttons when the form is submitted?


问:
hookHeader in Prestashop, breaks flow whatever I do
I want to add a custom js file my_sdk.js in my Prestashop module.

I register the hook header and prepare the function,
but whatever I do inside, breaks something.
My my_sdk.js file is correctly added by addJS() and it works.
The problem is that, after that, the cart is no more updated.

Whatever I write inside the hookHeader, it's executed but then the popup showing after the 'add to cart' action, stops working. The popup doesn't show up and the total amount of the cart is not updated until I refresh the page. It's not a problem of my js file, even if I don't import it and write something else (like an echo), I have the same problem.

It works only if I don't write anything (or comment everything) inside function hookHeader().

 public function install() {
        return (bool) $this->registerHook(['header']);
    }

    public function hookHeader($params) {

        $this->context->controller->addJS(_PS_MODULE_DIR_ . $this->name . '/views/js/my_sdk.js');  // this line breaks the popup
        echo "hello, this breaks the popup"; // also just this line breaks the popup

    }
```

I really don't understand why. Tried also with hookDisplayHeader, same thing. The website works, without errors, but the cart is not updated and the popup doesn't show.

Body:
I want to add a custom js file my_sdk.js in my Prestashop module.

I register the hook header and prepare the function,
but whatever I do inside, breaks something.
My my_sdk.js file is correctly added by addJS() and it works.
The problem is that, after that, the cart is no more updated.

Whatever I write inside the hookHeader, it's executed but then the popup showing after the 'add to cart' action, stops working. The popup doesn't show up and the total amount of the cart is not updated until I refresh the page. It's not a problem of my js file, even if I don't import it and write something else (like an echo), I have the same problem.

It works only if I don't write anything (or comment everything) inside function hookHeader().

 public function install() {
        return (bool) $this->registerHook(['header']);
    }

    public function hookHeader($params) {

        $this->context->controller->addJS(_PS_MODULE_DIR_ . $this->name . '/views/js/my_sdk.js');  // this line breaks the popup
        echo "hello, this breaks the popup"; // also just this line breaks the popup

    }

I really don't understand why. Tried also with hookDisplayHeader, same thing. The website works, without errors, but the cart is not updated and the popup doesn't show.


问:
Discord - Post API Data via Bot
I want to create a Discord Bot which listens to an API Call from a different Server.

For Example:

Discord Bot is running in my own Server and listening to ! commands

Another Server (Webserver) is having an event

The other server needs to call my Discord Bot (HTTP Request ?)

The Discord Bot needs to send a Message containing the Data from the previous call to a predefined Channel

I just can't find a way to do this. I tried webhooks, bot commands, discord gateway etc.
But there just seems to be no way that I can be able to send a message to my discord server via bot from a http request.

Anyone having a great idea how to achieve this ?

Thanks in advance!

What I have done so far:
Created a Bot using discord.io
Created Bot commands listening to ! (works)
Created a Websocket (works, but not able to send message)
Created a Webhook via Discord.js (Works but created no URL so I can't send a Message, also too dynamic)

Title: Discord - Post API Data via Bot


问:
docker login shows x509: certificate signed by unknown authority
I am running docker registry as container in Ubuntu 22.04 with Docker version 20.10.22 if configured with self-sign certificate.

I have tried open daemon.json and add insecure-registries.
But still not working. Can you help on this issue?

container started successfully. But giving error for docker login command.

Error message:
Error response from daemon: x509: certificate signed by unknown authority

enter image description here


问:
DocumentFilter and FocusListener conflicts
I must implement UI which using DocumentFilter and FocusListener for following requirements:

In each input field only the input of single digits should be possible. Multi-digit numbers should not be entered into a field (not even temporarily). be entered into a field. Use a DocumentFilter to implement this requirement.

In the currently edited field, the currently entered value should be displayed. In the other fields an asterisk should be displayed. Use FocusEvents to implement this requirement.
Following is my code

```<code>import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Set;

public class PasswordForm extends JFrame {

    // Declare input fields
    private JTextField field1;
    private JTextField field2;
    private JTextField field3;

    public PasswordForm() {
        // Set layout for the form
        setLayout(new FlowLayout());

        // Initialize input fields with value 0
        field1 = new JTextField(3);
        field2 = new JTextField(3);
        field3 = new JTextField(3);

        field1.setText("0");
        field2.setText("0");
        field3.setText("0");

        // Create a document filter to allow only single-digit input
        DocumentFilter filter = new SingleDigitFilter();

        //PasswordFieldFocusListener listener = new PasswordFieldFocusListener(filter);

        // Set focus listeners for each input field
        field1.addFocusListener(new PasswordFieldFocusListener(filter, field1));
        field2.addFocusListener(new PasswordFieldFocusListener(filter, field2));
        field3.addFocusListener(new PasswordFieldFocusListener(filter, field3));

//         //Set the document filter for each input field
//        ((AbstractDocument) field1.getDocument()).setDocumentFilter(filter);
//        ((AbstractDocument) field2.getDocument()).setDocumentFilter(filter);
//        ((AbstractDocument) field3.getDocument()).setDocumentFilter(filter);

        // Add input fields to the form
        add(field1);
        add(field2);
        add(field3);
    }

    public static void main(String[] args) {
        PasswordForm form = new PasswordForm();
        form.setTitle("Access Data Query");
        form.setSize(300, 100);
        form.setLocationRelativeTo(null);
        form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        form.setVisible(true);
    }

    private class PasswordFieldFocusListener implements FocusListener {
        private JTextField textField;
        private SingleDigitFilter filter;

        public PasswordFieldFocusListener(DocumentFilter filter, JTextField textField) {
            this.filter =  (SingleDigitFilter) filter;
            this.textField = textField;
            ((AbstractDocument) textField.getDocument()).setDocumentFilter(this.filter);
        }

        @Override
        public void focusGained(FocusEvent e) {
            // Display the currently entered value in the currently edited field
            //JTextField field = (JTextField)e.getSource();
//            filter.setChanging(true);
//            System.out.println(filter.isChanging());
//            textField.setText(textField.getText());
//            System.out.println(textField.getText());
        }

        @Override
        public void focusLost(FocusEvent e) {
            // Use SwingUtilities.invokeLater to display asterisks in the other fields when focus is lost
            //JTextField field = (JTextField)e.getSource();
            System.out.println("test");
            textField.setText("*");
            textField.revalidate();
            textField.repaint();        }
    }

    // SingleDigitFilter class to allow only single-digit input
    class SingleDigitFilter extends DocumentFilter {
        private boolean changing = false;
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if (!changing && string.matches("[\\d*]") && (fb.getDocument().getLength() < 1)) {
                super.insertString(fb,offset, string, attr);
                System.out.println("inserr");
            }
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (!changing && text.matches("[\\d*]")&& (fb.getDocument().getLength() < 1)) {
                super.replace(fb, offset, length, text, attrs);
                System.out.println("replace");
            }
        }

        public void setChanging(boolean changing) {
            this.changing = changing;
        }

        public boolean isChanging() {
            return changing;
        }
    }
}
</code>```

Problem: the FocusListener does not work!, also the setText - Method wouldn't be called! but when I deleted the DocumentFilter, then it worked. I will appreciate for any advices.
Thanks in advance.

Body:
I must implement UI which using DocumentFilter and FocusListener for following requirements:

In each input field only the input of single digits should be possible. Multi-digit numbers should not be entered into a field (not even temporarily). be entered into a field. Use a DocumentFilter to implement this requirement.

In the currently edited field, the currently entered value should be displayed. In the other fields an asterisk should be displayed. Use FocusEvents to implement this requirement.
Following is my code

import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Set;

public class PasswordForm extends JFrame {

    // Declare input fields
    private JTextField field1;
    private JTextField field2;
    private JTextField field3;

    public PasswordForm() {
        // Set layout for the form
        setLayout(new FlowLayout());

        // Initialize input fields with value 0
        field1 = new JTextField(3);
        field2 = new JTextField(3);
        field3 = new JTextField(3);

        field1.setText("0");
        field2.setText("0");
        field3.setText("0");

        // Create a document filter to allow only single-digit input
        DocumentFilter filter = new SingleDigitFilter();

        //PasswordFieldFocusListener listener = new PasswordFieldFocusListener(filter);

        // Set focus listeners for each input field
        field1.addFocusListener(new PasswordFieldFocusListener(filter, field1));
        field2.addFocusListener(new PasswordFieldFocusListener(filter, field2));
        field3.addFocusListener(new PasswordFieldFocusListener(filter, field3));

//         //Set the document filter for each input field
//        ((AbstractDocument) field1.getDocument()).setDocumentFilter(filter);
//        ((AbstractDocument) field2.getDocument()).setDocumentFilter(filter);
//        ((AbstractDocument) field3.getDocument()).setDocumentFilter(filter);

        // Add input fields to the form
        add(field1);
        add(field2);
        add(field3);
    }

    public static void main(String[] args) {
        PasswordForm form = new PasswordForm();
        form.setTitle("Access Data Query");
        form.setSize(300, 100);
        form.setLocationRelativeTo(null);
        form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        form.setVisible(true);
    }

    private class PasswordFieldFocusListener implements FocusListener {
        private JTextField textField;
        private SingleDigitFilter filter;

        public PasswordFieldFocusListener(DocumentFilter filter, JTextField textField) {
            this.filter =  (SingleDigitFilter) filter;
            this.textField = textField;
            ((AbstractDocument) textField.getDocument()).setDocumentFilter(this.filter);
        }

        @Override
        public void focusGained(FocusEvent e) {
            // Display the currently entered value in the currently edited field
            //JTextField field = (JTextField)e.getSource();
//            filter.setChanging(true);
//            System.out.println(filter.isChanging());
//            textField.setText(textField.getText());
//            System.out.println(textField.getText());
        }

        @Override
        public void focusLost(FocusEvent e) {
            // Use SwingUtilities.invokeLater to display asterisks in the other fields when focus is lost
            //JTextField field = (JTextField)e.getSource();
            System.out.println("test");
            textField.setText("*");
            textField.revalidate();
            textField.repaint();        }
    }

    // SingleDigitFilter class to allow only single-digit input
    class SingleDigitFilter extends DocumentFilter {
        private boolean changing = false;
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if (!changing && string.matches("[\\d*]") && (fb.getDocument().getLength() < 1)) {
                super.insertString(fb,offset, string, attr);
                System.out.println("inserr");
            }
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (!changing && text.matches("[\\d*]")&& (fb.getDocument().getLength() < 1)) {
                super.replace(fb, offset, length, text, attrs);
                System.out.println("replace");
            }
        }

        public void setChanging(boolean changing) {
            this.changing = changing;
        }

        public boolean isChanging() {
            return changing;
        }
    }
}

Problem: the FocusListener does not work!, also the setText - Method wouldn't be called! but when I deleted the DocumentFilter, then it worked. I will appreciate for any advices.
Thanks in advance.


问:
PayPal webhooks integration with django
I am integrating Paypal in django-rest- framework. The issue is with paypal webhook response. I get a webhook json response  when ever  I pay some amount on paypal already  created a url path in my application for the same.

Sample JSON object response:

{'event_version': '1.0', 'create_time': '2022-12-19T18:57:12.343Z', 'resource_type': 'checkout-order', 'resource_version': '2.0', 'event_type': 'CHECKOUT.ORDER.APPROVED', 'summary': 'An order has been approved by buyer', 'resource': {'update_time': '2022-12-19T18:57:02Z', 'create_time': '2022-12-19T18:56:51Z', 'purchase_units': [{'reference_id': 'default', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'payee': {'email_address': 'mailto:sb-dgfcl23459178@business.example.com', 'merchant_id': ''jkdshfhsjdfhjksfhjsfs'}, 'custom_id': 'e-book-1234', 'shipping': {'name': {'full_name': 'John Doe'}, 'address': {'address_line_1': '1 Main St', 'admin_area_2': 'San Jose', 'admin_area_1': 'CA', 'postal_code': '95131', 'country_code': 'US'}}, 'payments': {'captures': [{'id': '9HW93194EE464044X', 'status': 'COMPLETED', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'final_capture': True, 'seller_protection': {'status': 'ELIGIBLE', 'dispute_categories': ['ITEM_NOT_RECEIVED', 'UNAUTHORIZED_TRANSACTION']}, 'seller_receivable_breakdown': {'gross_amount': {'currency_code': 'USD', 'value': '10.00'}, 'paypal_fee': {'currency_code': 'USD', 'value': '0.84'}, 'net_amount': {'currency_code': 'USD', 'value': '9.16'}}, 'links': [{'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X/refund', 'rel': 'refund', 'method': 'POST'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'up', 'method': 'GET'}], 'create_time': '2022-12-19T18:57:02Z', 'update_time': '2022-12-19T18:57:02Z'}]}}], 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'self', 'method': 'GET'}], 'id': '4CV868937U646315D', 'payment_source': {'paypal': {}},
'intent': 'CAPTURE', 'payer': {'name': {'given_name': 'John', 'surname': 'Doe'},
'email_address': "adsfhjasdfhdajhk@gmail.com"
'payer_id': 'CSNQVZ49MMDA2',
  'address': {'country_code': 'US'}},
  'status': 'COMPLETED'},
  'links': [{'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G/resend', 'rel': 'resend', 'method': 'POST'}]}

Is there any inbuilt library which can handle this response in python or database design to handle this or I need to create it myself.

Title: PayPal webhooks integration with django


问:
extracting the number of orders for each category according to its' date by the number of the product type appeared using python
extracting the number of orders for each category according to its' date by the number of the product type appeared using python keep in mind that the date variable is not the data as a column i transformed the date and time variable into a date variable

i used the following liabraries

#Importing libraries  import pandas as pd  import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set()

these are my products

```<code>print(" The Total number for each product type: ")

data.products.value_counts()

</code>```

the output is

```<code>productA                      8124
productB                      3047
</code>```

the trasformation

```<code>data['date'] = pd.to_datetime(data['Assessment_Date']).dt.date
data['date']=pd.to_datetime(data['date'])
</code>```

here where i tried to count ho many number order for each product based on the date

```<code>data.set_index('date',inplace=True)
</code>```

and the output is

KEYERROR: 'date' is not a column in the data

please if you have another way to get the output bellow let me now

```<code>PRODUCT TYPE       DATE                NUMBER OF ORDERS
productA           1-11-2020           11
productB           1-11-2020           122

</code>```

and so on for the whole period
thank you

Body:
extracting the number of orders for each category according to its' date by the number of the product type appeared using python keep in mind that the date variable is not the data as a column i transformed the date and time variable into a date variable

i used the following liabraries

#Importing libraries  import pandas as pd  import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set()

these are my products

print(" The Total number for each product type: ")

data.products.value_counts()

the output is

productA                      8124
productB                      3047

the trasformation

data['date'] = pd.to_datetime(data['Assessment_Date']).dt.date
data['date']=pd.to_datetime(data['date'])

here where i tried to count ho many number order for each product based on the date

data.set_index('date',inplace=True)

and the output is

KEYERROR: 'date' is not a column in the data

please if you have another way to get the output bellow let me now

PRODUCT TYPE       DATE                NUMBER OF ORDERS
productA           1-11-2020           11
productB           1-11-2020           122

and so on for the whole period
thank you


问:
VS Code shows me errors due to local PHP version
I am currently working on a PHP Laravel project. For this project I need at least PHP 8.1, so I have a PHP Docker instance. On my Mac I have php 7.3.24. The project runs as expected. But my IDE (VS Code) gives me an error message in many places due to the local PHP version. For example, the typehint of class variables.

In addition, included libraries are not recognised when I want to initiate them (undefined type).

My question: Do I have to upgrade the local PHP version or is there a setting in the IDE?


问:
Sending bolded words through Telegram
I'm building a chatbot and I need to send some words in bold. According to the Telegram documentation, to make a word bold, you need to put two asterisks at the beginning of it and two at the end. However, it doesn't work:

So I was wondering if anyone knows if anything has changed and if the documentation is out of date

I tried with two asterisks and with HTML tags

Title: Sending bolded words through Telegram


问:
Change html received from AJAX Wordpress
I am trying to put the form back after 2 seconds of success message, for that I've sent the form html code along with API response, can someone help me to put the form code inside
 div after 2 seconds success message?

Also the response getting as html form is same form <form class="custom-popup-form">

jQuery:

```<code>jQuery( ".custom-popup-form" ).on( "submit", function( event ) {
  event.preventDefault();
  let sdata = jQuery( this ).serialize();

  jQuery.ajax({
      url: my_ajax_object.ajax_url,
      type: "post",
      cache: false,
      async: false,
      data: {
        action: "submit_huspot_dynamic_form",
        data: sdata
      },

      beforeSend: function () {
        var img_loading =
          '<div class="posts-page-links"><img src="' +
          my_ajax_object.loading_gif_url +
          '"></div>';
        jQuery(".loading_gif").html(img_loading);
      },
      success: function (res) {
          console.log(res);
          jQuery(".loading_gif").hide();
          jQuery(".custom-popup-form-wrapper").html('<p>We have received your request. We will get in touch with you shortly.</p>');
      }
});

});
</code>```

Response received:

```<code>    {"inlineMessage":"<p>We have received your request. We will get in touch with you shortly.</p>"}
<style>
        .custom-popup-form input#phone_number,.custom-popup-form input#first_name,.custom-popup-form input#last_name,.custom-popup-form input#email,.custom-popup-form textarea#message,.custom-popup-form input#company_name,.custom-popup-form input#designation{
        background-color: #f5f8fa !important;
        border: 1px solid #c9c9c9 !important;
        color: #000000 !important;
        border-radius: 10px !important;
    }
    .custom-popup-form .message_css{
        padding: 0 !important;
        font-size: 15px !important;
    }
    </style>
    <div class="custom-popup-form-wrapper">
    <form class="custom-popup-form">
      <div class="row">
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
          <label for="email">Email*</label>
          <input type="email" class="form-control" id="email" name="email" required>
          <span id="email_msg" style="display:none;"></span>
          </div>
      </div>
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
          <label for="phone_number">Phone Number*</label>
          <input type="text" class="form-control" id="phone_number" name="phone_number" required>
          <span id="phone_number_msg" style="display:none;"></span>
        </div>
      </div>
    </div>

        <div class="row">
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
          <label for="first_name">First Name*</label>
          <input type="text" class="form-control" id="first_name" name="first_name" required>
          <span id="first_name_msg" style="display:none;"></span>
          </div>
      </div>
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
           <label for="last_name">Last Name*</label>
          <input type="text" class="form-control" id="last_name" name="last_name" required>
          <span id="last_name_msg" style="display:none;"></span>
        </div>
      </div>
    </div>

      <div class="row">
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
          <label for="company_name">Company name*</label>
          <input type="text" class="form-control" id="company_name" name="company_name" required>
          <span id="company_name_msg" style="display:none;"></span>
          </div>
      </div>
      <div class="col-md-6 col-xs-12 col-sm-6">
      <div class="form-group">
           <label for="designation">Designation*</label>
          <input type="text" class="form-control" id="designation" name="designation" required>
          <span id="designation_msg" style="display:none;"></span>
        </div>
      </div>
    </div>

       <div class="col-12 message_css">
      <div class="form-group">
           <label for="message">Message*</label>
          <textarea rows="3" id="message" name="message" required></textarea>
          <span id="message_msg" style="display:none;"></span>
        </div>
      </div>
         <input type="hidden" class="form-control" id="section" name="section" value="" required>
         <input type="hidden" class="form-control" id="pageUrl" name="pageUrl" value="" required>
         <input type="hidden" class="form-control" id="pageTitle" name="pageTitle" value="" required>

        <div class="col-12">
      <div class="form-group">
        <label for="acceptance">GDPR / Privacy Declaration*</label>
        <div class="checkbox">
          <label><input type="checkbox" name="remember" required> I accept the GDPR / Privacy Declaration of Test Inc</label>
        </div>
        <span id="acceptance_msg" style="display:none;"></span>
        </div>
      </div>

        <button type="submit" class="btn btn-default">Submit</button><div class="loading_gif"></div>
      </form>
      </div>`
</code>```

{"inlineMessage":"
We have received your request. We will get in
touch with you shortly.
"}

This part of response is from API which is doing a post request and received this as success.

Body:
I am trying to put the form back after 2 seconds of success message, for that I've sent the form html code along with API response, can someone help me to put the form code inside
 div after 2 seconds success message?

Also the response getting as html form is same form <form class="custom-popup-form">

jQuery:

jQuery( ".custom-popup-form" ).on( "submit", function( event ) {
  event.preventDefault();
  let sdata = jQuery( this ).serialize();

  jQuery.ajax({
      url: my_ajax_object.ajax_url,
      type: "post",
      cache: false,
      async: false,
      data: {
        action: "submit_huspot_dynamic_form",
        data: sdata
      },

      beforeSend: function () {
        var img_loading =
          '

';
        jQuery(".loading_gif").html(img_loading);
      },
      success: function (res) {
          console.log(res);
          jQuery(".loading_gif").hide();
          jQuery(".custom-popup-form-wrapper").html('
We have received your request. We will get in touch with you shortly.
');
      }
});

});

Response received:

    {"inlineMessage":"
We have received your request. We will get in touch with you shortly.
"}

    <form class="custom-popup-form">

          Email*
          <input type="email" class="form-control" id="email" name="email" required>

          Phone Number*
          <input type="text" class="form-control" id="phone_number" name="phone_number" required>

          First Name*
          <input type="text" class="form-control" id="first_name" name="first_name" required>

           Last Name*
          <input type="text" class="form-control" id="last_name" name="last_name" required>

          Company name*
          <input type="text" class="form-control" id="company_name" name="company_name" required>

           Designation*
          <input type="text" class="form-control" id="designation" name="designation" required>

           Message*
          <textarea rows="3" id="message" name="message" required></textarea>

         <input type="hidden" class="form-control" id="section" name="section" value="" required>
         <input type="hidden" class="form-control" id="pageUrl" name="pageUrl" value="" required>
         <input type="hidden" class="form-control" id="pageTitle" name="pageTitle" value="" required>

        GDPR / Privacy Declaration*

          <input type="checkbox" name="remember" required> I accept the GDPR / Privacy Declaration of Test Inc

        <button type="submit" class="btn btn-default">Submit</button>

      </form>

`

{"inlineMessage":"
We have received your request. We will get in
touch with you shortly.
"}

This part of response is from API which is doing a post request and received this as success.


问:
Filter elements in Nuxt Vue 3 slot filtering by type
I created my personal form and now I need to get specific type elements in my slot. This is my code:

<template>
  <form @submit="validation">
    <slot></slot>
  </form>
</template>
```
<p>Everything seems ok but now I have this compilation error:</p>
```[vite-node] Failed to load /.nuxt/components

at ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:198:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ViteNodeRunner.cachedRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:146:12)
at async request (/C:/_______/node_modules/vite-node/dist/client.mjs:169:16)
at async C:/_______/components/eform.vue:5:31
at async ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:270:5)
at async ViteNodeRunner.cachedRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:146:12)
at async request (/C:/_______/node_modules/vite-node/dist/client.mjs:169:16)
at async virtual:nuxt:C:/_______/.nuxt/components.server.mjs:83:32
at async ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:270:5)
```
<p>The problem is on this piece of code:</p>
<pre class="lang-js prettyprint-override"><code>slot.default().filter(x => x.type == InputText);
</code>```

When I remove InputText the building issues disappear. InputText is another component created in the same way.

Body:
I created my personal form and now I need to get specific type elements in my slot. This is my code:

<template>
  <form @submit="validation">
    <slot></slot>
  </form>
</template>

Everything seems ok but now I have this compilation error:

[vite-node] Failed to load /.nuxt/components

at ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:198:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ViteNodeRunner.cachedRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:146:12)
at async request (/C:/_______/node_modules/vite-node/dist/client.mjs:169:16)
at async C:/_______/components/eform.vue:5:31
at async ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:270:5)
at async ViteNodeRunner.cachedRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:146:12)
at async request (/C:/_______/node_modules/vite-node/dist/client.mjs:169:16)
at async virtual:nuxt:C:/_______/.nuxt/components.server.mjs:83:32
at async ViteNodeRunner.directRequest (/C:/_______/node_modules/vite-node/dist/client.mjs:270:5)

The problem is on this piece of code:

slot.default().filter(x => x.type == InputText);

When I remove InputText the building issues disappear. InputText is another component created in the same way.


问:
How to use function parameters to access an object's element
I am trying to pass a parameter to function to access an object's element but keep getting ReferrenceError:obj is not defined

const obj = {
  'man1': 1,
  'man2': 2,
  'man3': 3
}

function test(i) {
  console.log(obj.man `${i}`)
}
test(1)
test(2)
test(3)```


问:
Exception on "add_roles" function for discord.py
I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?

Codes there:

```<code>@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.message_id == 0000:
        guild: discord.Guild = client.get_guild(payload.guild_id)
        if payload.emoji.name == "someEmoji":
            role0: discord.Role = guild.get_role(1111)
            await payload.member.add_roles(role0)
        elif payload.emoji.name == "someEmoji":
            role1: discord.Role = guild.get_role(2222)
            await payload.member.add_roles(role1)
</code>```

Logs(With pysnooper):

```<code>19:50:26.101973 line        54                 await member.add_roles(role1)
19:50:26.104641 return      54                 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call        54                 await member.add_roles(role1)
19:50:26.590784 exception   54                 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR   ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 54, in on_raw_reaction_remove
    await member.remove_roles(en_role)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
    start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>
</code>```

Body:
I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?

Codes there:

@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.message_id == 0000:
        guild: discord.Guild = client.get_guild(payload.guild_id)
        if payload.emoji.name == "someEmoji":
            role0: discord.Role = guild.get_role(1111)
            await payload.member.add_roles(role0)
        elif payload.emoji.name == "someEmoji":
            role1: discord.Role = guild.get_role(2222)
            await payload.member.add_roles(role1)

Logs(With pysnooper):

19:50:26.101973 line        54                 await member.add_roles(role1)
19:50:26.104641 return      54                 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call        54                 await member.add_roles(role1)
19:50:26.590784 exception   54                 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR   ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 54, in on_raw_reaction_remove
    await member.remove_roles(en_role)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
    start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>


问:
can we use material3 motion transition patterns in navigation graph XML?
i've been using custom enter and exit animations for actions in my nav graph. but i want to use Container Transform
for the navigation, can i use it in my XML directly?

```<code><fragment
    android:id="@+id/placeSearch"
    android:name="com.dr.kuldeep.ui.places.PlaceSearch"
    android:label="fragment_place_search"
    tools:layout="@layout/fragment_place_search" >
    <action
        android:id="@+id/action_placeSearch_to_placeDetails"
        app:enterAnim="@anim/from_right"
        app:exitAnim="@anim/to_left"
        app:popEnterAnim="@anim/from_left"
        app:popExitAnim="@anim/to_right"
        app:destination="@id/placeDetails" />
</fragment>
</code>```

i'm a newbie in android development sorry if my question sounds dumb i've looked for a solution but coudn't find a way to use it directly in XML. thanks in advance!

Body:
i've been using custom enter and exit animations for actions in my nav graph. but i want to use Container Transform
for the navigation, can i use it in my XML directly?

<fragment
    android:id="@+id/placeSearch"
    android:name="com.dr.kuldeep.ui.places.PlaceSearch"
    android:label="fragment_place_search"
    tools:layout="@layout/fragment_place_search" >
    <action
        android:id="@+id/action_placeSearch_to_placeDetails"
        app:enterAnim="@anim/from_right"
        app:exitAnim="@anim/to_left"
        app:popEnterAnim="@anim/from_left"
        app:popExitAnim="@anim/to_right"
        app:destination="@id/placeDetails" />
</fragment>

i'm a newbie in android development sorry if my question sounds dumb i've looked for a solution but coudn't find a way to use it directly in XML. thanks in advance!


问:
Mongoose 6 - How to get only the custom validation error message without the error?
```<code>const userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: [true, 'Email address is required'],
        minlength: [4, 'Must be at least 4 characters long']
    }
});
</code>```

When I log the error I get:

```<code>User validation failed: email: Must be at least 4 characters long
</code>```

How can I get only my custom message:

```<code>Must be at least 4 characters long
</code>```

The only thing I do as of now is

```<code>const messageString = message.split(':');
messageString[3]
</code>```

But is there a better way? I saw some solutions for this but its all for mongoose version 5 or less and it doesnt apply to version 6 as the error object has different properties.

On a side note (maybe this should be a seperate question) but as the error object is different now, how can I check if its a mongoose validation error? The err object doesnt come with it anymore.

```<code> Error: User validation failed: email: Must be at least 4 characters long
    at ValidationError.inspect (/Users/... {
  errors: {
    email: ValidatorError: Must be at least 4 characters long
        at validate (/Users/user/....
        at processTicksAndRejections (node:internal/process/task_queues:78:11) {
      properties: [Object],
      kind: 'minlength',
      path: 'email',
      value: 'hgg',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'
}
</code>```

Also, I dont want to have to access the modal property 'email' when accessing any other property as in my errorhandler, I want to keep it reusable for other errors too

Body:
const userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: [true, 'Email address is required'],
        minlength: [4, 'Must be at least 4 characters long']
    }
});

When I log the error I get:

User validation failed: email: Must be at least 4 characters long

How can I get only my custom message:

Must be at least 4 characters long

The only thing I do as of now is

const messageString = message.split(':');
messageString[3]

But is there a better way? I saw some solutions for this but its all for mongoose version 5 or less and it doesnt apply to version 6 as the error object has different properties.

On a side note (maybe this should be a seperate question) but as the error object is different now, how can I check if its a mongoose validation error? The err object doesnt come with it anymore.

 Error: User validation failed: email: Must be at least 4 characters long
    at ValidationError.inspect (/Users/... {
  errors: {
    email: ValidatorError: Must be at least 4 characters long
        at validate (/Users/user/....
        at processTicksAndRejections (node:internal/process/task_queues:78:11) {
      properties: [Object],
      kind: 'minlength',
      path: 'email',
      value: 'hgg',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'
}

Also, I dont want to have to access the modal property 'email' when accessing any other property as in my errorhandler, I want to keep it reusable for other errors too


问:
Exception thrown when using python in for-loop in C++-script
I have a C++ script that I run in Visual studio 2022 on windows 10 and where I include the python module. In the code I import numpy in a for-loop. The code executes fine the first round, but in the second round and exception is thrown as soon as the code tries to execute the import statement. I have googled for the error and searched for similar issues on stackOverflow but not found any solution. I have also isolated the error and made a minimal example. Here is the code from the example:

```<code>#include <C:\Program Files\Python39\include\Python.h>
#include <iostream>

using namespace std;

int main() {

    for (int i = 0; i < 5; i++) {
        cout << i << endl;

        Py_Initialize();
        PyRun_SimpleString("import numpy as np");
        PyRun_SimpleString("arr = np.array([1,2,3])");
        PyRun_SimpleString("print(arr)");
        Py_Finalize();

    }
}

</code>```

This is the output from the console when running the code:

```<code>0
[1 2 3]
1
Traceback (most recent call last):
  File "<string>", line 1, in <module>
</code>```

Here is the error message in visual studio:

```<code>Exception thrown at 0x00007FFCB9461319 (_multiarray_umath.cp39-win_amd64.pyd) in App4.exe: 0xC0000005: Access violation writing location 0x0000000000000008.
</code>```

What could be going on here and how can I solve it?

Body:
I have a C++ script that I run in Visual studio 2022 on windows 10 and where I include the python module. In the code I import numpy in a for-loop. The code executes fine the first round, but in the second round and exception is thrown as soon as the code tries to execute the import statement. I have googled for the error and searched for similar issues on stackOverflow but not found any solution. I have also isolated the error and made a minimal example. Here is the code from the example:

#include <C:\Program Files\Python39\include\Python.h>
#include <iostream>

using namespace std;

int main() {

    for (int i = 0; i < 5; i++) {
        cout << i << endl;

        Py_Initialize();
        PyRun_SimpleString("import numpy as np");
        PyRun_SimpleString("arr = np.array([1,2,3])");
        PyRun_SimpleString("print(arr)");
        Py_Finalize();

    }
}

This is the output from the console when running the code:

0
[1 2 3]
1
Traceback (most recent call last):
  File "<string>", line 1, in <module>

Here is the error message in visual studio:

Exception thrown at 0x00007FFCB9461319 (_multiarray_umath.cp39-win_amd64.pyd) in App4.exe: 0xC0000005: Access violation writing location 0x0000000000000008.

What could be going on here and how can I solve it?


问:
How to use one query instead of subqueries with CONCAT() function?

SELECT entID,entHelmName, ecnID  FROM `tblentries`
JOIN `tblCategories` ON ecnEvent = entEvent
WHERE ecnEvent = 52 AND
CONCAT(entID,'#',ecnID) NOT IN (SELECT CONCAT(ecyEntry,'#',eciCategory)  FROM `tblentryCategories` JOIN tblcategoryitems ON eciID = ecyItem JOIN tblEntries ON ecyEntry = entID WHERE entEvent = 52);
```
<pre class="lang-none prettyprint-override"><code>entID   entHelmName ecnID
1661    Bernice Hulme   27
1661    Bernice Hulme   28
1654    Bill Kenyon     28
1655    David Morris    28
</code>```

Context:
There are Events, which sailors can enter to race (and are scored).
Sailors can be assigned values in categories which are specific to each event.

Example: in Event 52 Categories are called Fleet=27 and Division=28
(Fleet values are Silver,Gold, Division values are Adult,Junior)

Bernice has no choice set for either Fleet or Division so 2 rows in results

Bill is in "Gold Fleet" but has no choice set for Division

David  is in "Silver Fleet" but has no choice set for Division

Here are the table contents, table structures below.
(Note foreign keys on tblentrycategories  ecyEntry->entID and ecyItem->eciID, and tblCategories ecnID->eciCategory)

Table content (showing relevant rows only)

tblntries:

```<code>SELECT `entID`, `entEvent`, `entHelmName`
FROM `tblentries`
WHERE entEvent=52;
</code>```

entID entEvent  entHelmName
1661    52  Bernice
1654    52  Bill
1655    52  David
1653    52  Deborah
1662    52  Michaela
```
<p>tblcategories:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM `tblcategories`
WHERE `ecnEvent`=52;
</code>```

ecnID ecnEvent  ecnName
28  52  Division
27  52  Fleet
```
<p>tblcategoryitems:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM `tblcategoryitems`
WHERE `eciCategory` IN (27,28);
</code>```

eciID eciCategory eciValue
55  27  Gold
54  27  Silver
57  28  Adult
56  28  Junior
```
<p>tblentrycategories:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT `tblentrycategories`.*, `entID`,`entEvent`,`entHelmName`
FROM `tblentrycategories`
JOIN `tblentries`
WHERE `ecyEntry` = `entID` AND `entEvent` = 52;
</code>```

ecyEntry ecyItem    entID   entEvent entHelmName
1654    55      1654    52  Bill
1655    54      1655    52  David
1653    55      1653    52  Deborah
1653    57      1653    52  Deborah
1662    54      1662    52  Michaela
1662    56      1662    52  Michaela
```
<hr />
<p>Table structures:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE `tblentries` (
  `entID` int(11) NOT NULL AUTO_INCREMENT,
  `entSeries` int(11) DEFAULT NULL,
  `entEvent` int(11) NOT NULL,
  `entHelmName` varchar(50) NOT NULL,
  `entClub` varchar(50) DEFAULT NULL,
  `entClass` int(11) NOT NULL,
  PRIMARY KEY (`entID`),
  UNIQUE KEY `ixentEventHelmClassFleet` (`entEvent`,`entSeries`,`entHelmName`,`entFleet`,`entClass`),
  CONSTRAINT `fkentEvent` FOREIGN KEY (`entEvent`) REFERENCES `tblevents` (`evtID`),
) ENGINE=InnoDB AUTO_INCREMENT=1589 DEFAULT CHARSET=utf8;
</code>```

CREATE TABLE `tblcategories` (
  `ecnID` int(11) NOT NULL AUTO_INCREMENT,
  `ecnEvent` int(11) NOT NULL,
  `ecnName` varchar(50) NOT NULL,
  PRIMARY KEY (`ecnID`),
  UNIQUE KEY `ixecnEventName` (`ecnEvent`,`ecnName`),
  KEY `ixecnEvent` (`ecnEvent`),
  CONSTRAINT `fkecnEvent` FOREIGN KEY (`ecnEvent`) REFERENCES `tblevents` (`evtID`),
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
```
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE `tblcategoryitems` (
  `eciID` int(11) NOT NULL AUTO_INCREMENT,
  `eciCategory` int(11) NOT NULL,
  `eciValue` varchar(50) NOT NULL,
  PRIMARY KEY (`eciID`),
  UNIQUE KEY `ixeciCategoryValue` (`eciCategory`,`eciValue`),
  KEY `ixeciCategory` (`eciCategory`),
  CONSTRAINT `fkeciCategory` FOREIGN KEY (`eciCategory`) REFERENCES `tblcategories` (`ecnID`),
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;
</code>```

CREATE TABLE `tblentrycategories` (
  `ecyEntry` int(11) NOT NULL DEFAULT 0,
  `ecyItem` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`ecyEntry`,`ecyItem`),
  KEY `ixecyEntry` (`ecyEntry`),
  KEY `ixecyItem` (`ecyItem`),
  CONSTRAINT `fkecyEntry` FOREIGN KEY (`ecyEntry`) REFERENCES `tblentries` (`entID`),
  CONSTRAINT `fkecyItem` FOREIGN KEY (`ecyItem`) REFERENCES `tblcategoryitems` (`eciID`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```

Body:
SELECT entID,entHelmName, ecnID  FROM `tblentries`
JOIN `tblCategories` ON ecnEvent = entEvent
WHERE ecnEvent = 52 AND
CONCAT(entID,'#',ecnID) NOT IN (SELECT CONCAT(ecyEntry,'#',eciCategory)  FROM `tblentryCategories` JOIN tblcategoryitems ON eciID = ecyItem JOIN tblEntries ON ecyEntry = entID WHERE entEvent = 52);

entID   entHelmName ecnID
1661    Bernice Hulme   27
1661    Bernice Hulme   28
1654    Bill Kenyon     28
1655    David Morris    28

Context:
There are Events, which sailors can enter to race (and are scored).
Sailors can be assigned values in categories which are specific to each event.

Example: in Event 52 Categories are called Fleet=27 and Division=28
(Fleet values are Silver,Gold, Division values are Adult,Junior)

Bernice has no choice set for either Fleet or Division so 2 rows in results

Bill is in "Gold Fleet" but has no choice set for Division

David  is in "Silver Fleet" but has no choice set for Division

Here are the table contents, table structures below.
(Note foreign keys on tblentrycategories  ecyEntry->entID and ecyItem->eciID, and tblCategories ecnID->eciCategory)

Table content (showing relevant rows only)

tblntries:

SELECT `entID`, `entEvent`, `entHelmName`
FROM `tblentries`
WHERE entEvent=52;

entID entEvent  entHelmName
1661    52  Bernice
1654    52  Bill
1655    52  David
1653    52  Deborah
1662    52  Michaela

tblcategories:

SELECT *
FROM `tblcategories`
WHERE `ecnEvent`=52;

ecnID ecnEvent  ecnName
28  52  Division
27  52  Fleet

tblcategoryitems:

SELECT *
FROM `tblcategoryitems`
WHERE `eciCategory` IN (27,28);

eciID eciCategory eciValue
55  27  Gold
54  27  Silver
57  28  Adult
56  28  Junior

tblentrycategories:

SELECT `tblentrycategories`.*, `entID`,`entEvent`,`entHelmName`
FROM `tblentrycategories`
JOIN `tblentries`
WHERE `ecyEntry` = `entID` AND `entEvent` = 52;

ecyEntry ecyItem    entID   entEvent entHelmName
1654    55      1654    52  Bill
1655    54      1655    52  David
1653    55      1653    52  Deborah
1653    57      1653    52  Deborah
1662    54      1662    52  Michaela
1662    56      1662    52  Michaela

Table structures:

CREATE TABLE `tblentries` (
  `entID` int(11) NOT NULL AUTO_INCREMENT,
  `entSeries` int(11) DEFAULT NULL,
  `entEvent` int(11) NOT NULL,
  `entHelmName` varchar(50) NOT NULL,
  `entClub` varchar(50) DEFAULT NULL,
  `entClass` int(11) NOT NULL,
  PRIMARY KEY (`entID`),
  UNIQUE KEY `ixentEventHelmClassFleet` (`entEvent`,`entSeries`,`entHelmName`,`entFleet`,`entClass`),
  CONSTRAINT `fkentEvent` FOREIGN KEY (`entEvent`) REFERENCES `tblevents` (`evtID`),
) ENGINE=InnoDB AUTO_INCREMENT=1589 DEFAULT CHARSET=utf8;

CREATE TABLE `tblcategories` (
  `ecnID` int(11) NOT NULL AUTO_INCREMENT,
  `ecnEvent` int(11) NOT NULL,
  `ecnName` varchar(50) NOT NULL,
  PRIMARY KEY (`ecnID`),
  UNIQUE KEY `ixecnEventName` (`ecnEvent`,`ecnName`),
  KEY `ixecnEvent` (`ecnEvent`),
  CONSTRAINT `fkecnEvent` FOREIGN KEY (`ecnEvent`) REFERENCES `tblevents` (`evtID`),
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

CREATE TABLE `tblcategoryitems` (
  `eciID` int(11) NOT NULL AUTO_INCREMENT,
  `eciCategory` int(11) NOT NULL,
  `eciValue` varchar(50) NOT NULL,
  PRIMARY KEY (`eciID`),
  UNIQUE KEY `ixeciCategoryValue` (`eciCategory`,`eciValue`),
  KEY `ixeciCategory` (`eciCategory`),
  CONSTRAINT `fkeciCategory` FOREIGN KEY (`eciCategory`) REFERENCES `tblcategories` (`ecnID`),
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8;

CREATE TABLE `tblentrycategories` (
  `ecyEntry` int(11) NOT NULL DEFAULT 0,
  `ecyItem` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`ecyEntry`,`ecyItem`),
  KEY `ixecyEntry` (`ecyEntry`),
  KEY `ixecyItem` (`ecyItem`),
  CONSTRAINT `fkecyEntry` FOREIGN KEY (`ecyEntry`) REFERENCES `tblentries` (`entID`),
  CONSTRAINT `fkecyItem` FOREIGN KEY (`ecyItem`) REFERENCES `tblcategoryitems` (`eciID`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


问:
Encrypted output is different in openssl command and openssl C Program
I wrote a simple openssl program to perform 'AES-128-CBC' encryption.

```<code>#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#define KEY_SIZE 16
#define IV_SIZE 16

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

void hexdump(const void* data, size_t size) {
    char ascii[17];
    size_t i, j;
    ascii[16] = '\0';
    for (i = 0; i < size; ++i) {
        printf("%02X ", ((unsigned char*)data)[i]);
        if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
            ascii[i % 16] = ((unsigned char*)data)[i];
        } else {
            ascii[i % 16] = '.';
        }
        if ((i+1) % 8 == 0 || i+1 == size) {
            printf(" ");
            if ((i+1) % 16 == 0) {
                printf("|  %s \n", ascii);
            } else if (i+1 == size) {
                ascii[(i+1) % 16] = '\0';
                if ((i+1) % 16 <= 8) {
                    printf(" ");
                }
                for (j = (i+1) % 16; j < 16; ++j) {
                    printf("   ");
                }
                printf("|  %s \n", ascii);
            }
        }
    }
}

int encrypt_file(void)
{
    EVP_CIPHER_CTX *ctx;
    char plain_text[12] = "Hello World";
    size_t plaintext_len = 12;
    unsigned char *ciphertext = NULL;
    int ciphertext_maxlen = plaintext_len + EVP_CIPHER_block_size(EVP_aes_128_cbc())*2 - 1;
    int len  = 0, ciphertext_len = 0;
    ciphertext = (unsigned char *)malloc(ciphertext_maxlen * sizeof(unsigned char));

    unsigned char key[KEY_SIZE]= {0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11};
    unsigned char iv[IV_SIZE] = {0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22};
    hexdump(key, 16);
    hexdump(iv, 16);

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
        handleErrors();

    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plain_text, plaintext_len))
        handleErrors();

    ciphertext_len = len;
    if( EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1 )
        handleErrors();

    ciphertext_len += len;

    printf("ciphertext len:%d\n", ciphertext_len);

    EVP_CIPHER_CTX_free(ctx);
    hexdump(ciphertext, ciphertext_len);
    free(ciphertext);
    return 0;

}

int main(int argc, char *argv[])
{
    encrypt_file();
    return 0;
}
</code>```

When i am running this program it's generating cipher text.

```<code>11 11 11 11 11 11 11 11  11 11 11 11 11 11 11 11  |  ................
22 22 22 22 22 22 22 22  22 22 22 22 22 22 22 22  |  """"""""""""""""
ciphertext len:16
4F 55 95 1F D9 A6 34 F1  2F 90 06 2B 82 F8 C2 19  |  OU....4./..+....
</code>```

I am trying to verify whether my C code is working fine or not by passing the same parameters to openssl commands

```<code>jamal@jamal-VirtualBox:~$ echo "Hello World" > plaintext.txt
jamal@jamal-VirtualBox:~$ cat plaintext.txt
Hello World
jamal@jamal-VirtualBox:~$ openssl enc -aes-128-cbc -in plaintext.txt -K '11111111111111111111111111111111' -iv '22222222222222222222222222222222' -out openssl_enc.txt -p
salt=F3753875307F0000
key=11111111111111111111111111111111
iv =22222222222222222222222222222222
jamal@jamal-VirtualBox:~$ hexdump openssl_enc.txt
0000000 ea60 4e8e a289 ea50 ee19 0edc 81ea 557d
0000010
</code>```

Why is the cipher bytes generated by C code not same as the one generated by openssl command. Am i missing anything in Code?

Body:
I wrote a simple openssl program to perform 'AES-128-CBC' encryption.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#define KEY_SIZE 16
#define IV_SIZE 16

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

void hexdump(const void* data, size_t size) {
    char ascii[17];
    size_t i, j;
    ascii[16] = '\0';
    for (i = 0; i < size; ++i) {
        printf("%02X ", ((unsigned char*)data)[i]);
        if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
            ascii[i % 16] = ((unsigned char*)data)[i];
        } else {
            ascii[i % 16] = '.';
        }
        if ((i+1) % 8 == 0 || i+1 == size) {
            printf(" ");
            if ((i+1) % 16 == 0) {
                printf("|  %s \n", ascii);
            } else if (i+1 == size) {
                ascii[(i+1) % 16] = '\0';
                if ((i+1) % 16 <= 8) {
                    printf(" ");
                }
                for (j = (i+1) % 16; j < 16; ++j) {
                    printf("   ");
                }
                printf("|  %s \n", ascii);
            }
        }
    }
}

int encrypt_file(void)
{
    EVP_CIPHER_CTX *ctx;
    char plain_text[12] = "Hello World";
    size_t plaintext_len = 12;
    unsigned char *ciphertext = NULL;
    int ciphertext_maxlen = plaintext_len + EVP_CIPHER_block_size(EVP_aes_128_cbc())*2 - 1;
    int len  = 0, ciphertext_len = 0;
    ciphertext = (unsigned char *)malloc(ciphertext_maxlen * sizeof(unsigned char));

    unsigned char key[KEY_SIZE]= {0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11};
    unsigned char iv[IV_SIZE] = {0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22};
    hexdump(key, 16);
    hexdump(iv, 16);

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
        handleErrors();

    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plain_text, plaintext_len))
        handleErrors();

    ciphertext_len = len;
    if( EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1 )
        handleErrors();

    ciphertext_len += len;

    printf("ciphertext len:%d\n", ciphertext_len);

    EVP_CIPHER_CTX_free(ctx);
    hexdump(ciphertext, ciphertext_len);
    free(ciphertext);
    return 0;

}

int main(int argc, char *argv[])
{
    encrypt_file();
    return 0;
}

When i am running this program it's generating cipher text.

11 11 11 11 11 11 11 11  11 11 11 11 11 11 11 11  |  ................
22 22 22 22 22 22 22 22  22 22 22 22 22 22 22 22  |  """"""""""""""""
ciphertext len:16
4F 55 95 1F D9 A6 34 F1  2F 90 06 2B 82 F8 C2 19  |  OU....4./..+....

I am trying to verify whether my C code is working fine or not by passing the same parameters to openssl commands

jamal@jamal-VirtualBox:~$ echo "Hello World" > plaintext.txt
jamal@jamal-VirtualBox:~$ cat plaintext.txt
Hello World
jamal@jamal-VirtualBox:~$ openssl enc -aes-128-cbc -in plaintext.txt -K '11111111111111111111111111111111' -iv '22222222222222222222222222222222' -out openssl_enc.txt -p
salt=F3753875307F0000
key=11111111111111111111111111111111
iv =22222222222222222222222222222222
jamal@jamal-VirtualBox:~$ hexdump openssl_enc.txt
0000000 ea60 4e8e a289 ea50 ee19 0edc 81ea 557d
0000010

Why is the cipher bytes generated by C code not same as the one generated by openssl command. Am i missing anything in Code?


问:
Error: Missing target element || Stimulus 1.1.1 Rails 6
I have this error 'Error: Missing target element' in console when i try to select one target.

The main idea here is to iterate through an array of web_servers and select for each controllers, a target within each instance.(the value is_available will change continuously, and I want to use action cable to monitor it).

My stimulus controller:

```<code>import { Controller } from "stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["status"];

  connect() {
    console.log('Will create subscription to: channel: "ScanServersStatusChannel" web_server_id: ' + this.data.get('id'));

    this.channel = consumer.subscriptions.create({ channel: 'ScanServersStatusChannel', web_server_id: this.data.get('id') }, {
      connected: this._cableConnected.bind(this),
      disconnected: this._cableDisconnected.bind(this),
      received: this._cableReceived.bind(this),
    });
  }

  _cableConnected() {
    // Called when the subscription is ready for use on the server
    console.log('_cableConnected');
    console.log(this.statusTarget);

  }

  _cableDisconnected() {
    // Called when the subscription has been terminated by the server
    console.log('_cableDisconnected');
  }

  _cableReceived(data) {
    // Called when incoming data from websocket
    const element = this.statusTarget
    element.innerHTML = data
  }
}
</code>```

My view:

```<code><% @web_servers.each do |web_server, index| %>
  <div data-controller="serverstatus" data-serverstatus-id="<%= web_server.id %>">
      <tbody class="accordion">
        <tr>
          <td id="web-server-id"><%= web_server.id %></td>
          <td><%= web_server.port_number %></td>
          <td><%= web_server.address %></td>
          <div data-target="serverstatus.status">
            <td><%= render 'admin/dashboards/web_servers/web_server_status', web_server: web_server%></td>
          </div>
        </tr>
      </tbody>
  </div>
<% end %>
</code>```

Inside the partial:

```<code><span ><%= web_server.is_available ? 'Disponible' : 'Non disponible' %></span>
</code>```

Body:
I have this error 'Error: Missing target element' in console when i try to select one target.

The main idea here is to iterate through an array of web_servers and select for each controllers, a target within each instance.(the value is_available will change continuously, and I want to use action cable to monitor it).

My stimulus controller:

import { Controller } from "stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["status"];

  connect() {
    console.log('Will create subscription to: channel: "ScanServersStatusChannel" web_server_id: ' + this.data.get('id'));

    this.channel = consumer.subscriptions.create({ channel: 'ScanServersStatusChannel', web_server_id: this.data.get('id') }, {
      connected: this._cableConnected.bind(this),
      disconnected: this._cableDisconnected.bind(this),
      received: this._cableReceived.bind(this),
    });
  }

  _cableConnected() {
    // Called when the subscription is ready for use on the server
    console.log('_cableConnected');
    console.log(this.statusTarget);

  }

  _cableDisconnected() {
    // Called when the subscription has been terminated by the server
    console.log('_cableDisconnected');
  }

  _cableReceived(data) {
    // Called when incoming data from websocket
    const element = this.statusTarget
    element.innerHTML = data
  }
}

My view:

<% @web_servers.each do |web_server, index| %>
  <div data-controller="serverstatus" data-serverstatus-id="<%= web_server.id %>">

          <%= web_server.id %>
          <%= web_server.port_number %>
          <%= web_server.address %>

            <%= render 'admin/dashboards/web_servers/web_server_status', web_server: web_server%>

<% end %>

Inside the partial:

<%= web_server.is_available ? 'Disponible' : 'Non disponible' %>


问:
How adding ticket attachments with the Zendesk API using vba in Access
I'm unfortunately trying to upload localfile like "H:\Book1.pdf" size arround 150KB to zendesk from Access VBA
Attachement is a 2 step method, I need your help on the first "Uploading the file you want to attach"; the documentation indicate the need to use --data-binary in Curl ...I feel this is the issue. how to reproduce that in vba ?

```<code>Public Function ZendeskTicketAttachementStep1()

    Dim xml_Https As New MSXML2.XMLHTTP60
    Dim xml_Resp As MSXML2.DOMDocument60
    Set xml_Resp = New MSXML2.DOMDocument60
    Dim xml_Value As MSXML2.IXMLDOMNode

    xml_Https.Open "POST", "https://support.zendesk.com/api/v2/uploads?filename=test.pdf", False

    xml_Https.setRequestHeader "Content-Type", "application/pdf"
    xml_Https.Send ("H:\Book1.pdf")

    Debug.Print xml_Https.responseText

End Function
</code>```

Unfortunately the response show that something whent wrong ; the file has not been upload :

```<code>{
  "upload": {
    "token": "1P05PdGDCY4jJbVoQ9VtOvQaZ",
    "expires_at": "2022-12-23T12:03:22Z",
    "attachments": [
      {
        "url": "https://support.zendesk.com/api/v2/attachments/5241457262746.json",
        "id": 5241457262746,
        "file_name": "test.pdf",
        "content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
        "mapped_content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
        "content_type": "application/pdf",
        "size": 12,
        "width": null,
        "height": null,
        "inline": false,
        "deleted": false,
        "malware_access_override": false,
        "malware_scan_result": "not_scanned",
        "thumbnails": [
        ]
      }
    ],
    "attachment": {
      "url": "https://support.zendesk.com/api/v2/attachments/5241457262746.json",
      "id": 5241457262746,
      "file_name": "test.pdf",
      "content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
      "mapped_content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
      "content_type": "application/pdf",
      "size": 12,
      "width": null,
      "height": null,
      "inline": false,
      "deleted": false,
      "malware_access_override": false,
      "malware_scan_result": "not_scanned",
      "thumbnails": [
      ]
    }
  }
}
</code>```

I have the feeling that i cannot send the file directly; seems that i need to do something before... I guess someone can helpme .

Not sure, Look like I miss to "convert" the file to binary before POST

I'm trying to have the file uploaded

Thank's

Body:
I'm unfortunately trying to upload localfile like "H:\Book1.pdf" size arround 150KB to zendesk from Access VBA
Attachement is a 2 step method, I need your help on the first "Uploading the file you want to attach"; the documentation indicate the need to use --data-binary in Curl ...I feel this is the issue. how to reproduce that in vba ?

Public Function ZendeskTicketAttachementStep1()

    Dim xml_Https As New MSXML2.XMLHTTP60
    Dim xml_Resp As MSXML2.DOMDocument60
    Set xml_Resp = New MSXML2.DOMDocument60
    Dim xml_Value As MSXML2.IXMLDOMNode

    xml_Https.Open "POST", "https://support.zendesk.com/api/v2/uploads?filename=test.pdf", False

    xml_Https.setRequestHeader "Content-Type", "application/pdf"
    xml_Https.Send ("H:\Book1.pdf")

    Debug.Print xml_Https.responseText

End Function

Unfortunately the response show that something whent wrong ; the file has not been upload :

{
  "upload": {
    "token": "1P05PdGDCY4jJbVoQ9VtOvQaZ",
    "expires_at": "2022-12-23T12:03:22Z",
    "attachments": [
      {
        "url": "https://support.zendesk.com/api/v2/attachments/5241457262746.json",
        "id": 5241457262746,
        "file_name": "test.pdf",
        "content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
        "mapped_content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
        "content_type": "application/pdf",
        "size": 12,
        "width": null,
        "height": null,
        "inline": false,
        "deleted": false,
        "malware_access_override": false,
        "malware_scan_result": "not_scanned",
        "thumbnails": [
        ]
      }
    ],
    "attachment": {
      "url": "https://support.zendesk.com/api/v2/attachments/5241457262746.json",
      "id": 5241457262746,
      "file_name": "test.pdf",
      "content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
      "mapped_content_url": "https://support.zendesk.com/attachments/token/1zhdP1qlBKonSpJWXebvcumtg/?name=test.pdf",
      "content_type": "application/pdf",
      "size": 12,
      "width": null,
      "height": null,
      "inline": false,
      "deleted": false,
      "malware_access_override": false,
      "malware_scan_result": "not_scanned",
      "thumbnails": [
      ]
    }
  }
}

I have the feeling that i cannot send the file directly; seems that i need to do something before... I guess someone can helpme .

Not sure, Look like I miss to "convert" the file to binary before POST

I'm trying to have the file uploaded

Thank's


问:
Laravel OCI8 : Getting syntax error, unexpected '|', expecting ';' or '{' on OCI8.php
I'm setting up my a docker container with PHP 7.4 and OCI8

Im installing instantclient via zip file and unzipping it using the dockerfile.
it was successful in building and mounting but when i try to send a request to the controller it returns syntax error, unexpected '|', expecting ';' or '{' in /var/www/html/vendor/yajra/laravel-pdo-via-oci8/src/Pdo/Oci8.php (line 353).

does this mean oci8 was not install successfully or i'm my zip file for the instantclient is outdate? does anyone have an idea of this issue

Dockerfile for reference

```<code>    FROM composer:2.0 as vendor

COPY composer.json/ /app/composer.json
COPY docker/config/nginx.conf /app/nginx.conf

RUN composer install \
    --ignore-platform-reqs \
    --no-interaction \
    --no-plugins \
    --no-scripts \
    --no-ansi \
    --prefer-dist

FROM alpine:3.14
LABEL Maintainer="Christian Jay Bayno"

# Install packages
RUN apk --no-cache add php7 \
php7-fpm \
php7-phalcon \
php7-pdo_mysql \
php7-json \
php7-openssl \
php7-curl \
php7-tokenizer \
php7-dom \
php7-dev \
php7-opcache \
nginx \
supervisor \
curl \
git \
tzdata \
g++ \
gcc \
make \
libaio-dev \
libnsl \
gcompat

RUN ln -s /usr/lib/libnsl.so.2 /usr/lib/libnsl.so.1

# Install Instaclient and PDO OCI
RUN mkdir -p /opt/oci

COPY ./docker/oracle/instantclient-basic-19.17.0.0.0.zip /opt/oci
COPY ./docker/oracle/instantclient-sdk-19.17.0.0.0.zip /opt/oci
COPY ./docker/oracle/pdo_oci.zip /opt/oci
RUN cd /opt/oci \
    && unzip instantclient-basic-19.17.0.0.0.zip \
    && unzip instantclient-sdk-19.17.0.0.0.zip \
    && cd instantclient_19_17/ \
    && ln -s /opt/oci/instantclient_19_17/libclntsh.so.12.1 libclntsh.so \
    && ln -s /opt/oci/instantclient_19_17/libocci.so.12.1 libocci.so \
    && ls \
    && cd ../ \
    && unzip pdo_oci.zip \
    && cd pdo_oci \
    && phpize \
    && ./configure --with-pdo-oci=shared,instantclient,/opt/oci/instantclient_19_17 \
    && make \
    && make install \
    && echo "extension=oci8.so" >> /etc/php7/conf.d/pdo_oci.ini \
    && echo "extension=pdo_oci.so" >> /etc/php7/conf.d/pdo_oci.ini \
    && cd /opt/oci \
    && rm *.zip

# Configure Timezone
ENV TZ Asia/Manila

# Configure nginx
COPY docker/config/nginx.conf /etc/nginx/nginx.conf

# Configure PHP-FPM
COPY docker/config/fpm-pool.conf /etc/php7/php-fpm.d/www.conf
COPY docker/config/php.ini /etc/php7/conf.d/app.ini

# Configure supervisord
COPY docker/config/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Make sure files/folders needed by the processes are accessable when they run under the nobody user
RUN chown -R nobody.nobody /run && \
  chown -R nobody.nobody /var/lib/nginx && \
  chown -R nobody.nobody /var/log/nginx

# Set up document root
RUN mkdir -p /var/www/html

# Switch to use a non-root user from here on
USER nobody

# Add application
WORKDIR /var/www/html
COPY --chown=nobody . /var/www/html/
COPY --chown=nobody --from=vendor /app/vendor/ /var/www/html/vendor/

# Expose the port nginx is reachable on
EXPOSE 8085

# Let supervisord start nginx & php-fpm
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

# Configure a healthcheck to validate that everything is up&running
HEALTHCHECK --timeout=10s CMD curl --silent --fail http://127.0.0.1:8085/fpm-ping
</code>```

Body:
I'm setting up my a docker container with PHP 7.4 and OCI8

Im installing instantclient via zip file and unzipping it using the dockerfile.
it was successful in building and mounting but when i try to send a request to the controller it returns syntax error, unexpected '|', expecting ';' or '{' in /var/www/html/vendor/yajra/laravel-pdo-via-oci8/src/Pdo/Oci8.php (line 353).

does this mean oci8 was not install successfully or i'm my zip file for the instantclient is outdate? does anyone have an idea of this issue

Dockerfile for reference

    FROM composer:2.0 as vendor

COPY composer.json/ /app/composer.json
COPY docker/config/nginx.conf /app/nginx.conf

RUN composer install \
    --ignore-platform-reqs \
    --no-interaction \
    --no-plugins \
    --no-scripts \
    --no-ansi \
    --prefer-dist

FROM alpine:3.14
LABEL Maintainer="Christian Jay Bayno"

# Install packages
RUN apk --no-cache add php7 \
php7-fpm \
php7-phalcon \
php7-pdo_mysql \
php7-json \
php7-openssl \
php7-curl \
php7-tokenizer \
php7-dom \
php7-dev \
php7-opcache \
nginx \
supervisor \
curl \
git \
tzdata \
g++ \
gcc \
make \
libaio-dev \
libnsl \
gcompat

RUN ln -s /usr/lib/libnsl.so.2 /usr/lib/libnsl.so.1

# Install Instaclient and PDO OCI
RUN mkdir -p /opt/oci

COPY ./docker/oracle/instantclient-basic-19.17.0.0.0.zip /opt/oci
COPY ./docker/oracle/instantclient-sdk-19.17.0.0.0.zip /opt/oci
COPY ./docker/oracle/pdo_oci.zip /opt/oci
RUN cd /opt/oci \
    && unzip instantclient-basic-19.17.0.0.0.zip \
    && unzip instantclient-sdk-19.17.0.0.0.zip \
    && cd instantclient_19_17/ \
    && ln -s /opt/oci/instantclient_19_17/libclntsh.so.12.1 libclntsh.so \
    && ln -s /opt/oci/instantclient_19_17/libocci.so.12.1 libocci.so \
    && ls \
    && cd ../ \
    && unzip pdo_oci.zip \
    && cd pdo_oci \
    && phpize \
    && ./configure --with-pdo-oci=shared,instantclient,/opt/oci/instantclient_19_17 \
    && make \
    && make install \
    && echo "extension=oci8.so" >> /etc/php7/conf.d/pdo_oci.ini \
    && echo "extension=pdo_oci.so" >> /etc/php7/conf.d/pdo_oci.ini \
    && cd /opt/oci \
    && rm *.zip

# Configure Timezone
ENV TZ Asia/Manila

# Configure nginx
COPY docker/config/nginx.conf /etc/nginx/nginx.conf

# Configure PHP-FPM
COPY docker/config/fpm-pool.conf /etc/php7/php-fpm.d/www.conf
COPY docker/config/php.ini /etc/php7/conf.d/app.ini

# Configure supervisord
COPY docker/config/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Make sure files/folders needed by the processes are accessable when they run under the nobody user
RUN chown -R nobody.nobody /run && \
  chown -R nobody.nobody /var/lib/nginx && \
  chown -R nobody.nobody /var/log/nginx

# Set up document root
RUN mkdir -p /var/www/html

# Switch to use a non-root user from here on
USER nobody

# Add application
WORKDIR /var/www/html
COPY --chown=nobody . /var/www/html/
COPY --chown=nobody --from=vendor /app/vendor/ /var/www/html/vendor/

# Expose the port nginx is reachable on
EXPOSE 8085

# Let supervisord start nginx & php-fpm
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

# Configure a healthcheck to validate that everything is up&running
HEALTHCHECK --timeout=10s CMD curl --silent --fail http://127.0.0.1:8085/fpm-ping