问:
How to get specific errors from called sub functions in the catch block of the main function
A fews weeks ago I have asked a first question about this topic Catch errors when using async/await

My register function was getting pretty long and some parts of it are reusable for other controller functions so I decided to decompose the code into various reusable functions.

```<code>const findOrCreateEntity = async (req, next) => {
    let entity, entity_type;

    if(req.body.enterprise_number) {
        entity = await Company.findOne({ enterprise_number: req.body.enterprise_number });
        entity_type = 'Company';

        if(!entity) {
            return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}`, 400, 'company_not_found'));
        }
    } else {
        entity = await PrivatePerson.findOne({ email: req.body.email });
        entity_type = 'PrivatePerson';

        if(!entity) {
            [entity] = await PrivatePerson.create([{
                _id: mongoose.Types.ObjectId().toHexString(),
                ...req.body,
                source: req.app
            }], { session: req.session })
        }
    }

    return {
        entity, entity_type
    };
};

const createEnergyMandate = async (req, entity_id, entity_type, next) => {
    let energy_mandate;

    energy_mandate = await EnergyMandate.findOne({ entity: entity_id });

    if(energy_mandate) {
        return next(new ErrorResponse('Email already in use', `An account with the provided email address already exists. Please login instead.`, 409, 'email_already_in_use'));
    }

    let preferences = {
        push_notifications: true,
        sms_notifications: true,
        email_notifications: true
    }

    if(!req.app.notifications) {
        preferences = {
            push_notifications: false,
            sms_notifications: false,
            email_notifications: false
        }
    }

    [energy_mandate] = await EnergyMandate.create([{
        _id: mongoose.Types.ObjectId().toHexString(),
        entity: entity_id,
        start_date: Date.now(),
        status: 'edit_customer',
        legal: {
            privacy_policy_version: '2.1',
            privacy_policy_signed: true,
            privacy_policy_signed_at: Date.now(),
            privacy_policy_signed_from_ip: req.user_ip,

            general_conditions_version: '2.1',
            general_conditions_signed: true,
            general_conditions_signed_at: Date.now(),
            general_conditions_signed_from_ip: req.user_ip
        },
        preferences: preferences,
        sales_channel: req.app.channel
    }], { session: req.session });

    return energy_mandate;
}

export const register = asyncHandler(async (req, res, next) => {
    const session = await mongoose.startSession();
    session.startTransaction();

    req.session = session;

    try {
        // Find or create entity
        const { entity, entity_type } = await findOrCreateEntity(req, next);

        // Create energy mandate
        const energy_mandate = await createEnergyMandate(req, entity._id, entity_type, next);

        // Create auth0 user unless req.app.user is false
        if(!req.app.user) {
            auth0_user = await createAuth0User(req, next);
            auth0_uid = auth0_user.user_id;
        } else {
            auth0_uid = req.user.uid;
        }

        return res.status(200).json({
            message: 'User registered',
            data: {
                user_id: auth0_uid
            }
        });
    } catch (error) {
        await session.abortTransaction();

        if(auth0_user) {
            await auth0ManagementClient.deleteUser({
                id: auth0_user.user_id
            });
        }

        next(error);
    } finally {
        session.endSession();
    }
});
</code>```

As you can see there are some points where I use an ErrorResponse to write very specific errors like return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}</code>, 400, 'company_not_found'));`

Based on the previous question I asked and the answer I received, I should wrap each function in the register controller function into it's own try/catch block so the register function stops executing.

I've got two question about that:

How can I return the specific errors like return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}`, 400, 'company_not_found')); to the client but also calling the catch block.

Will the 'global catch' where the transaction is being aborted still be hit if I have all these smaller try/catch blocks? In other words will the main catch block of a try/catch be executed if the try/catch block has one or multiple try/catch blocks?

Body:
A fews weeks ago I have asked a first question about this topic Catch errors when using async/await

My register function was getting pretty long and some parts of it are reusable for other controller functions so I decided to decompose the code into various reusable functions.

const findOrCreateEntity = async (req, next) => {
    let entity, entity_type;

    if(req.body.enterprise_number) {
        entity = await Company.findOne({ enterprise_number: req.body.enterprise_number });
        entity_type = 'Company';

        if(!entity) {
            return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}`, 400, 'company_not_found'));
        }
    } else {
        entity = await PrivatePerson.findOne({ email: req.body.email });
        entity_type = 'PrivatePerson';

        if(!entity) {
            [entity] = await PrivatePerson.create([{
                _id: mongoose.Types.ObjectId().toHexString(),
                ...req.body,
                source: req.app
            }], { session: req.session })
        }
    }

    return {
        entity, entity_type
    };
};

const createEnergyMandate = async (req, entity_id, entity_type, next) => {
    let energy_mandate;

    energy_mandate = await EnergyMandate.findOne({ entity: entity_id });

    if(energy_mandate) {
        return next(new ErrorResponse('Email already in use', `An account with the provided email address already exists. Please login instead.`, 409, 'email_already_in_use'));
    }

    let preferences = {
        push_notifications: true,
        sms_notifications: true,
        email_notifications: true
    }

    if(!req.app.notifications) {
        preferences = {
            push_notifications: false,
            sms_notifications: false,
            email_notifications: false
        }
    }

    [energy_mandate] = await EnergyMandate.create([{
        _id: mongoose.Types.ObjectId().toHexString(),
        entity: entity_id,
        start_date: Date.now(),
        status: 'edit_customer',
        legal: {
            privacy_policy_version: '2.1',
            privacy_policy_signed: true,
            privacy_policy_signed_at: Date.now(),
            privacy_policy_signed_from_ip: req.user_ip,

            general_conditions_version: '2.1',
            general_conditions_signed: true,
            general_conditions_signed_at: Date.now(),
            general_conditions_signed_from_ip: req.user_ip
        },
        preferences: preferences,
        sales_channel: req.app.channel
    }], { session: req.session });

    return energy_mandate;
}

export const register = asyncHandler(async (req, res, next) => {
    const session = await mongoose.startSession();
    session.startTransaction();

    req.session = session;

    try {
        // Find or create entity
        const { entity, entity_type } = await findOrCreateEntity(req, next);

        // Create energy mandate
        const energy_mandate = await createEnergyMandate(req, entity._id, entity_type, next);

        // Create auth0 user unless req.app.user is false
        if(!req.app.user) {
            auth0_user = await createAuth0User(req, next);
            auth0_uid = auth0_user.user_id;
        } else {
            auth0_uid = req.user.uid;
        }

        return res.status(200).json({
            message: 'User registered',
            data: {
                user_id: auth0_uid
            }
        });
    } catch (error) {
        await session.abortTransaction();

        if(auth0_user) {
            await auth0ManagementClient.deleteUser({
                id: auth0_user.user_id
            });
        }

        next(error);
    } finally {
        session.endSession();
    }
});

As you can see there are some points where I use an ErrorResponse to write very specific errors like return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}</code>, 400, 'company_not_found'));`

Based on the previous question I asked and the answer I received, I should wrap each function in the register controller function into it's own try/catch block so the register function stops executing.

I've got two question about that:

How can I return the specific errors like return next(new ErrorResponse('Company not found', `We were unable to find the company for the given enterprise number ${req.body.enterprise_number}`, 400, 'company_not_found')); to the client but also calling the catch block.

Will the 'global catch' where the transaction is being aborted still be hit if I have all these smaller try/catch blocks? In other words will the main catch block of a try/catch be executed if the try/catch block has one or multiple try/catch blocks?


来源: stackexchange

问:
how to access georss:point from
I'm trying to grab some data from an rss feed. I have everything I need except the latitude and longitude from the georss:point key. I can't seem to access it and it doesn't even show up in the console when I console.log the entire object. It only shows itself in the raw xml file.

Here is my code snippet.

```<code>feed.items.forEach(function(entry) {
            console.dir(entry)

            let h2 = document.createElement('h1');
            let h3 = document.createElement('h2');
            let p = document.createElement('p');

            let li = document.getElementById('jobData');
            let text = document.createTextNode(entry.title + '\n' + entry.link + '\n' + entry.contentSnippet);
            li.appendChild(text);
            document.body.appendChild(li)
            console.log(entry.title + ':' + entry.link);
        })
```[This is the xlm I'm working with](https://i.stack.imgur.com/91AUy.png)[
This is my object when I console.log. The geo:rss is no longer there.](https://i.stack.imgur.com/xnykk.png)

```

ContentLicense: CC BY-SA 4.0

Title: how to access georss:point from

Body:
I'm trying to grab some data from an rss feed. I have everything I need except the latitude and longitude from the georss:point key. I can't seem to access it and it doesn't even show up in the console when I console.log the entire object. It only shows itself in the raw xml file.

Here is my code snippet.

feed.items.forEach(function(entry) {
            console.dir(entry)

            let h2 = document.createElement('h1');
            let h3 = document.createElement('h2');
            let p = document.createElement('p');

            let li = document.getElementById('jobData');
            let text = document.createTextNode(entry.title + '\n' + entry.link + '\n' + entry.contentSnippet);
            li.appendChild(text);
            document.body.appendChild(li)
            console.log(entry.title + ':' + entry.link);
        })
```[This is the xlm I'm working with](https://i.stack.imgur.com/91AUy.png)[
This is my object when I console.log. The geo:rss is no longer there.](https://i.stack.imgur.com/xnykk.png)


问:
Authentication error when I send email from Yandex using Flask
I want to send emails from Yandex using Flask but I get "authentication failed: This user does not have access rights to this service".

I did this:

```<code>from flask import Flask, render_template, redirect, request
from flask_mail import Mail, Message

app=Flask(__name__)
mail = Mail(app)

app.config['MAIL_SERVER'] = 'smtp.yandex.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'my-username@yandex.com'
app.config['MAIL_PASSWORD'] = 'my-password'
mail = Mail(app)

@app.route('/send-email')
def send_mail():
    msg = Message('This email was sent by me from Flask', sender='my-username@yandex.com',recipients=['rec@gmail.com'])
    msg.body = "This is the email body, I just wanted to test the flask email option, and see how doest it work."
    mail.send(msg)
    return 'Email sent!'
</code>```

I was expecting the message to be sent, but I got the authentification error.
PS: My email and password are correct.

Body:
I want to send emails from Yandex using Flask but I get "authentication failed: This user does not have access rights to this service".

I did this:

from flask import Flask, render_template, redirect, request
from flask_mail import Mail, Message

app=Flask(__name__)
mail = Mail(app)

app.config['MAIL_SERVER'] = 'smtp.yandex.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'my-username@yandex.com'
app.config['MAIL_PASSWORD'] = 'my-password'
mail = Mail(app)

@app.route('/send-email')
def send_mail():
    msg = Message('This email was sent by me from Flask', sender='my-username@yandex.com',recipients=['rec@gmail.com'])
    msg.body = "This is the email body, I just wanted to test the flask email option, and see how doest it work."
    mail.send(msg)
    return 'Email sent!'

I was expecting the message to be sent, but I got the authentification error.
PS: My email and password are correct.


问:
cpp thread detach position?
my simple test code here:

// t.cpp

#include <iostream>
#include <chrono>
#include <thread>

void fcn()
{
    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"hihi" << float(i++)<<std::endl;
    }
}

std::thread t(fcn);

t.detach(); // detach position A

int main()
{
    // t.detach(); // detach position B

    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"yoyo" << float(i++)<<std::endl;
    }

}
```

compile and run by g++ ./t.cpp -o t -lpthread; ./t;

when detach at position A got compile error error: ‘t’ does not name a type | t.detach();,
but detach at position B is ok.

why is this different?

my situation is that i wish to move the fcn() and std::thread t(fcn) as well as t.detach() into a standalone header file later (for a better orginazation of the project) thanks

Title: cpp thread detach position?

Body:
my simple test code here:

// t.cpp

#include <iostream>
#include <chrono>
#include <thread>

void fcn()
{
    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"hihi" << float(i++)<<std::endl;
    }
}

std::thread t(fcn);

t.detach(); // detach position A

int main()
{
    // t.detach(); // detach position B

    uint8_t i = 0;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout<<"yoyo" << float(i++)<<std::endl;
    }

}

compile and run by g++ ./t.cpp -o t -lpthread; ./t;

when detach at position A got compile error error: ‘t’ does not name a type | t.detach();,
but detach at position B is ok.

why is this different?

my situation is that i wish to move the fcn() and std::thread t(fcn) as well as t.detach() into a standalone header file later (for a better orginazation of the project) thanks


问:
How to change a variable used by a QProcess script?
I have a script that execute a QProcess as so:

```<code> def openCams(self):
        self.cam = QProcess()
        self.cam.execute('python',['CamWinv4.py'])
</code>```

I would like to change a variable within CamWinv4 when openCams run.
The question is: How should I proceed to do that ?

Thank You for your time.

Body:
I have a script that execute a QProcess as so:

 def openCams(self):
        self.cam = QProcess()
        self.cam.execute('python',['CamWinv4.py'])

I would like to change a variable within CamWinv4 when openCams run.
The question is: How should I proceed to do that ?

Thank You for your time.


问:
AreaSeries does not seem to work for highPrecision data points
Consider the following example. It does not display an area series plot.

<!DOCTYPE html>

    <title>Using chart in HTML page</title>
    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width,initial-scale=1" />

LightningChart® JS in HTML page

```

AreaSeries seem to work fine when axisX type does not have type = linear-highPrecision.

I have a time series data with timestamp in microseconds, so I would like to use high precision mode.
However, it seems to not work well.

First of all for small values (set data = data1 on line 85) , the shaded area does not align with the line plot

Shaded area not correct

If I use microsecond timestamp (set data = data3 on line 85), it just does not even show any shaded area.

Shows no shaded area at all

Small x-values work fine when I remove linear-highPrecision (on line 54).

Good case of low-precision area-series plot

What am I doing wrong for high precision plots? Is it supposed to work?

Body:
Consider the following example. It does not display an area series plot.

<!DOCTYPE html>

    <title>Using chart in HTML page</title>
    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width,initial-scale=1" />

LightningChart® JS in HTML page

AreaSeries seem to work fine when axisX type does not have type = linear-highPrecision.

I have a time series data with timestamp in microseconds, so I would like to use high precision mode.
However, it seems to not work well.

First of all for small values (set data = data1 on line 85) , the shaded area does not align with the line plot

Shaded area not correct

If I use microsecond timestamp (set data = data3 on line 85), it just does not even show any shaded area.

Shows no shaded area at all

Small x-values work fine when I remove linear-highPrecision (on line 54).

Good case of low-precision area-series plot

What am I doing wrong for high precision plots? Is it supposed to work?


问:
React Native: SvgUri doesn't render SVG image from URL
I am trying to load a logo from the response of an API in my app using the react-native-svg library. There are no errors of any kind, and when including the component in my code other elements of the screen are moving out of the way, there is just no visible image.

```<code>import { SvgUri } from "react-native-svg";

...

    <TouchableInfoContainer>
      <TouchableBar onPress={() => {}}>
        <SvgUri
          uri={data.operating_carrier.logo_symbol_url}
          height={20}
          width={20}
        />
        <DataText>
          {flightInfo[0].segments[0].operating_carrier.name}{" "}
          {flightInfo[0].segments[0].operating_carrier.iata_code}{" "}
          {flightInfo[0].segments[0].operating_carrier_flight_number}
        </DataText>
        <InfoSection>
          <Icon size={20} name="airplane-clock" color={theme.colors.white} />
          <DataText color={theme.colors.highlight}> 2:32</DataText>
        </InfoSection>
      </TouchableBar>
    </TouchableInfoContainer>
</code>```

I've been following the documentation here: https://github.com/software-mansion/react-native-svg/blob/main/USAGE.md. I've attempted to install and use both react-native-svg 13.4.0 and react-native-svg 13.6.0 but neither work. I've also attempted to add a hardcoded link to an SVG file that I'm visited manually in my browser to ensure that it actually exists. No images will display, just blank space.

Body:
I am trying to load a logo from the response of an API in my app using the react-native-svg library. There are no errors of any kind, and when including the component in my code other elements of the screen are moving out of the way, there is just no visible image.

import { SvgUri } from "react-native-svg";

...

    <TouchableInfoContainer>
      <TouchableBar onPress={() => {}}>
        <SvgUri
          uri={data.operating_carrier.logo_symbol_url}
          height={20}
          width={20}
        />
        <DataText>
          {flightInfo[0].segments[0].operating_carrier.name}{" "}
          {flightInfo[0].segments[0].operating_carrier.iata_code}{" "}
          {flightInfo[0].segments[0].operating_carrier_flight_number}
        </DataText>
        <InfoSection>
          <Icon size={20} name="airplane-clock" color={theme.colors.white} />
          <DataText color={theme.colors.highlight}> 2:32</DataText>
        </InfoSection>
      </TouchableBar>
    </TouchableInfoContainer>

I've been following the documentation here: https://github.com/software-mansion/react-native-svg/blob/main/USAGE.md. I've attempted to install and use both react-native-svg 13.4.0 and react-native-svg 13.6.0 but neither work. I've also attempted to add a hardcoded link to an SVG file that I'm visited manually in my browser to ensure that it actually exists. No images will display, just blank space.


问:
Best strategy for combining the outcomes of multiple nested queries
Heeey all I'm a bit stuck with querying my document with elasticsearch:

I've got almost a 1 to 1 copy of this specific problem. Unfortunately that question has not been answered.

So I'm wondering a few things:
Is this a design flaw in how my documents are stored?
What is the best strategy to avoid these kind of problems?

Many thanks in advance,

Leon


问:
Having problem with adding triangles to a sphere mesh
I am trying to create triangles from my Vector3 array that contains all my vertices for my sphere. Bascially, i want to copy the index of the vertex in my Traingle array. But how can i copy only the value of the index, not the actual value of the Vector3. I dont know if that makes sense but thank you

I tried a lot of things


问:
Can you use a JsonPath with a JsonProperty Annotation
I have a Kotlin data class that I want to map to some Json - common as rain, by itself. What I'd like to do is represent each field as a JsonPath expression in the @JsonAttribute field because the result I get is an array with 1 single map in it - something like this:

data class Bug(
    @JsonProperty("\$.items[0].rptno")
    val id: Long,
    val status: Int,
    @JsonProperty("\$.items[0].updated_date")
    val reportedDate: Instant, // fields.created
    @JsonProperty("updated_date")
    val updatedDate: Instant,
    val pillar: String, // from pi file as pillar
    @JsonProperty("\$.items[0].product_id")
    val productId: Int,
    @JsonProperty("\$.items[0].assignee")
    val assignee: String,
    val serviceRequests: List<Long> = listOf(),

    @JsonProperty("\$.items[0].subject")
    val title: String,
    @JsonProperty("\$.items[0].bug_type")
    val type: String,
)

```


问:
Error of GET http://localhost:3000/users/myproducts/undefined 404 (Not Found)
I have a issue about bad request that I have not find any method for solving.
Here is my code for creating a page which contains app bar on the top and it will gather the data from MongoDB users. There is a array defined to users called purchased which contains the ids of products of user bought. main purpose of the code will be take those ids and list them as product cards in the page.

myProducts.js

import * as React from "react";
import { useParams } from "react-router-dom";
import ListPurchase from "../Components/Purchased/listmyPurchase";
import AppBar from "../Components/Navbar/appbar";

export default function ActiveBids() {
  const { email } = useParams();

  return (
    <>
      <AppBar></AppBar>
      <ListPurchase>email={email}</ListPurchase>
    </>
  );
}
```
<p>I think listmyPurchase is listing the products, fetches a user's purchase history from a server using the user's email address. It uses the Axios library to make an HTTP GET request to the server and then parses the response to extract the purchase history data, which it uses to render a list of purchased items. The notEmpty function is used to check if the response data is empty
listmyPurchase.js</p>
<pre class="lang-js prettyprint-override"><code>import * as React from 'react';
import { Box, Container, CircularProgress, Typography } from '@mui/material';
import serverURI from '../../Constants/connection';
import axios from 'axios';
import PurchasedItems from '../Purchased/myPurchase';

export default function ListPurchase(props) {
  const email = props.email;
  // console.log(email);
  let uri = serverURI + '/users/myproducts/';
  const [message, setMessage] = React.useState([{}]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    var config = {
      method: 'get',
      url: uri + email,

      headers: {
        'Content-Type': 'application/json',
      },
    };
    console.log(uri);

    axios(config)
      .then((response) => {
        console.log(response.data.message);
        setMessage(response.data.message);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error);
      });
  }, [email, uri]);

  function notEmpty(obj) {
    return Object.keys(obj).length === 0;
  }

  return (
    <Container sx={{ mt: 5, mb: 5 }}>
      {/* <Divider></Divider> */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 30 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Box>
          {notEmpty(message[0]) ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 30 }}>
              <Typography fontWeight={600}>No active bid history.</Typography>
            </Box>
          ) : (
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                columnGap: 3,
                rowGap: 2,
                gridTemplateColumns: 'repeat(4, 1fr)',
              }}
            >
              {message.map((product, idx) => (
                <PurchasedItems
                  key={idx}
                  pid={product._id}
                  price={product.price}
                  start_date={product.start_date}
                  duration={product.duration}
                  type={product.type}
                  name={product.name}
                  owner={product.owner}
                  image={product.image}
                  states={product.state}
                ></PurchasedItems>
              ))}
            </Box>
          )}
        </Box>
      )}
    </Container>
  );
}

</code>```

In here I know there is unnecessary part of change the color of text interms of price and who bidded but the only thing I try to manage is the list different products that purchased in terms of bidded by users It is React component that represents a single purchased item. It receives data about the purchased item as props, including the item's name, type, owner, image, and bid price. The component renders this information in a user-friendly format and includes an event handler for clicking on the image or the item's name, which navigates to the product page for the item. The states prop is used to determine the color of the bid price (green if the bid is active, red if it is not). The useNavigate hook from the react-router-dom library is used to handle navigation to the product page.

myPurchase.js

import * as React from 'react';
import { Box, Typography } from '@mui/material';
import { Container } from '@mui/material';
import { useNavigate } from 'react-router-dom';

export default function PurchasedItems(props) {
  const pid = props.pid;
  // console.log(pid);
  const type = props.type || 'test';
  const name = props.name || 'test';
  const owner = props.owner || 'test';
  const image =
    props.image ||
    'https://assets.adidas.com/images/w_600,f_auto,q_auto/49808757050946de8bedae29011926b5_9366/Manchester_United_22-23_Home_Jersey_Red_H13881_21_model.jpg';
  const price = props.price;
  const duration = Number(props.duration) / 1000;
  const start_date = Number(props.start_date) / 1000;
  const currentDate = Math.floor(Date.now() / 1000);
  const remainingTime = duration - (currentDate - start_date);
  const states = props.states;
  const [currentRemaningTime, setRemainingTime] = React.useState(remainingTime);
  const navigate = useNavigate();

  const handleProductPage = () => {
    navigate(`/product/${pid}`);
  };

  return (
    <Container>
      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
        {' '}
        <Box
          sx={{
            width: '60%',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',

            p: 3,
          }}
        >
          <Box sx={{ display: 'flex', direction: 'row', alignItems: 'center' }}>
            <Box>

            </Box>
            <Box onClick={handleProductPage} sx={{ ml: 5 }}>
              <Typography color="text.primary" sx={{ fontWeight: 700 }}>
                {name}
              </Typography>
              <Typography color="text.primary" sx={{ fontWeight: 500 }}>
                {type}
              </Typography>
              <Typography color="text.primary" sx={{ fontWeight: 500 }}>
                {owner}
              </Typography>
            </Box>
          </Box>
          <Box
            onClick={handleProductPage}
            sx={{ display: 'flex', alignItems: 'center' }}
          >
            <Typography sx={{ color: 'black', fontWeight: 700 }}>
              {`Your bid:`}
            </Typography>
            {states ? (
              <Typography sx={{ color: 'green', fontWeight: 700 }}>
                {`${price}$`}
              </Typography>
            ) : (
              <Typography sx={{ color: 'red', fontWeight: 700 }}>
                {`${price}$`}
              </Typography>
            )}
          </Box>
        </Box>
      </Box>
    </Container>
  );
}

```
<p>App.js</p>
<pre class="lang-js prettyprint-override"><code>import "./App.css";
import Signin from "./Views/signin";
import Signup from "./Views/signup";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Profile from "./Views/profile";
// import Test from "./Views/test";
import Search from "./Views/search";

import HomePage from "./Views/homepage";

import Product from "./Views/product";

import AdminPage from "./Views/adminpage";
import ActiveBids from "./Views/activebid";
import MyProducts from "./Views/myProducts";

function App() {
  return (
    <BrowserRouter>
      <Routes>

        <Route path="/myproducts/:email" element={<MyProducts />} />

      </Routes>
    </BrowserRouter>
  );
}

export default App;

</code>```

users.js

var express = require("express");
var router = express.Router();
const userModel = require("../models/user.model");
let userController = require("../controller/user.controller");

router.get("/myproducts/:email", userController.getMyPurchase);

module.exports = router;

```
<p>user.controller.js</p>
<pre class="lang-js prettyprint-override"><code>const express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
let auth = require('../controller/auth');
let bcrypt = require('bcryptjs');
const { Schema } = mongoose;
const { MongoClient, MongoGridFSChunkError, ObjectId } = require('mongodb');

const userModel = require('../models/user.model');
const teamModel = require('../models/team.model');
const catchAsync = require('./../utils/catchAsync');
const productModel = require('../models/product.model');
const bidModel = require('../models/bid.model');

const mailgun = require('mailgun-js');

exports.getMyPurchase = (req, res, next) => {
  let email = req.params.email;

  // Find the user with the specified email address
  userModel
    .findOne({ email: email })
    .then((user) => {
      // Find the purchased items for the user
      productModel
        .find({
          _id: { $in: user.purchased },
          open: true,
        })
        .then((products) => {
          // Send the purchased items as a response
          res.send({
            message: products,
          });
        })
        .catch((error) => {
          // Handle any errors that occurred during the query
          next(error);
        });
    })
    .catch((error) => {
      // Handle any errors that occurred during the query
      next(error);
    });
};
``;

</code>```

I cannot find the reason of "GET http://localhost:3000/users/myproducts/undefined 404 (Not Found)"

Body:
I have a issue about bad request that I have not find any method for solving.
Here is my code for creating a page which contains app bar on the top and it will gather the data from MongoDB users. There is a array defined to users called purchased which contains the ids of products of user bought. main purpose of the code will be take those ids and list them as product cards in the page.

myProducts.js

import * as React from "react";
import { useParams } from "react-router-dom";
import ListPurchase from "../Components/Purchased/listmyPurchase";
import AppBar from "../Components/Navbar/appbar";

export default function ActiveBids() {
  const { email } = useParams();

  return (
    <>
      <AppBar></AppBar>
      <ListPurchase>email={email}</ListPurchase>
    </>
  );
}

I think listmyPurchase is listing the products, fetches a user's purchase history from a server using the user's email address. It uses the Axios library to make an HTTP GET request to the server and then parses the response to extract the purchase history data, which it uses to render a list of purchased items. The notEmpty function is used to check if the response data is empty
listmyPurchase.js

import * as React from 'react';
import { Box, Container, CircularProgress, Typography } from '@mui/material';
import serverURI from '../../Constants/connection';
import axios from 'axios';
import PurchasedItems from '../Purchased/myPurchase';

export default function ListPurchase(props) {
  const email = props.email;
  // console.log(email);
  let uri = serverURI + '/users/myproducts/';
  const [message, setMessage] = React.useState([{}]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    var config = {
      method: 'get',
      url: uri + email,

      headers: {
        'Content-Type': 'application/json',
      },
    };
    console.log(uri);

    axios(config)
      .then((response) => {
        console.log(response.data.message);
        setMessage(response.data.message);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error);
      });
  }, [email, uri]);

  function notEmpty(obj) {
    return Object.keys(obj).length === 0;
  }

  return (
    <Container sx={{ mt: 5, mb: 5 }}>
      {/* <Divider></Divider> */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 30 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Box>
          {notEmpty(message[0]) ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 30 }}>
              <Typography fontWeight={600}>No active bid history.</Typography>
            </Box>
          ) : (
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                columnGap: 3,
                rowGap: 2,
                gridTemplateColumns: 'repeat(4, 1fr)',
              }}
            >
              {message.map((product, idx) => (
                <PurchasedItems
                  key={idx}
                  pid={product._id}
                  price={product.price}
                  start_date={product.start_date}
                  duration={product.duration}
                  type={product.type}
                  name={product.name}
                  owner={product.owner}
                  image={product.image}
                  states={product.state}
                ></PurchasedItems>
              ))}
            </Box>
          )}
        </Box>
      )}
    </Container>
  );
}

In here I know there is unnecessary part of change the color of text interms of price and who bidded but the only thing I try to manage is the list different products that purchased in terms of bidded by users It is React component that represents a single purchased item. It receives data about the purchased item as props, including the item's name, type, owner, image, and bid price. The component renders this information in a user-friendly format and includes an event handler for clicking on the image or the item's name, which navigates to the product page for the item. The states prop is used to determine the color of the bid price (green if the bid is active, red if it is not). The useNavigate hook from the react-router-dom library is used to handle navigation to the product page.

myPurchase.js

import * as React from 'react';
import { Box, Typography } from '@mui/material';
import { Container } from '@mui/material';
import { useNavigate } from 'react-router-dom';

export default function PurchasedItems(props) {
  const pid = props.pid;
  // console.log(pid);
  const type = props.type || 'test';
  const name = props.name || 'test';
  const owner = props.owner || 'test';
  const image =
    props.image ||
    'https://assets.adidas.com/images/w_600,f_auto,q_auto/49808757050946de8bedae29011926b5_9366/Manchester_United_22-23_Home_Jersey_Red_H13881_21_model.jpg';
  const price = props.price;
  const duration = Number(props.duration) / 1000;
  const start_date = Number(props.start_date) / 1000;
  const currentDate = Math.floor(Date.now() / 1000);
  const remainingTime = duration - (currentDate - start_date);
  const states = props.states;
  const [currentRemaningTime, setRemainingTime] = React.useState(remainingTime);
  const navigate = useNavigate();

  const handleProductPage = () => {
    navigate(`/product/${pid}`);
  };

  return (
    <Container>
      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
        {' '}
        <Box
          sx={{
            width: '60%',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',

            p: 3,
          }}
        >
          <Box sx={{ display: 'flex', direction: 'row', alignItems: 'center' }}>
            <Box>

            </Box>
            <Box onClick={handleProductPage} sx={{ ml: 5 }}>
              <Typography color="text.primary" sx={{ fontWeight: 700 }}>
                {name}
              </Typography>
              <Typography color="text.primary" sx={{ fontWeight: 500 }}>
                {type}
              </Typography>
              <Typography color="text.primary" sx={{ fontWeight: 500 }}>
                {owner}
              </Typography>
            </Box>
          </Box>
          <Box
            onClick={handleProductPage}
            sx={{ display: 'flex', alignItems: 'center' }}
          >
            <Typography sx={{ color: 'black', fontWeight: 700 }}>
              {`Your bid:`}
            </Typography>
            {states ? (
              <Typography sx={{ color: 'green', fontWeight: 700 }}>
                {`${price}$`}
              </Typography>
            ) : (
              <Typography sx={{ color: 'red', fontWeight: 700 }}>
                {`${price}$`}
              </Typography>
            )}
          </Box>
        </Box>
      </Box>
    </Container>
  );
}

App.js

import "./App.css";
import Signin from "./Views/signin";
import Signup from "./Views/signup";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Profile from "./Views/profile";
// import Test from "./Views/test";
import Search from "./Views/search";

import HomePage from "./Views/homepage";

import Product from "./Views/product";

import AdminPage from "./Views/adminpage";
import ActiveBids from "./Views/activebid";
import MyProducts from "./Views/myProducts";

function App() {
  return (
    <BrowserRouter>
      <Routes>

        <Route path="/myproducts/:email" element={<MyProducts />} />

      </Routes>
    </BrowserRouter>
  );
}

export default App;

users.js

var express = require("express");
var router = express.Router();
const userModel = require("../models/user.model");
let userController = require("../controller/user.controller");

router.get("/myproducts/:email", userController.getMyPurchase);

module.exports = router;

user.controller.js

const express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
let auth = require('../controller/auth');
let bcrypt = require('bcryptjs');
const { Schema } = mongoose;
const { MongoClient, MongoGridFSChunkError, ObjectId } = require('mongodb');

const userModel = require('../models/user.model');
const teamModel = require('../models/team.model');
const catchAsync = require('./../utils/catchAsync');
const productModel = require('../models/product.model');
const bidModel = require('../models/bid.model');

const mailgun = require('mailgun-js');

exports.getMyPurchase = (req, res, next) => {
  let email = req.params.email;

  // Find the user with the specified email address
  userModel
    .findOne({ email: email })
    .then((user) => {
      // Find the purchased items for the user
      productModel
        .find({
          _id: { $in: user.purchased },
          open: true,
        })
        .then((products) => {
          // Send the purchased items as a response
          res.send({
            message: products,
          });
        })
        .catch((error) => {
          // Handle any errors that occurred during the query
          next(error);
        });
    })
    .catch((error) => {
      // Handle any errors that occurred during the query
      next(error);
    });
};
``;

I cannot find the reason of "GET http://localhost:3000/users/myproducts/undefined 404 (Not Found)"


问:
How to concatenate a data frame to a new column
enter image description here

I’ve tried modifying syntax.
I’m expecting a new dataset an I only get rows, no columns.


问:
How to make GCC recognize System V `-G` option for linking dynamic libraries?
The next POSIX standard is expected to include support for producing dynamic libraries / shared objects through the c99 (or c17, c2x, etc.) compiler driver, using the -G flag, which the standard borrows from System V.

I've read in the GCC document the -G option is supported, at least for compatibility.

How do I utilize this gcc compatibility feature for standard-conformance in the projected future? Is there an equivalent tweak for the clang (since I heard that it aims to be largely compatible with gcc)?


问:
How to tell Sonar to use my LCOV file for Code Coverage for GOLANG GO
Team,
I am generating go coverage and converting them to html to view in Jenkins. but I want to ship the LCOV file .dat to sonarqube. is there a way? like set a key value in sonar-project.properties

```<code>./bazel $BAZEL_STARTUP_OPTS coverage $BAZEL_OPTS $BAZEL_EXTRA_OPTS //src/services/discovery/... \
    --combined_report=lcov \
    --test_output=errors --test_verbose_timeout_warnings | tee /tmp/test_results.txt
</code>```

for view on Jenkins I am converting LCOV _coverage_report.dat to html. But what I want to know if I can specify this in sonarqube.properties file either html or .dat lcov? to pick it up after scanning is done?
I see this for java but not for GO

```<code>./bazel run @lcov//:bin/genhtml -- -o \coverage/discovery --ignore-errors source --no-source --function-coverage --branch-coverage --no-sort bazel-out/_coverage/_coverage_report.dat || true
</code>```

Body:
Team,
I am generating go coverage and converting them to html to view in Jenkins. but I want to ship the LCOV file .dat to sonarqube. is there a way? like set a key value in sonar-project.properties

./bazel $BAZEL_STARTUP_OPTS coverage $BAZEL_OPTS $BAZEL_EXTRA_OPTS //src/services/discovery/... \
    --combined_report=lcov \
    --test_output=errors --test_verbose_timeout_warnings | tee /tmp/test_results.txt

for view on Jenkins I am converting LCOV _coverage_report.dat to html. But what I want to know if I can specify this in sonarqube.properties file either html or .dat lcov? to pick it up after scanning is done?
I see this for java but not for GO

./bazel run @lcov//:bin/genhtml -- -o \coverage/discovery --ignore-errors source --no-source --function-coverage --branch-coverage --no-sort bazel-out/_coverage/_coverage_report.dat || true


问:
Display Javascript Cookies in Table
I am writing a program which fetches the user's cookies along with their input. I got all the input fields displayed on a dynamic table but couldn't figure out to add the cookie along with it. Also is there any other way to display the table in another page?

```<code><!DOCTYPE html>
<html>
<head>
  <title>DATA</title>
  <link rel="stylesheet" href="main.css">
</head>
<body>

  <div class="container">
    <label for="fname">FIRST NAME</label>
    <input type="text" name="fname" id="fname">
    <label for="lname">LAST NAME</label>
    <input type="text" name="lname" id="lname">
    <label for="email">EMAIL</label>
    <input type="text" name="email" id="email">
    <label for="age">AGE</label>
    <input type="text" name="age" id="age">
    <input type="button" name="button" id="btn" value="Add" onclick="AddRow()">

  </div>

    <table id="show">

        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Email</th>
          <th>Age</th>
          <th>Cookies</th>

        </tr>

    </table>

  <script>
    function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");

    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }

    // Return null if not found
    return null;
}

    var cookies = document.cookie;
    var list1 = [];
    var list2 = [];
    var list3 = [];
    var list4 = [];
    var list5 = [];

    var n = 1;
    var x = 0;

    function AddRow(){

      var AddRown = document.getElementById('show');
      var NewRow = AddRown.insertRow(n);

      list1[x] = document.getElementById("fname").value;
      list2[x] = document.getElementById("lname").value;
      list3[x] = document.getElementById("email").value;
      list4[x] = document.getElementById("age").value;
      list5[x] = document.getElementById(cookies).value;

      var cel1 = NewRow.insertCell(0);
      var cel2 = NewRow.insertCell(1);
      var cel3 = NewRow.insertCell(2);
      var cel4 = NewRow.insertCell(3);
      var cel5 = NewRow.insertCell(4);

      cel1.innerHTML = list1[x];
      cel2.innerHTML = list2[x];
      cel3.innerHTML = list3[x];
      cel4.innerHTML = list4[x];
      cel5.innerHTML = list5[x];

      n++;
      x++;
    }

  </script>
</body>
</html>
</code>```

This is the Error msg I got no matter what I did
Uncaught TypeError: Cannot read properties of null (reading 'value')

Title: Display Javascript Cookies in Table

Body:
I am writing a program which fetches the user's cookies along with their input. I got all the input fields displayed on a dynamic table but couldn't figure out to add the cookie along with it. Also is there any other way to display the table in another page?

<!DOCTYPE html>

  <title>DATA</title>
  <link rel="stylesheet" href="main.css">

    FIRST NAME
    <input type="text" name="fname" id="fname">
    LAST NAME
    <input type="text" name="lname" id="lname">
    EMAIL
    <input type="text" name="email" id="email">
    AGE
    <input type="text" name="age" id="age">
    <input type="button" name="button" id="btn" value="Add" onclick="AddRow()">

          First Name
          Last Name
          Email
          Age
          Cookies

This is the Error msg I got no matter what I did
Uncaught TypeError: Cannot read properties of null (reading 'value')


问:
Sketchpy returning NameError: name 'draw' is not defined
So I want to draw an image and draw it with Turtle but I'm not sure how to command the Turtle to draw the image
I've tried using sketchpy after following some tutorials but it returns an error

```<code>from sketchpy import canvas
obj=canvas.sketch_from_image('file:///C:/Users/aryan_mukhi/Downloads/32fd871166ae8debb1f848664365963f_adobe_express.svg')

obj = draw(threshold=127)
</code>```
```<code>NameError: name 'draw' is not defined
</code>```

I've searched google but since sketchpy is a small library couldn't find any info on how to solve it
I checked their website apparently the draw function is part of the sketchpy package, however since it's undefined can anyone suggest any alternatives

Body:
So I want to draw an image and draw it with Turtle but I'm not sure how to command the Turtle to draw the image
I've tried using sketchpy after following some tutorials but it returns an error

from sketchpy import canvas
obj=canvas.sketch_from_image('file:///C:/Users/aryan_mukhi/Downloads/32fd871166ae8debb1f848664365963f_adobe_express.svg')

obj = draw(threshold=127)

NameError: name 'draw' is not defined

I've searched google but since sketchpy is a small library couldn't find any info on how to solve it
I checked their website apparently the draw function is part of the sketchpy package, however since it's undefined can anyone suggest any alternatives


问:
Angular routerlink fragment not triggering slider
My Problem

I have modified this pure css slider, and trying to use it in Angular

Here's how I initially created the dynamic slider anchor points for moving around

```<code><a class="slide__prev" [attr.href]="first ? '#slides__' + (appropriate?.data.length) : '#slides__' + ((i+1) - 1)" title="Next"></a>
</code>```

The above generates an HTML looking like this

```<code><a _ngcontent-fmy-c57="" title="Next" class="slide__next" href="#slides__2"></a>
</code>```

The problem with the above is, although it works on the / url, trying to use the slider on any other routes fails, i.e website.com/other/.

This fails because instead of the built URL to point to the current page's fragment, it goes to the homepage i.e /#slides__2 which thus reloads the page.

What I've tried

I tried using Angular's URL fragment approach. Thus I built a URL like this dynamically. Except although the URL and fragment all look right, the slider doesn't get triggered to move left or right

```<code><a class="slide__prev" [routerLink]="'.'" [fragment]="first ? 'slides__' + (appropriate?.data.length) : 'slides__' + ((i+1) - 1)" title="Next"></a>
</code>```

Question

I'm not understanding why the fragment done with [fragment] doesn't trigger at all. Any insights will be appreciated

Body:
My Problem

I have modified this pure css slider, and trying to use it in Angular

Here's how I initially created the dynamic slider anchor points for moving around

The above generates an HTML looking like this

The problem with the above is, although it works on the / url, trying to use the slider on any other routes fails, i.e website.com/other/.

This fails because instead of the built URL to point to the current page's fragment, it goes to the homepage i.e /#slides__2 which thus reloads the page.

What I've tried

I tried using Angular's URL fragment approach. Thus I built a URL like this dynamically. Except although the URL and fragment all look right, the slider doesn't get triggered to move left or right

Question

I'm not understanding why the fragment done with [fragment] doesn't trigger at all. Any insights will be appreciated


问:
How to set up TLS on verneMQ Broker on AKS
I'm baffled by this one. I followed instructions setting up mqtts port and server certs -

enable the port

create a k8s secret with my ca cert and intermediate cert file as well as .key ( I tried with both .crt/.key and pem files, neither option worked).

set up mount

set up docker environment variables as below -

```<code>  - name: DOCKER_VERNEMQ_LISTENER__SSL__CAFILE
    value: "/etc/ssl/vernemq/vernemq_ca.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CERTFILE
    value: "/etc/ssl/vernemq/vernemq.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__KEYFILE
    value: "/etc/ssl/vernemq/vernemq.key"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__REQUIRE_CERTIFICATE
    value: "on"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__DEFAULT
    value: "0.0.0.0:8883"
  - name: DOCKER_VERNEMQ_LISTENER__TCP__DEFAULT
    value: "0.0.0.0:1883"
</code>```

However, when I tried running test with mosquitto_pub by passing in --cafile, I'm getting "protocol error". Did anyone set up VerneMQ TLS to work?

```<code>mosquitto_pub -h <hostIP> -t test -m ‘test’ --cafile ca.crt -i testClient -d
Client testClient sending CONNECT
Error: Protocol error
</code>```

I used openssl s-client connect to test the connection, I'm getting write: error(54) with some other output. How can I get around that? Thanks!

```<code>CONNECTED(00000003)
write:errno=54
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 287 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1670975815
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
</code>```

I tried using self generated certs, it didn't work either. I also tested try setting up chained CA files, using different format...etc. To no avail

Body:
I'm baffled by this one. I followed instructions setting up mqtts port and server certs -

enable the port

create a k8s secret with my ca cert and intermediate cert file as well as .key ( I tried with both .crt/.key and pem files, neither option worked).

set up mount

set up docker environment variables as below -

  - name: DOCKER_VERNEMQ_LISTENER__SSL__CAFILE
    value: "/etc/ssl/vernemq/vernemq_ca.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CERTFILE
    value: "/etc/ssl/vernemq/vernemq.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__KEYFILE
    value: "/etc/ssl/vernemq/vernemq.key"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__REQUIRE_CERTIFICATE
    value: "on"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__DEFAULT
    value: "0.0.0.0:8883"
  - name: DOCKER_VERNEMQ_LISTENER__TCP__DEFAULT
    value: "0.0.0.0:1883"

However, when I tried running test with mosquitto_pub by passing in --cafile, I'm getting "protocol error". Did anyone set up VerneMQ TLS to work?

mosquitto_pub -h <hostIP> -t test -m ‘test’ --cafile ca.crt -i testClient -d
Client testClient sending CONNECT
Error: Protocol error

I used openssl s-client connect to test the connection, I'm getting write: error(54) with some other output. How can I get around that? Thanks!

CONNECTED(00000003)
write:errno=54
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 287 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1670975815
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)

I tried using self generated certs, it didn't work either. I also tested try setting up chained CA files, using different format...etc. To no avail


问:
How to call function from controller into javascript tag blade.php LARAVEL
I am trying to call save function from my controller into javascript tag in my blade.php but javascript cannot recognize my function.My idea is make that javascript to do my function every 1 minute.

What the thing I missed out? Is it possible to do that?

Here my function in controller

```<code>public function savelivemarket(){

        $token = $this->tomeiToken();
        $client = new Client();
        $connect2= 'https://uat.fxinside.net';

        $params = [
            'headers' => ['SSO_TOKEN' => $token],

        ];

        $online_data = null;
        $online_data2 = null;
        $online_data3 = null;
        $online_data4 = null;

        try{

            $online_response = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAU500GMM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body = $online_response->getBody()->getContents();

            $online_data = json_decode($online_body);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response2 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=GS900GMM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body2 = $online_response2->getBody()->getContents();

            $online_data2 = json_decode($online_body2);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response3 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAG1GMS/SGD',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body3 = $online_response3->getBody()->getContents();

            $online_data3 = json_decode($online_body3);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response4 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAGKGM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body4 = $online_response4->getBody()->getContents();

            $online_data4 = json_decode($online_body4);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        if(isset($online_data)){
            try{
                DB::beginTransaction();
//                dd('a');
                $ratehistory = new RateHistory();
                $ratehistory->symbol = '$online_data[0]->symbol[0]';
                $ratehistory->bid_price = '$online_data[0]->bid[0]';
                $ratehistory->offer_price = '$online_data[0]->offer[0]';

                $ratehistory->save();

//            dd($payout);

                DB::commit();

            }catch (\Exception $e){
                DB::rollback();
//            dd($e->getMessage());
                return redirect()->back()->withInput()->withErrors('Failed To Add Payout');
//                return redirect()->back()->withInput()->withErrors($e->getMessage());
            }
        }

    }
</code>```

then here my javascript function in blade.php

```<code>    <script>
                  $(document).ready(function(){
                      setInterval(function(){
                          $.ajax({
                              url: "savelivemarket()",
                              success: function( response ) {
                                  // update div
                              }
                          });
                      },6000);
                  });
    </script>
</code>```

route web.php

Body:
I am trying to call save function from my controller into javascript tag in my blade.php but javascript cannot recognize my function.My idea is make that javascript to do my function every 1 minute.

What the thing I missed out? Is it possible to do that?

Here my function in controller

public function savelivemarket(){

        $token = $this->tomeiToken();
        $client = new Client();
        $connect2= 'https://uat.fxinside.net';

        $params = [
            'headers' => ['SSO_TOKEN' => $token],

        ];

        $online_data = null;
        $online_data2 = null;
        $online_data3 = null;
        $online_data4 = null;

        try{

            $online_response = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAU500GMM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body = $online_response->getBody()->getContents();

            $online_data = json_decode($online_body);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response2 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=GS900GMM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body2 = $online_response2->getBody()->getContents();

            $online_data2 = json_decode($online_body2);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response3 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAG1GMS/SGD',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body3 = $online_response3->getBody()->getContents();

            $online_data3 = json_decode($online_body3);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        try{

            $online_response4 = $client->request('GET', $connect2.'/v2/rates/spot/FULL/TXGApp?symbol=XAGKGM/MYR',$params);

            $online_statusCode = $online_response->getStatusCode();
            $online_body4 = $online_response4->getBody()->getContents();

            $online_data4 = json_decode($online_body4);

//            dd($online_data);

        } catch (ClientException $e) {
//            dd( Psr7\Message::toString($e->getRequest()),Psr7\Message::toString($e->getResponse()),$e->getMessage(),$token);
        }catch (\Exception $e){
//            dd($e->getMessage());
        }

        if(isset($online_data)){
            try{
                DB::beginTransaction();
//                dd('a');
                $ratehistory = new RateHistory();
                $ratehistory->symbol = '$online_data[0]->symbol[0]';
                $ratehistory->bid_price = '$online_data[0]->bid[0]';
                $ratehistory->offer_price = '$online_data[0]->offer[0]';

                $ratehistory->save();

//            dd($payout);

                DB::commit();

            }catch (\Exception $e){
                DB::rollback();
//            dd($e->getMessage());
                return redirect()->back()->withInput()->withErrors('Failed To Add Payout');
//                return redirect()->back()->withInput()->withErrors($e->getMessage());
            }
        }

    }

then here my javascript function in blade.php

route web.php


问:
Selenium is slow when opening and/or retrieving local html file
I am attempting to retrieve data from pro-football-reference.com, but due to their restrictions on accessing the site, if you access it too quickly, they ban you. I downloaded all of the HTML pages to a data folder on my local machine.

The issue is that now when I try to open the file using a Selenium webdriver it takes about 95 seconds to open and retrieve the html. Below is the code that I am running. The input 'box_score_file' is the local files that I have downloaded to my machine. On average files are around 500 KB.

Is this issue just due to the size of my files or is there a more efficient way to retrieve this?

```<code>def Parse_File(box_score_file):
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options)
    driver.get(f'file://{box_score_file}')
    html = driver.page_source

    soup = BeautifulSoup(html, 'html.parser')
    [s.decompose() for s in soup.select('tr.over_header')]
    [s.decompose() for s in soup.select('tr.thead')]
    return soup
</code>```

I've tried using the requests library, but since some of the tables for the html file are hidden by javascript if I use requests library I can't retrieve all of the tables that I want to create a DataFrame with.

I've also tried using playwright, but whenever I attempt to use playwright I receive the error ModuleNotFoundError: No module named 'pyee.asyncio'. I've tried 'pip install pyee', but anaconda then reports back that the requirement is already satisfied. I've also tried async playwright, but that just gives me the same issue as before saying there is no module named 'pyee.asyncio'

```<code>from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout

def Parse_File(box_score_file):
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(box_score_file)
            print(page.title())
            html = page.inner_html()
    except PlaywrightTimeout:
        print(f"Timeout error on {box_score_file}")

    soup = BeautifulSoup(html, 'html.parser')
    [s.decompose() for s in soup.select('tr.over_header')]
    [s.decompose() for s in soup.select('tr.thead')]
    return soup

</code>```

This is my first time posting, so please let me know if I can provide any additional information or details and thank you for your time.

Body:
I am attempting to retrieve data from pro-football-reference.com, but due to their restrictions on accessing the site, if you access it too quickly, they ban you. I downloaded all of the HTML pages to a data folder on my local machine.

The issue is that now when I try to open the file using a Selenium webdriver it takes about 95 seconds to open and retrieve the html. Below is the code that I am running. The input 'box_score_file' is the local files that I have downloaded to my machine. On average files are around 500 KB.

Is this issue just due to the size of my files or is there a more efficient way to retrieve this?

def Parse_File(box_score_file):
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options)
    driver.get(f'file://{box_score_file}')
    html = driver.page_source

    soup = BeautifulSoup(html, 'html.parser')
    [s.decompose() for s in soup.select('tr.over_header')]
    [s.decompose() for s in soup.select('tr.thead')]
    return soup

I've tried using the requests library, but since some of the tables for the html file are hidden by javascript if I use requests library I can't retrieve all of the tables that I want to create a DataFrame with.

I've also tried using playwright, but whenever I attempt to use playwright I receive the error ModuleNotFoundError: No module named 'pyee.asyncio'. I've tried 'pip install pyee', but anaconda then reports back that the requirement is already satisfied. I've also tried async playwright, but that just gives me the same issue as before saying there is no module named 'pyee.asyncio'

from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeout

def Parse_File(box_score_file):
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(box_score_file)
            print(page.title())
            html = page.inner_html()
    except PlaywrightTimeout:
        print(f"Timeout error on {box_score_file}")

    soup = BeautifulSoup(html, 'html.parser')
    [s.decompose() for s in soup.select('tr.over_header')]
    [s.decompose() for s in soup.select('tr.thead')]
    return soup

This is my first time posting, so please let me know if I can provide any additional information or details and thank you for your time.


问:
How do you make it so that this code is toggleable?
```<code>import discord
from discord.ext import commands, tasks
import logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(message)s",
    level=logging.INFO,
)
client = commands.Bot(command_prefix="!")

target_channel_id = 869727547221475388
role_id = #write role ID here
@client.event
async def on_ready():
    print("Bot is ready")

@tasks.loop(minutes=40)
@commands.has_permissions(administrator = True)
async def ping_start():
    message_channel = client.get_channel(target_channel_id)
    role = message_channel.guild.get_role(role_id)
    print(f"Got channel {message_channel}")
    await message_channel.send(role.mention)

@ping_start.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")

ping_start.start()

client.run("TOKEN")
</code>```

I found this code somewhere else on this site. It basically pings a certain role every 40 minutes. The thing is, I want to make it so that when you type a command in the chat, it starts timing. And you can also stop this with a different command. How would I do that?

Edit: Tried this code but the output says "Line 81 name 'remindcmd' is used prior to global declaration". I know what this means but don't know how to fix it since it looks like everything should work.

```<code>import os
from keep_alive import keep_alive
from discord.ext import commands, tasks
import logging

logging.basicConfig(
  format="%(asctime)s - %(name)s - %(message)s",
  level=logging.INFO,
)
client = commands.Bot(command_prefix="!!")

# target_channel_id = 1052266313734697041
# role_id = 1052265314269798400
@client.event
async def on_ready():
  print("I'm in")

global remindcmd
remindcmd = "neither"

@client.event
async def on_message(message):
  if message.content.__contains__("!!listen"):
          await message.channel.send("Listening for command input.")
          print("!!listen command detected.")

  if message.content.__contains__("!!test"):
          global remindcmd
          await message.channel.send(f"!!test {remindcmd}")

  if message.content.startswith("!!"):
    if message.content.endswith("/"):
      if message.content.startswith("!!reverse/"):
          revmsg = message.content[message.content.find("/")+1:-1]
          await message.channel.send(revmsg[::-1])

      if message.content.startswith("!!saysecretcmd/"):
        print(message.content[15:message.content.find("/", message.content.find("/")+1)])
        message_channel = client.get_channel(int(message.content[15:message.content.find("/", message.content.find("/")+1)]))
        print(f"Got channel {message_channel} !!saysecretcmd")
        saymsg = message.content[message.content.find("/", message.content.find("/")+1)+1:-1]
        print(f"Said the message, {saymsg}")
        await message_channel.send(saymsg)

      if message.content.startswith("!!remind/"):
        if not message.content.startswith("!!remind/stop/"):

          arg1 = message.content[9:message.content.find("/", message.content.find("/")+1)]
          arg2 = message.content[message.content.find("/", message.content.find("/")+1)+1:message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)]
          arg3 = message.content[message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)]
          arg4 = message.content[message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)]
          arg5 = message.content[message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)+1)]
          print(arg1)
          print(arg2)
          print(arg3)
          print(arg4)
          print(arg5)

          if arg2 == "false":
            print("Unlooped")
            #time.sleep(arg1)

          else:
            print("Looped")
            print(arg1)
            print(arg2)
            print(arg3)
            print(arg4)
            print(arg5)
            print("arg variables printed")

            @tasks.loop(seconds=int(arg1))
            async def ping_start(message, target_channel_id, role_id):
              print("Entered async ping start")
              global remindcmd
              print(remindcmd)
              message_channel = client.get_channel(int(target_channel_id))
              role = message_channel.guild.get_role(int(role_id))
              if remindcmd == "false":
                global remindcmd
                print("Stopped")
                ping_start.cancel()
                await message_channel.send("Loop stopped.")
                remindcmd = "neither"
                print("remindcmd variable set to neither")
              print(f"Got channel {message_channel} !!remind")
              await message_channel.send(message.replace("{role}", role.mention))
              remindcmd = "true"
              print(remindcmd)

              @ping_start.before_loop
              async def before():
                await client.wait_until_ready()
                print("Finished waiting")

            ping_start.start(arg3, arg4, arg5)

      if message.content.startswith("!!remind/stop/"):
        print("Stop command detected")
        global remindcmd
        print(remindcmd)
        remindcmd = "false"
        print(remindcmd)
        print("remindcmd variable set to false")

# await message.channel.send("Message here")

keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
</code>```

Body:
import discord
from discord.ext import commands, tasks
import logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(message)s",
    level=logging.INFO,
)
client = commands.Bot(command_prefix="!")

target_channel_id = 869727547221475388
role_id = #write role ID here
@client.event
async def on_ready():
    print("Bot is ready")

@tasks.loop(minutes=40)
@commands.has_permissions(administrator = True)
async def ping_start():
    message_channel = client.get_channel(target_channel_id)
    role = message_channel.guild.get_role(role_id)
    print(f"Got channel {message_channel}")
    await message_channel.send(role.mention)

@ping_start.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")

ping_start.start()

client.run("TOKEN")

I found this code somewhere else on this site. It basically pings a certain role every 40 minutes. The thing is, I want to make it so that when you type a command in the chat, it starts timing. And you can also stop this with a different command. How would I do that?

Edit: Tried this code but the output says "Line 81 name 'remindcmd' is used prior to global declaration". I know what this means but don't know how to fix it since it looks like everything should work.

import os
from keep_alive import keep_alive
from discord.ext import commands, tasks
import logging

logging.basicConfig(
  format="%(asctime)s - %(name)s - %(message)s",
  level=logging.INFO,
)
client = commands.Bot(command_prefix="!!")

# target_channel_id = 1052266313734697041
# role_id = 1052265314269798400
@client.event
async def on_ready():
  print("I'm in")

global remindcmd
remindcmd = "neither"

@client.event
async def on_message(message):
  if message.content.__contains__("!!listen"):
          await message.channel.send("Listening for command input.")
          print("!!listen command detected.")

  if message.content.__contains__("!!test"):
          global remindcmd
          await message.channel.send(f"!!test {remindcmd}")

  if message.content.startswith("!!"):
    if message.content.endswith("/"):
      if message.content.startswith("!!reverse/"):
          revmsg = message.content[message.content.find("/")+1:-1]
          await message.channel.send(revmsg[::-1])

      if message.content.startswith("!!saysecretcmd/"):
        print(message.content[15:message.content.find("/", message.content.find("/")+1)])
        message_channel = client.get_channel(int(message.content[15:message.content.find("/", message.content.find("/")+1)]))
        print(f"Got channel {message_channel} !!saysecretcmd")
        saymsg = message.content[message.content.find("/", message.content.find("/")+1)+1:-1]
        print(f"Said the message, {saymsg}")
        await message_channel.send(saymsg)

      if message.content.startswith("!!remind/"):
        if not message.content.startswith("!!remind/stop/"):

          arg1 = message.content[9:message.content.find("/", message.content.find("/")+1)]
          arg2 = message.content[message.content.find("/", message.content.find("/")+1)+1:message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)]
          arg3 = message.content[message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)]
          arg4 = message.content[message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)]
          arg5 = message.content[message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)+1:message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/", message.content.find("/")+1)+1)+1)+1)+1)]
          print(arg1)
          print(arg2)
          print(arg3)
          print(arg4)
          print(arg5)

          if arg2 == "false":
            print("Unlooped")
            #time.sleep(arg1)

          else:
            print("Looped")
            print(arg1)
            print(arg2)
            print(arg3)
            print(arg4)
            print(arg5)
            print("arg variables printed")

            @tasks.loop(seconds=int(arg1))
            async def ping_start(message, target_channel_id, role_id):
              print("Entered async ping start")
              global remindcmd
              print(remindcmd)
              message_channel = client.get_channel(int(target_channel_id))
              role = message_channel.guild.get_role(int(role_id))
              if remindcmd == "false":
                global remindcmd
                print("Stopped")
                ping_start.cancel()
                await message_channel.send("Loop stopped.")
                remindcmd = "neither"
                print("remindcmd variable set to neither")
              print(f"Got channel {message_channel} !!remind")
              await message_channel.send(message.replace("{role}", role.mention))
              remindcmd = "true"
              print(remindcmd)

              @ping_start.before_loop
              async def before():
                await client.wait_until_ready()
                print("Finished waiting")

            ping_start.start(arg3, arg4, arg5)

      if message.content.startswith("!!remind/stop/"):
        print("Stop command detected")
        global remindcmd
        print(remindcmd)
        remindcmd = "false"
        print(remindcmd)
        print("remindcmd variable set to false")

# await message.channel.send("Message here")

keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)


问:
Ubuntu 22.04.1 LTS SDL2 wl_proxy_marshal_flags error
I'm a beginner at using Linux, so I'm following a couple of forum threads I've read so far.

I'm trying to compile a C++ program using g++ version 11.3.1, where I have installed SDL2 using the command sudo apt-get install libsdl2-dev and am using the recommended proprietary driver nvidia-driver-525 for my nvidia gtx 1060 graphics card. When I echo $XDG_SESSION_TYPE, it says x11.

However, when I compile the program using the link arguments -lSDL2, it gives me the following compile error:

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/libSDL2.so: undefined reference to `wl_proxy_marshal_flags'
collect2: error: ld returned 1 exit status

When I compile the program with the link arguments: -lSDL2 -lwayland-egl -lwayland-client -lwayland-cursor, it compiles successfully. But then when I try to run the program, it gives me this error:

./bin/main.exe: symbol lookup error: /usr/lib/x86_64-linux-gnu/libdecor-0.so.0: undefined symbol: wl_proxy_marshal_flags


问:
Problem with installing Metadata for the Github voice cloner
I ran pip install -r requirements.txt accordingly to their instruction. It returned an error below. I am using a Macbook and I'm not sure if it supports the Macbook.

```<code>  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
          main()
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-install-ihp6lzb3/pyqt5_2d7c8cf990a14fda93d8e2d2a9918655/project.py", line 63, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/pyqtbuild/project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/pyqtbuild/builder.py", line 69, in apply_user_defaults
          raise PyProjectOptionException('qmake',
      sipbuild.pyproject.PyProjectOptionException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

</code>```

I have no idea of how this code functioned so did nothing.

Body:
I ran pip install -r requirements.txt accordingly to their instruction. It returned an error below. I am using a Macbook and I'm not sure if it supports the Macbook.

  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
          main()
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-install-ihp6lzb3/pyqt5_2d7c8cf990a14fda93d8e2d2a9918655/project.py", line 63, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/pyqtbuild/project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/sipbuild/project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "/private/var/folders/g8/3z75tlj1135gfxby5h4z8wlr0000gn/T/pip-build-env-ji0fn1rh/overlay/lib/python3.10/site-packages/pyqtbuild/builder.py", line 69, in apply_user_defaults
          raise PyProjectOptionException('qmake',
      sipbuild.pyproject.PyProjectOptionException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I have no idea of how this code functioned so did nothing.


问:
Selenium - Get PixiJS canvas element?
I'm currently trying to automate a Starbucks game made in PixiJS. Chrome's inspect element can find the canvas object, but not the elements within that canvas. I just need to get the position of an image or object on the screen. I also found this tool called pixi-inspector that apparently can assist with debugging PixiJS in Chrome, but I can't figure out how to use it in Google Chrome or Selenium with Chromedriver.

I'm using Selenium with Python, here's the URL to the game: https://www.starbucksforlife.com/#/holiday-run (you need a Starbucks account to actually play the game)

If someone could help me figure out how to get the position of an image within a PixiJS canvas, that would be very much appreciated.

Thanks.

Title: Selenium - Get PixiJS canvas element?


问:
v8_*_cc.pdb files are missing. How do I get them?
(I am working with Windows 10)

I need to update V8 in a project that uses V8 5.8 to V8 7.9.
In the project with the old library I get these files: v8_*.lib, v8_*_cc.pdb, natives_blob.bin and snapshot_blob.bin

I have managed to build V8 7.9, but I do not get the v8_*_cc.pdb files.
How do I create these files? Thanks!

I followed the proceure described here.
This got me the .bin and .lib files. but not the .pdb files.


问:
Dotnet how to serialize binary data for mongo
I've got file data that I need to save in mongo in a dotnet application. The data needs to be serialized to mongo and then deserialized in a worker thread as (ideally) the same object.
I've been finding the tooling a little esoteric (maybe I don't know the right places to look yet).
Given the following object

```<code>public class File {
  public IEnumerable<byte> Data { get; set; }
  public string C { get; set; }
  public string D { get; set; }
}

public class X {
  public IEnumerable<File> Files { get; set; }
  public string A { get; set; }
  public string B { get; set; }
}

...

var toInsert = new X {
 A = "a", B = "b", Files = new []{ new File { Data = <byte array>, C ="c", D = "d" }
}
</code>```

When I insert toInsert into mongo, without any custom serialization, it ends up like

```<code>{
  a: "a",
  b: "b",
  files: [
    {
      c: "c",
      d: "d",
      data: <binary>

    }
  ]
}

</code>```

Which seems fine enough. When I try to pull the object out of mongo (again, without any custom serialization) I get the following error

Cannot deserialize a 'List' from BsonType 'Binary'.

Now, I've tried a lot of different things here - enough that I'm not going to go through the list, but this behavior I found peculiar. The client knows to turn an array of byte into a Binary Bson object but it has no idea how to get it back out?

The question is: what is the idiomatic dotnet / mongo way of serializing bytes to a document and reading them back out?

Body:
I've got file data that I need to save in mongo in a dotnet application. The data needs to be serialized to mongo and then deserialized in a worker thread as (ideally) the same object.
I've been finding the tooling a little esoteric (maybe I don't know the right places to look yet).
Given the following object

public class File {
  public IEnumerable<byte> Data { get; set; }
  public string C { get; set; }
  public string D { get; set; }
}

public class X {
  public IEnumerable<File> Files { get; set; }
  public string A { get; set; }
  public string B { get; set; }
}

...

var toInsert = new X {
 A = "a", B = "b", Files = new []{ new File { Data = <byte array>, C ="c", D = "d" }
}

When I insert toInsert into mongo, without any custom serialization, it ends up like

{
  a: "a",
  b: "b",
  files: [
    {
      c: "c",
      d: "d",
      data: <binary>

    }
  ]
}

Which seems fine enough. When I try to pull the object out of mongo (again, without any custom serialization) I get the following error

Cannot deserialize a 'List' from BsonType 'Binary'.

Now, I've tried a lot of different things here - enough that I'm not going to go through the list, but this behavior I found peculiar. The client knows to turn an array of byte into a Binary Bson object but it has no idea how to get it back out?

The question is: what is the idiomatic dotnet / mongo way of serializing bytes to a document and reading them back out?


问:
message.content return nothing (discord)
When I execute the "!close" command, nothing happens, the code is not launched.

```<code>if (message.content.startsWith("!close")) {

...

</code>```

So I did this:

```<code>console.log(message.content)

</code>```

And that surprises me because nothing is returned.

Do you know where it can come from?
Thanks.

Body:
When I execute the "!close" command, nothing happens, the code is not launched.

if (message.content.startsWith("!close")) {

...

So I did this:

console.log(message.content)

And that surprises me because nothing is returned.

Do you know where it can come from?
Thanks.


问:
Laravel errors with autoload.php and Illuminate?
Hello Laravel & Nginx server specialists,

I'm new to Laravel so I got these errors when installing a Laravel script on my VPS using Nginx, MariaDB, Php 7.4, Laravel 8.

Can anyone share ideas so that maybe I figure out what I'm wrong? Thank you very much!

```<code>PHP Warning:  file_exists(): open_basedir restriction in effect. File(/autoload.php) is not within the allowed path(s): (/home/my-domain-path/:/tmp:/var/run/cache-nginx/my-domain/) in /home/my-domain-path/public_html/core/vendor/vonage/nexmo-bridge/src/Autoloader.php on line 69

[previous exception] [object] (ErrorException(code: 0): file_exists(): open_basedir restriction in effect. File(/) is not within the allowed path(s): (/home/my-domain-path/:/tmp:/var/run/cache-nginx/my-domain/) at /home/my-domain-path/public_html/core/app/Http/Helpers/helpers.php:460)
</code>```

Body:
Hello Laravel & Nginx server specialists,

I'm new to Laravel so I got these errors when installing a Laravel script on my VPS using Nginx, MariaDB, Php 7.4, Laravel 8.

Can anyone share ideas so that maybe I figure out what I'm wrong? Thank you very much!

PHP Warning:  file_exists(): open_basedir restriction in effect. File(/autoload.php) is not within the allowed path(s): (/home/my-domain-path/:/tmp:/var/run/cache-nginx/my-domain/) in /home/my-domain-path/public_html/core/vendor/vonage/nexmo-bridge/src/Autoloader.php on line 69

[previous exception] [object] (ErrorException(code: 0): file_exists(): open_basedir restriction in effect. File(/) is not within the allowed path(s): (/home/my-domain-path/:/tmp:/var/run/cache-nginx/my-domain/) at /home/my-domain-path/public_html/core/app/Http/Helpers/helpers.php:460)