问:
Force Jupyter to print and not display
I am using Jupyter notebooks in Visual Studio Code to present lab sessions for my Python programming course, albeit I am recommending students to work with .py files for themselves and their submissions. Ideally I would like the output of my Python cells to be identical to a Python console, and not pretty-printed by display.

I have already added

```<code>"jupyter.runStartupCommands": [
        "from IPython.core.interactiveshell import InteractiveShell",
        "InteractiveShell.ast_node_interactivity = 'all'"
]
</code>```

to settings.json to ensure I get all output but it is still passed to display. However, in a Python console, running int shows the representation <class 'int'>, whereas in the notebook it just shows int. Is there a way to force the Python cells to print and not display, so that the output is identical?

Title: Force Jupyter to print and not display

Body:
I am using Jupyter notebooks in Visual Studio Code to present lab sessions for my Python programming course, albeit I am recommending students to work with .py files for themselves and their submissions. Ideally I would like the output of my Python cells to be identical to a Python console, and not pretty-printed by display.

I have already added

"jupyter.runStartupCommands": [
        "from IPython.core.interactiveshell import InteractiveShell",
        "InteractiveShell.ast_node_interactivity = 'all'"
]

to settings.json to ensure I get all output but it is still passed to display. However, in a Python console, running int shows the representation <class 'int'>, whereas in the notebook it just shows int. Is there a way to force the Python cells to print and not display, so that the output is identical?


来源: stackexchange

问:
C# Array out of bounds
I have created for loop but it only executes once instead of multiple times. At first it takes value but after increment ment it doesnot executes but catch an exception of array out of bounds and indexoutofexception.

Why this for loop is not repeating, I can't seem to find its solution.

This is my code

```<code>private void CheckForVariable()
        {

            //to split parameter by , then stored in array

            parameter = inputcommand[1].Split(",".ToCharArray());

            for (int i = 0; i < parameter.Length ; i++)
            {
                try
                {
                    //checks if the parameter is an int
                    int test = Convert.ToInt32(parameter[i]);
                    //Console.WriteLine(parameter[i]);
                }
                catch
                {
                    Boolean foundVariable = false;
                    if (foundVariable == false)
                    {
                        foreach (KeyValuePair<string, int> variable in VariableDictionary)
                        {
                            if (variable.Key.Equals(parameter[i]))
                            {
                                parameter[i] = variable.Value.ToString();
                            }
                        }
                    }
                }
            }

        }
</code>```

I tried to do exception handling using try catch, it doesnot seems to work. It is only taking single value instead of multiple times. I want to pass repeated value until it executes as expected.

ContentLicense: CC BY-SA 4.0

Title: C# Array out of bounds

Body:
I have created for loop but it only executes once instead of multiple times. At first it takes value but after increment ment it doesnot executes but catch an exception of array out of bounds and indexoutofexception.

Why this for loop is not repeating, I can't seem to find its solution.

This is my code

private void CheckForVariable()
        {

            //to split parameter by , then stored in array

            parameter = inputcommand[1].Split(",".ToCharArray());

            for (int i = 0; i < parameter.Length ; i++)
            {
                try
                {
                    //checks if the parameter is an int
                    int test = Convert.ToInt32(parameter[i]);
                    //Console.WriteLine(parameter[i]);
                }
                catch
                {
                    Boolean foundVariable = false;
                    if (foundVariable == false)
                    {
                        foreach (KeyValuePair<string, int> variable in VariableDictionary)
                        {
                            if (variable.Key.Equals(parameter[i]))
                            {
                                parameter[i] = variable.Value.ToString();
                            }
                        }
                    }
                }
            }

        }

I tried to do exception handling using try catch, it doesnot seems to work. It is only taking single value instead of multiple times. I want to pass repeated value until it executes as expected.


问:
Dbeaver - run all query without selecting it (CTEs)
Is it possible to run the whole SQL query with all CTEs without selecting the code?

eg:
with CTE1 as (..),
CTE2 as (..),
..
CTE30 as (..),
select * from CTE30;

What I want is to have the cursor at last line and ctrl+enter and runs the code without me selecting it. (In datagrip its possible. )


问:
Comparison circle plot in Python/Pandas
Is there a way to create a comparison circle plot in python on Pandas dataframe, something similar to this https://docs.tibco.com/pub/spotfire/7.0.1/doc/html/box/box_what_are_comparison_circles.htm

preferably using plotly, panda plot, matplotlib etc

Title: Comparison circle plot in Python/Pandas


问:
how can I fixe position of bar graph using Plotly in react-native
Actually, my bar graph is moving screen how can I fix the position of the graph?

I tried using displayModebar false but actually, I'm not getting exact properties to fix it.


问:
How do I create an interacted trend variable?
I have a dataset with the dependant variable CoD, independent variable IM and the control variables ln.bo, MA, LEV, BTM, ROA and sd_cfo. I have dummies for year and industry.

I need to create a trend variable that captures only how IM's effect on CoD has changed during the years. The years range from 2010-2021. Each year is assigned a value of 1-13.

I've tried creating an interaction variable by adding IM:Time into the lm function.
The time variable is the year, ranging from 2010-2021. Each year occurs more than once in the Time column. Does this mean I should assign a binary value for each year instead? Regression results show IM:Time1, IM:Time2 and so on.

If I only had 1 independant variable I'm quite certain the formula would've looked like this:
CoD = b0 + b1Time + b2IM + b3IM interacted with time + e.

My question is how the code should look for an interacted trend variable for IM. In the end I would like to know if IM's effect on CoD has increased or decreased during the years.

Thank you.


问:
Is it pissible to login using Cognito Social Login without a hosted UI?
I'm using react-google-login and amazon-cognito-identity-js packages to log my users in.

I'd like to use the amazon-cognito-identity-js's auth method, passing the user's email and password, to call Cognito functions and set the tokens to local storage.

However, coming to Cognito Social Login, it is only possible to use this URI: https://doamin.auth.us-region.amazoncognito.com/login?response_type=token&client_id=*****&redirect_uri=http://localhost:3000.

On clicking the URL, it redirects to call back url. Can i make this process like amazon-cognito-identity-js authenticate method?


问:
Stripe subscription schedule update - disable prorations
While I try to update subscription, invoice is unnecessary complicated.

```<code>await stripe.subscriptionSchedules.update(
      subscriptionSchedule.id,
      {
        end_behavior: 'release',
        phases: [
          {
            start_date: stripeSub.current_period_start,
            end_date: stripeSub.current_period_end,
            proration_behavior: 'none',
            items: [
              {
                price: stripeSub.plan.id,
                plan: stripeSub.plan.id,
                quantity: stripeSub.quantity
              },
            ],
          },
          {
            start_date: stripeSub.current_period_end,
            proration_behavior: 'none',
            items: [
              {
                price: priceId,
                quantity: quantity
              },
            ],
          },
        ],
      }
    );
</code>```

I'm updating subscription at the end of current subscription phase.
In stripe subscription change log proration was created for 6.99 and then -6.99.

stripe log

I tried almost everything from stripe docs docs

Can I avoid this to have only one position on invoice with scheduled subscription cost (new subsctiprion is $60) when invoice will be finalized of current phase end?

Current invoice is
6.99
-6.99
60

I want to only be 60

Body:
While I try to update subscription, invoice is unnecessary complicated.

await stripe.subscriptionSchedules.update(
      subscriptionSchedule.id,
      {
        end_behavior: 'release',
        phases: [
          {
            start_date: stripeSub.current_period_start,
            end_date: stripeSub.current_period_end,
            proration_behavior: 'none',
            items: [
              {
                price: stripeSub.plan.id,
                plan: stripeSub.plan.id,
                quantity: stripeSub.quantity
              },
            ],
          },
          {
            start_date: stripeSub.current_period_end,
            proration_behavior: 'none',
            items: [
              {
                price: priceId,
                quantity: quantity
              },
            ],
          },
        ],
      }
    );

I'm updating subscription at the end of current subscription phase.
In stripe subscription change log proration was created for 6.99 and then -6.99.

stripe log

I tried almost everything from stripe docs docs

Can I avoid this to have only one position on invoice with scheduled subscription cost (new subsctiprion is $60) when invoice will be finalized of current phase end?

Current invoice is
6.99
-6.99
60

I want to only be 60


问:
How to sum all gatherings from my forLoop out of it?
each time my for loop saves a value and then replaces it with the next one

I expect to be able to collect all the values without being replaced by the next one, and all of them can be collected in one variable

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

```<code>    int n = Integer.parseInt(scanner.nextLine());
    int priceForTon = 0;
    int sumTones = 0;
    int allTons = 0;
    int priceForAllTones = 0;
    double average = 0;
    for (int i = 1; i <= n; i++) {
        int tonsOfCar = Integer.parseInt(scanner.nextLine());
        if (tonsOfCar <= 3) {
            priceForTon = 200;
            sumTones = priceForTon * tonsOfCar;
        } else if (tonsOfCar >= 4 && tonsOfCar <=11) {
            priceForTon = 175;
            sumTones = priceForTon * tonsOfCar;
        }else {
            priceForTon = 120;
            sumTones = priceForTon * tonsOfCar;
        }
       allTons += tonsOfCar;
    }

    priceForAllTones = sumTones;
    System.out.printf("%.2f", average);
</code>```

Body:
each time my for loop saves a value and then replaces it with the next one

I expect to be able to collect all the values without being replaced by the next one, and all of them can be collected in one variable

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

    int n = Integer.parseInt(scanner.nextLine());
    int priceForTon = 0;
    int sumTones = 0;
    int allTons = 0;
    int priceForAllTones = 0;
    double average = 0;
    for (int i = 1; i <= n; i++) {
        int tonsOfCar = Integer.parseInt(scanner.nextLine());
        if (tonsOfCar <= 3) {
            priceForTon = 200;
            sumTones = priceForTon * tonsOfCar;
        } else if (tonsOfCar >= 4 && tonsOfCar <=11) {
            priceForTon = 175;
            sumTones = priceForTon * tonsOfCar;
        }else {
            priceForTon = 120;
            sumTones = priceForTon * tonsOfCar;
        }
       allTons += tonsOfCar;
    }

    priceForAllTones = sumTones;
    System.out.printf("%.2f", average);


问:
Error Enoent: no such file or directory multer
I was building a twitter clone app where users can upload tweets with and without images. Before deploying my backend, everything worked fine. Users could upload tweets with and without images. However, after I deployed my backend, I've been unable to get users to upload a tweet with an image. I keep getting this error.

```<code>Error Enoent: no such file or directory
</code>```

This happened after I deployed my backend to Render. It was working fine just before I deployed my backend It is currently impossible to upload an image at the moment. I think this has something to do with the way I'm setting the path in my multer middleware. Here's the middleware I use to upload images:

```<code>import multer from "multer";

const storage = multer.diskStorage({
   destination: function (req, file, cb) {
   cb(null, "uploads");
},

filename: function (req, file, cb) {
   cb(null, new Date().toISOString() + file.originalname);
},
});

const uploadFile = multer({ storage }).single("image");

export default uploadFile;
</code>```

As you can see, I'm setting the storage path to "uploads". However, since I've deployed my backend somewhere else, I think it should be updated. Can anyone tell me how I should update it if I already have a backend hosted somewhere else. If I'm wrong and it has nothing to do with how I'm setting the path, can you tell me what's wrong and how to fix it? Thanks a lot!

Body:
I was building a twitter clone app where users can upload tweets with and without images. Before deploying my backend, everything worked fine. Users could upload tweets with and without images. However, after I deployed my backend, I've been unable to get users to upload a tweet with an image. I keep getting this error.

Error Enoent: no such file or directory

This happened after I deployed my backend to Render. It was working fine just before I deployed my backend It is currently impossible to upload an image at the moment. I think this has something to do with the way I'm setting the path in my multer middleware. Here's the middleware I use to upload images:

import multer from "multer";

const storage = multer.diskStorage({
   destination: function (req, file, cb) {
   cb(null, "uploads");
},

filename: function (req, file, cb) {
   cb(null, new Date().toISOString() + file.originalname);
},
});

const uploadFile = multer({ storage }).single("image");

export default uploadFile;

As you can see, I'm setting the storage path to "uploads". However, since I've deployed my backend somewhere else, I think it should be updated. Can anyone tell me how I should update it if I already have a backend hosted somewhere else. If I'm wrong and it has nothing to do with how I'm setting the path, can you tell me what's wrong and how to fix it? Thanks a lot!


问:
TypeScript intellisense doesn't seem to resolve default module in CJS context
Let's say I have the following basic CJS module:

module.exports = { foo: "bar" }
```
<p>For which I've configured separately following TS typing:</p>
<pre class="lang-js prettyprint-override"><code>declare const test: { foo: string };

export default test;
</code>```

Having that when I try to import this typed module in TypeScript file, Intellisense works as expected:

But when I try to require it in CJS module intellisense fails, as it suggests the .default property, on which then foo is suggested, which is not correct:

What I'm missing in TS setup to have intellisense in CJS working properly? Is it possible to make it right?

Body:
Let's say I have the following basic CJS module:

module.exports = { foo: "bar" }

For which I've configured separately following TS typing:

declare const test: { foo: string };

export default test;

Having that when I try to import this typed module in TypeScript file, Intellisense works as expected:

But when I try to require it in CJS module intellisense fails, as it suggests the .default property, on which then foo is suggested, which is not correct:

What I'm missing in TS setup to have intellisense in CJS working properly? Is it possible to make it right?


问:
Is there a way to customize breadcrumbs in Emacs Orgmode?
When I set org-agenda-prefix-format with %b, I got all higher levels headline shown in the agenda .Is there any way to show only parent level, without other higher levels shown.

I have tried:

```<code>'((todo . " %-25(concat \"[\"(truncate-string-to-width (car (last
(org-get-outline-path))) 21 nil nil t) \"]\")"))
</code>```

It works ok with todo.
However, when I tried on agenda:

```<code>'((agenda . " %-25(concat \"[\"(truncate-string-to-width (car (last
(org-get-outline-path))) 21 nil nil t) \"]\")"))
</code>```

my custom command:

```<code>("n" "Agenda and all TODOs"
      ((agenda "" nil)
       (alltodo "" nil))
      nil)
</code>```

did not work, only agenda but no todo shown.

update:
If there is no agenda items for today, the agenda view shows ok with both todo and agenda. However, If there is an agenda items for today, the todo won't show any more. Does my org-agenda-prefix-format config affect the timeline or something? This really makes me confused.

Body:
When I set org-agenda-prefix-format with %b, I got all higher levels headline shown in the agenda .Is there any way to show only parent level, without other higher levels shown.

I have tried:

'((todo . " %-25(concat \"[\"(truncate-string-to-width (car (last
(org-get-outline-path))) 21 nil nil t) \"]\")"))

It works ok with todo.
However, when I tried on agenda:

'((agenda . " %-25(concat \"[\"(truncate-string-to-width (car (last
(org-get-outline-path))) 21 nil nil t) \"]\")"))

my custom command:

("n" "Agenda and all TODOs"
      ((agenda "" nil)
       (alltodo "" nil))
      nil)

did not work, only agenda but no todo shown.

update:
If there is no agenda items for today, the agenda view shows ok with both todo and agenda. However, If there is an agenda items for today, the todo won't show any more. Does my org-agenda-prefix-format config affect the timeline or something? This really makes me confused.


问:
How to correctly pass a variable from a twig include file to another include twig file
I am trying to pass a variable from one twig include file to another twig include file, (I did post earlier but my question probably wasn't as clear as it could have been). I have 3 files, the view.twig & then a gallery.twig & galleryConfig.twig files

I somehow need to extract the variables from the galleryConfig.twig file and have these available to the gallery.twig file - I know how to pass a variable directly into the template using the with - but how would I use this to pass ALL the variables from galleryConfig.twig into the gallery.twig file

view.twig

```<code><div>
  {% include '@app/components/view/images/galleryConfig.twig' %}
  {% include '@app/components/view/images/gallery.twig' with {
      'holdingImage' : 'somefile.png'
  } %}
</div>
</code>```

galleryConfig.twig

```<code>{% block javascript %}
    <script type="text/javascript">

    </script>
{% endblock %}
{% set holdingImage = ('holding-image.svg') %}
</code>```

gallery.twig

```<code>{% block content %}
<div>
  {{ holdingImage }}
</div>
{% endblock %}
</code>```

Expected result :
The gallery.twig view to display the holdingImage variable which is holding-image.svg and stored in the galleryConfig.twig file

Body:
I am trying to pass a variable from one twig include file to another twig include file, (I did post earlier but my question probably wasn't as clear as it could have been). I have 3 files, the view.twig & then a gallery.twig & galleryConfig.twig files

I somehow need to extract the variables from the galleryConfig.twig file and have these available to the gallery.twig file - I know how to pass a variable directly into the template using the with - but how would I use this to pass ALL the variables from galleryConfig.twig into the gallery.twig file

view.twig

  {% include '@app/components/view/images/galleryConfig.twig' %}
  {% include '@app/components/view/images/gallery.twig' with {
      'holdingImage' : 'somefile.png'
  } %}

galleryConfig.twig

{% block javascript %}

{% endblock %}
{% set holdingImage = ('holding-image.svg') %}

gallery.twig

{% block content %}

  {{ holdingImage }}

{% endblock %}

Expected result :
The gallery.twig view to display the holdingImage variable which is holding-image.svg and stored in the galleryConfig.twig file


问:
How to fix ModuleNotFoundError for grpc?
I just started working on grpc with python and faced problem when I import grpc.

```<code>    import grpc // no module named grpc
</code>```

I'm working on vscode on my MacBook and have tried below to solve this.

```<code>    pip3 install grpcio
    pip3 install grpcio-tools
    python3 -m pip install grpcio
    python3 -m pip install grpcio-tools
</code>```

All above give output:
Requirement already satisfied: grpcio in /user/local/lib/python3.10/site-packages

I have also tried below command

```<code>    python3 -m pip install --hidden-import=pkg_resources
</code>```

Output gives me various other tags listed below.

I'm new to grpc and wasted many hours finding the solution on internet, even chatgpt failed me. Plz kindly help here.

Body:
I just started working on grpc with python and faced problem when I import grpc.

    import grpc // no module named grpc

I'm working on vscode on my MacBook and have tried below to solve this.

    pip3 install grpcio
    pip3 install grpcio-tools
    python3 -m pip install grpcio
    python3 -m pip install grpcio-tools

All above give output:
Requirement already satisfied: grpcio in /user/local/lib/python3.10/site-packages

I have also tried below command

    python3 -m pip install --hidden-import=pkg_resources

Output gives me various other tags listed below.

I'm new to grpc and wasted many hours finding the solution on internet, even chatgpt failed me. Plz kindly help here.


问:
Unable to install scispacy in Jupyter notebook
Unable to install scispacy in Jupyter notebook.
Please find the below error
enter image description here</p>


问:
Grafana: Adding indivisual Ldap user using ldap.toml
I am looking for a solution on how to add a specific LDAP user to access grafana. The current configuration I have in "ldap.toml" works for a group or multiple groups but not sure how to add individual ldap users. We want to only add specific group and individual members to the grafana.

Note: I do not want to add used through UI. Just wanted to make sure whether that is feasible or not.


问:
how to set default date in MUI X MobileDatePicker
in our system we migrate from using { DatePicker, DatePickerProps } from "material-ui-pickers-mui5"
to use { MobileDatePicker, MobileDatePickerProps } from "@mui/x-date-pickers"

we have a property called initialFocusedDate, I tried to use it and there is no property like that in the new MUI X date pickers.

how can I set an initial date for the new MUI X date pickers?


问:
how can I hide overlapping when hovering over a label in an echarts chart?
I have the hide overlap activate but when I hover on a label all the values are shown and I want to show the same values that are shown through the hide overlap.

This is what it looks like with the hide overlap without hover:

And this is how it looks with the hide overlap with hover:

I hope it stays the same with hover and without hover.


问:
Symfony 4 - Problem sending email after change my DNS
Click here

to see my diagram app.

Hey, my client change her DNS (like that : xxx-dns.com to dns.com) and this is ok, except one problem.. In react native app, I have contact form for send message to pro "partner", and this pro partner are in the process of switching their emails from xxx-dns.com to dns.com.
BUT the contact form provide by SwitchMailer doesn't work with the new DNS, I have check all configuration files, same for the server, the controller is (I think) ok.

Please help me, it's been a week

I have var_dump() all information in my controller, check api endpoint, navigate into my server and check configuration files.

This is my contact controller :

```<code>
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Twig\Environment as Twig;

class ContactController extends AbstractController
{
    /**
     * @var string
     */
    private $mailFrom;

    /**
     * @var string
     */
    private $backUrl;

    private $tokenStorage;

    public function __construct(string $mailFrom, string $backUrl, TokenStorageInterface $tokenStorage)
    {
        $this->mailFrom     = $mailFrom;
        $this->backUrl      = $backUrl;
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @Route("/contact", name="app_send_contact")
     */
    public function sendAction(\Swift_Mailer $mailer, Twig $twig, Request $request)
    {
        // Retrieve user
        $currentUser = $this->tokenStorage->getToken()->getUser();
        if (!$currentUser) {
            return $this->json(array('success' => false, 'message' => 'Utilisateur introuvable.'));
        }

        // Prepare parameters
        $contactObject  = $request->request->get('object');
        $contactMessage = $request->request->get('message');

        // Retrieve establishment
        $establishment = $currentUser->getEstablishments()->first();
        if (!$establishment) {
            return $this->json(array('success' => false, 'message' => 'Etablissement introuvable.'));
        }

        // Prepare mail
        $mailTitle = $currentUser->getFirstname() . ' ' . $currentUser->getLastname() . ' vous a envoyé un message : ' . $contactObject;

        // Send mail to establishment
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($establishment->getEmail())
            ->setReplyTo($currentUser->getEmail(), $currentUser->getFirstname() . ' ' . $currentUser->getLastname())
            ->setBody(
                $twig->render(
                    'emails/contact.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        // Prepare mail
        $mailTitle = 'Confirmation de demande de contact';

        // Send mail to parent
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($currentUser->getEmail())
            ->setBody(
                $twig->render(
                    'emails/contact_confirmation.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        return $this->json(array('success' => true));
    }
}```
```

Body:
Click here

to see my diagram app.

Hey, my client change her DNS (like that : xxx-dns.com to dns.com) and this is ok, except one problem.. In react native app, I have contact form for send message to pro "partner", and this pro partner are in the process of switching their emails from xxx-dns.com to dns.com.
BUT the contact form provide by SwitchMailer doesn't work with the new DNS, I have check all configuration files, same for the server, the controller is (I think) ok.

Please help me, it's been a week

I have var_dump() all information in my controller, check api endpoint, navigate into my server and check configuration files.

This is my contact controller :

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Twig\Environment as Twig;

class ContactController extends AbstractController
{
    /**
     * @var string
     */
    private $mailFrom;

    /**
     * @var string
     */
    private $backUrl;

    private $tokenStorage;

    public function __construct(string $mailFrom, string $backUrl, TokenStorageInterface $tokenStorage)
    {
        $this->mailFrom     = $mailFrom;
        $this->backUrl      = $backUrl;
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @Route("/contact", name="app_send_contact")
     */
    public function sendAction(\Swift_Mailer $mailer, Twig $twig, Request $request)
    {
        // Retrieve user
        $currentUser = $this->tokenStorage->getToken()->getUser();
        if (!$currentUser) {
            return $this->json(array('success' => false, 'message' => 'Utilisateur introuvable.'));
        }

        // Prepare parameters
        $contactObject  = $request->request->get('object');
        $contactMessage = $request->request->get('message');

        // Retrieve establishment
        $establishment = $currentUser->getEstablishments()->first();
        if (!$establishment) {
            return $this->json(array('success' => false, 'message' => 'Etablissement introuvable.'));
        }

        // Prepare mail
        $mailTitle = $currentUser->getFirstname() . ' ' . $currentUser->getLastname() . ' vous a envoyé un message : ' . $contactObject;

        // Send mail to establishment
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($establishment->getEmail())
            ->setReplyTo($currentUser->getEmail(), $currentUser->getFirstname() . ' ' . $currentUser->getLastname())
            ->setBody(
                $twig->render(
                    'emails/contact.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        // Prepare mail
        $mailTitle = 'Confirmation de demande de contact';

        // Send mail to parent
        $message = (new \Swift_Message($mailTitle))
            ->setFrom($this->mailFrom)
            ->setTo($currentUser->getEmail())
            ->setBody(
                $twig->render(
                    'emails/contact_confirmation.html.twig',
                    array(
                        'user'            => $currentUser,
                        'establishment'   => $establishment,
                        'contact_object'  => $contactObject,
                        'contact_message' => $contactMessage,
                        'back_url'        => $this->backUrl,
                    )
                ),
                'text/html'
            );
        $mailer->send($message);

        return $this->json(array('success' => true));
    }
}```


问:
Spring Boot Context Path omitted when deployed to AWS Lambda
We have a Spring Boot application that we're trying to migrate to AWS Lambda using the aws-serverless-java-container-springboot2 library. However, on Lambda, we see that the server.servlet.context-path we configure in our application.yml needs to be omitted from the request URI, for the request to be directed to the correct controller endpoint.

Is it possible to have Lambda recognize the context-path defined in application.yml and process the requests without having to omit the context-path when making requests?

We tried using dispatcherServlet to configure the endpoints, however it doesn't seem to be working.


问:
GRPC server streaming, how to increase server ping time
Am working on a project using GRPC which has a node js server and client is Android written in Kotlin.
We are able to setup the connection and the server streaming works as expected.

The problem we are seeing is the server is pinging to client every 30 seconds for keepalive, even though we have kept the keep alive time as 5 minutes.

const options = { 'grpc.keepalive_permit_without_calls': false, "grpc.keepalive_time_ms": 300000 };

On client side

```<code>val builder = ManagedChannelBuilder.forAddress(ipaddress, portno)
                .keepAliveTime(5, TimeUnit.MINUTES)
                .keepAliveWithoutCalls(false)
                .proxyDetector { null }
                .usePlaintext()
            channel = builder.build()
</code>```

From wireshark logs I can see that the server is pinging the client every 30 seconds, is there any way to increase the time frame for pinging? If yes what is the maximum time frame we can keep and what are the code changes to be done ?

Body:
Am working on a project using GRPC which has a node js server and client is Android written in Kotlin.
We are able to setup the connection and the server streaming works as expected.

The problem we are seeing is the server is pinging to client every 30 seconds for keepalive, even though we have kept the keep alive time as 5 minutes.

const options = { 'grpc.keepalive_permit_without_calls': false, "grpc.keepalive_time_ms": 300000 };

On client side

val builder = ManagedChannelBuilder.forAddress(ipaddress, portno)
                .keepAliveTime(5, TimeUnit.MINUTES)
                .keepAliveWithoutCalls(false)
                .proxyDetector { null }
                .usePlaintext()
            channel = builder.build()

From wireshark logs I can see that the server is pinging the client every 30 seconds, is there any way to increase the time frame for pinging? If yes what is the maximum time frame we can keep and what are the code changes to be done ?


问:
How do I create an alert for a plotshape with an offset of -10, such that when the plotshape is displayed on the chart, an alert would trigger
I tried creating a label with an offset and having the alert trigger from the label displayed on the chart but I'm stuck at this point

prd = input.int(defval=10, title='Pivot Period', minval=4, maxval=30, group='Setup')

float src1 = ppsrc == 'High/Low' ? high : math.max(close, open)

float src2 = ppsrc == 'High/Low' ? low : math.min(close, open)

float ph = ta.pivothigh(src1, prd, prd)

float pl = ta.pivotlow(src2, prd, prd)

plotshape(ph and src1, style=shape.triangledown, text='SELL(H)', color=na, textcolor=color.new(#eeff00, 0), location=location.abovebar, offset=-prd)

plotshape(pl and src2, style=shape.triangleup, text='BUY(L)', color=na, textcolor=color.new(#ffffff, 0), location=location.belowbar, offset=-prd)

Lstyle = linestyle == 'Dashed' ? line.style_dashed : linestyle == 'Solid' ? line.style_solid : line.style_dotted

labeloffset = prd

labelcolor = color.red

labeltext = "Sell(R)"

labelcolor2 = color.green

labeltext2 = "Buy(S)"

value1 = ph and src1

value2 = pl and src2

var label ourlabel = na

label_ph = label.new(x = bar_index - labeloffset, y = na, text = labeltext, color = labelcolor, xloc = xloc.bar_index, yloc = yloc.abovebar, textcolor = color.white, style = label.style_label_down, size = size.normal, tooltip = "pl_label_id")

label_pl = label.new(x = bar_index - labeloffset, y = na, text = labeltext2, color = labelcolor2, xloc = xloc.bar_index, yloc = yloc.belowbar, textcolor = color.white, style = label.style_label_up, size = size.normal, tooltip  = "ph_label_id")

// Defined my conditions for the label

if ph and src1

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

else

```<code>label.delete(ourlabel)
</code>```

if pl and src2

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

else

```<code>label.delete(ourlabel)
</code>```

Body:
I tried creating a label with an offset and having the alert trigger from the label displayed on the chart but I'm stuck at this point

prd = input.int(defval=10, title='Pivot Period', minval=4, maxval=30, group='Setup')

float src1 = ppsrc == 'High/Low' ? high : math.max(close, open)

float src2 = ppsrc == 'High/Low' ? low : math.min(close, open)

float ph = ta.pivothigh(src1, prd, prd)

float pl = ta.pivotlow(src2, prd, prd)

plotshape(ph and src1, style=shape.triangledown, text='SELL(H)', color=na, textcolor=color.new(#eeff00, 0), location=location.abovebar, offset=-prd)

plotshape(pl and src2, style=shape.triangleup, text='BUY(L)', color=na, textcolor=color.new(#ffffff, 0), location=location.belowbar, offset=-prd)

Lstyle = linestyle == 'Dashed' ? line.style_dashed : linestyle == 'Solid' ? line.style_solid : line.style_dotted

labeloffset = prd

labelcolor = color.red

labeltext = "Sell(R)"

labelcolor2 = color.green

labeltext2 = "Buy(S)"

value1 = ph and src1

value2 = pl and src2

var label ourlabel = na

label_ph = label.new(x = bar_index - labeloffset, y = na, text = labeltext, color = labelcolor, xloc = xloc.bar_index, yloc = yloc.abovebar, textcolor = color.white, style = label.style_label_down, size = size.normal, tooltip = "pl_label_id")

label_pl = label.new(x = bar_index - labeloffset, y = na, text = labeltext2, color = labelcolor2, xloc = xloc.bar_index, yloc = yloc.belowbar, textcolor = color.white, style = label.style_label_up, size = size.normal, tooltip  = "ph_label_id")

// Defined my conditions for the label

if ph and src1

label_ph

else

label.delete(ourlabel)

if pl and src2

label_pl

else

label.delete(ourlabel)


问:
How do I fix ValueError: Unknown label type: 'unknown'?
Hi I am new to coding and using python. Below is the code I was working on. When I tried to run the line classifier.fit(X_train, y_train), I got an error saying ValueError: Unknown label type: 'unknown'. Can someone please help me fix this error. The sample data output is below the code along with the error detail.

```<code>import pickle as pp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler, MinMaxScaler

from matplotlib import rcParams
import warnings

warnings.filterwarnings("ignore")

# import the data and save it to CSV file

with open (r"C:\Users\user\Downloads\3_class_eso.pkl",mode ="rb") as file_object:
        #new data = pickle.load(file object)
        df_pkl=pd.read_pickle(file_object)

df = pd.DataFrame(df_pkl)
df.to_csv(r'3_class_eso.csv')

#Read the CSV file
with open (r"C:\Users\user\3_class_eso.csv",mode ="rb") as csvfile:
    class_eso_df = pd.read_csv(csvfile)

print(class_eso_df['patient'].unique())
class_eso_df

df.sample(10)

df.describe().T #T transposes the table

df.columns

# split data into input and taget variable(s)

X = df.drop("label", axis=1)
y = df["label"]

# standardize the dataset
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# split into train and test set
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, stratify=y, test_size=0.10, random_state=42
)

# create the classifier
classifier = RandomForestClassifier(n_estimators=100)

# Train the model using the training sets
classifier.fit(X_train, y_train)

# predicting on the test set
y_pred = classifier.predict(X_test)

# Calculate Model Accuracy
print("Accuracy:", accuracy_score(y_test, y_pred))

# check Important features
feature_importances_df = pd.DataFrame(
    {"feature": list(X.columns), "importance": classifier.feature_importances_}
).sort_values("importance", ascending=False)

# Display
feature_importances_df

# visualize important featuers

# Creating a bar plot
sns.barplot(x=feature_importances_df.feature, y=feature_importances_df.importance)
# Add labels to your

plt.xlabel("Feature Importance Score")
plt.ylabel("Features")
plt.title("Visualizing Important Features")
plt.xticks(
    rotation=45, horizontalalignment="right", fontweight="light", fontsize="x-large"
)
plt.show()

# load data with selected features
X = data.drop(["class", "triceps_skinfold_thickness"], axis=1)
y = data["class"]

# standardize the dataset
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# split into train and test set
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, stratify=y, test_size=0.10, random_state=42

# Create a Random Classifier
clf = RandomForestClassifier(n_estimators=100)

# Train the model using the training sets
clf.fit(X_train, y_train)

# prediction on test set
y_pred = clf.predict(X_test)

# Calculate Model Accuracy,
print("Accuracy:", accuracy_score(y_test, y_pred)
</code>```

Data Output:

```<code>label   patient 540nm   545nm   550nm   555nm   560nm   565nm   570nm   575nm   ... 950nm   955nm   960nm   965nm   970nm   975nm   980nm   985nm   990nm   995nm
6304    1   3   0.024611    0.000010    0.002371    0.002024    0.015048    0.016947    0.019419    0.031024    ... 0.810257    0.778144    0.746219    0.719923    0.705200    0.706337    0.698166    0.700408    0.693543    0.688942
10341   3   2   0.035594    0.029440    0.039589    0.036380    0.034254    0.022477    0.008407    0.000010    ... 0.663719    0.654958    0.643946    0.627616    0.617368    0.626918    0.642052    0.654729    0.665916    0.671674
41236   2   1   0.079670    0.098479    0.098112    0.095350    0.064322    0.031531    0.000010    0.003832    ... 0.260165    0.199396    0.143128    0.086094    0.044073    0.018284    0.015145    0.022305    0.027661    0.031981
3281    1   4   0.120939    0.090455    0.084849    0.076669    0.065076    0.032219    0.010626    0.000010    ... 0.721607    0.704053    0.685914    0.670526    0.669169    0.664550    0.666472    0.678053    0.687256    0.700908
10675   3   1   0.088422    0.095814    0.098164    0.097074    0.085914    0.066149    0.043095    0.035502    ... 0.010377    0.003554    0.000789    0.000010    0.003640    0.013012    0.023390    0.035495    0.043304    0.047597
39732   2   5   0.000010    0.002420    0.015663    0.043537    0.050159    0.026479    0.019643    0.032845    ... 0.668189    0.621993    0.570265    0.519619    0.479007    0.448666    0.443152    0.447300    0.468086    0.486695
38267   2   5   0.072105    0.043538    0.048519    0.038973    0.035595    0.015427    0.000010    0.005135    ... 0.649913    0.600812    0.558083    0.514695    0.483440    0.476638    0.476974    0.485495    0.495511    0.502594
47171   2   1   0.146220    0.166851    0.179302    0.190387    0.200632    0.171462    0.150305    0.151566    ... 0.162789    0.122572    0.081285    0.054663    0.035912    0.027628    0.029927    0.025769    0.013812    0.000010
48454   2   1   0.088796    0.079897    0.072558    0.031927    0.017156    0.008509    0.000010    0.013170    ... 0.474571    0.422503    0.371934    0.328638    0.291428    0.271157    0.262695    0.262393    0.265864    0.275453
42354   2   1   0.074457    0.056349    0.078159    0.070054    0.042928    0.016855    0.000010    0.035302    ... 0.438906    0.369661    0.317288    0.257424    0.203798    0.185550    0.192488    0.200904    0.202053    0.203369
10 rows × 94 columns
</code>```

Error Detail:

```<code>ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14888\515166051.py in <module>
      4
      5 # Train the model using the training sets
----> 6 classifier.fit(X_train, y_train)

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    365         self.n_outputs_ = y.shape[1]
    366
--> 367         y, expanded_class_weight = self._validate_y_class_weight(y)
    368
    369         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in _validate_y_class_weight(self, y)
    732
    733     def _validate_y_class_weight(self, y):
--> 734         check_classification_targets(y)
    735
    736         y = np.copy(y)

~\anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    195         "multilabel-sequences",
    196     ]:
--> 197         raise ValueError("Unknown label type: %r" % y_type)
    198
    199

ValueError: Unknown label type: 'unknown'
</code>```

I tried running the the line:

classifier.fit(X_train, y_train) and I got an error saying ValueError: Unknown label type: 'unknown'.

I expected to get the output to show different parameter values of the random forest classifier used during the training process on the train data.

Body:
Hi I am new to coding and using python. Below is the code I was working on. When I tried to run the line classifier.fit(X_train, y_train), I got an error saying ValueError: Unknown label type: 'unknown'. Can someone please help me fix this error. The sample data output is below the code along with the error detail.

import pickle as pp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler, MinMaxScaler

from matplotlib import rcParams
import warnings

warnings.filterwarnings("ignore")

# import the data and save it to CSV file

with open (r"C:\Users\user\Downloads\3_class_eso.pkl",mode ="rb") as file_object:
        #new data = pickle.load(file object)
        df_pkl=pd.read_pickle(file_object)

df = pd.DataFrame(df_pkl)
df.to_csv(r'3_class_eso.csv')

#Read the CSV file
with open (r"C:\Users\user\3_class_eso.csv",mode ="rb") as csvfile:
    class_eso_df = pd.read_csv(csvfile)

print(class_eso_df['patient'].unique())
class_eso_df

df.sample(10)

df.describe().T #T transposes the table

df.columns

# split data into input and taget variable(s)

X = df.drop("label", axis=1)
y = df["label"]

# standardize the dataset
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# split into train and test set
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, stratify=y, test_size=0.10, random_state=42
)

# create the classifier
classifier = RandomForestClassifier(n_estimators=100)

# Train the model using the training sets
classifier.fit(X_train, y_train)

# predicting on the test set
y_pred = classifier.predict(X_test)

# Calculate Model Accuracy
print("Accuracy:", accuracy_score(y_test, y_pred))

# check Important features
feature_importances_df = pd.DataFrame(
    {"feature": list(X.columns), "importance": classifier.feature_importances_}
).sort_values("importance", ascending=False)

# Display
feature_importances_df

# visualize important featuers

# Creating a bar plot
sns.barplot(x=feature_importances_df.feature, y=feature_importances_df.importance)
# Add labels to your

plt.xlabel("Feature Importance Score")
plt.ylabel("Features")
plt.title("Visualizing Important Features")
plt.xticks(
    rotation=45, horizontalalignment="right", fontweight="light", fontsize="x-large"
)
plt.show()

# load data with selected features
X = data.drop(["class", "triceps_skinfold_thickness"], axis=1)
y = data["class"]

# standardize the dataset
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# split into train and test set
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, stratify=y, test_size=0.10, random_state=42

# Create a Random Classifier
clf = RandomForestClassifier(n_estimators=100)

# Train the model using the training sets
clf.fit(X_train, y_train)

# prediction on test set
y_pred = clf.predict(X_test)

# Calculate Model Accuracy,
print("Accuracy:", accuracy_score(y_test, y_pred)

Data Output:

label   patient 540nm   545nm   550nm   555nm   560nm   565nm   570nm   575nm   ... 950nm   955nm   960nm   965nm   970nm   975nm   980nm   985nm   990nm   995nm
6304    1   3   0.024611    0.000010    0.002371    0.002024    0.015048    0.016947    0.019419    0.031024    ... 0.810257    0.778144    0.746219    0.719923    0.705200    0.706337    0.698166    0.700408    0.693543    0.688942
10341   3   2   0.035594    0.029440    0.039589    0.036380    0.034254    0.022477    0.008407    0.000010    ... 0.663719    0.654958    0.643946    0.627616    0.617368    0.626918    0.642052    0.654729    0.665916    0.671674
41236   2   1   0.079670    0.098479    0.098112    0.095350    0.064322    0.031531    0.000010    0.003832    ... 0.260165    0.199396    0.143128    0.086094    0.044073    0.018284    0.015145    0.022305    0.027661    0.031981
3281    1   4   0.120939    0.090455    0.084849    0.076669    0.065076    0.032219    0.010626    0.000010    ... 0.721607    0.704053    0.685914    0.670526    0.669169    0.664550    0.666472    0.678053    0.687256    0.700908
10675   3   1   0.088422    0.095814    0.098164    0.097074    0.085914    0.066149    0.043095    0.035502    ... 0.010377    0.003554    0.000789    0.000010    0.003640    0.013012    0.023390    0.035495    0.043304    0.047597
39732   2   5   0.000010    0.002420    0.015663    0.043537    0.050159    0.026479    0.019643    0.032845    ... 0.668189    0.621993    0.570265    0.519619    0.479007    0.448666    0.443152    0.447300    0.468086    0.486695
38267   2   5   0.072105    0.043538    0.048519    0.038973    0.035595    0.015427    0.000010    0.005135    ... 0.649913    0.600812    0.558083    0.514695    0.483440    0.476638    0.476974    0.485495    0.495511    0.502594
47171   2   1   0.146220    0.166851    0.179302    0.190387    0.200632    0.171462    0.150305    0.151566    ... 0.162789    0.122572    0.081285    0.054663    0.035912    0.027628    0.029927    0.025769    0.013812    0.000010
48454   2   1   0.088796    0.079897    0.072558    0.031927    0.017156    0.008509    0.000010    0.013170    ... 0.474571    0.422503    0.371934    0.328638    0.291428    0.271157    0.262695    0.262393    0.265864    0.275453
42354   2   1   0.074457    0.056349    0.078159    0.070054    0.042928    0.016855    0.000010    0.035302    ... 0.438906    0.369661    0.317288    0.257424    0.203798    0.185550    0.192488    0.200904    0.202053    0.203369
10 rows × 94 columns

Error Detail:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14888\515166051.py in <module>
      4
      5 # Train the model using the training sets
----> 6 classifier.fit(X_train, y_train)

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in fit(self, X, y, sample_weight)
    365         self.n_outputs_ = y.shape[1]
    366
--> 367         y, expanded_class_weight = self._validate_y_class_weight(y)
    368
    369         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:

~\anaconda3\lib\site-packages\sklearn\ensemble\_forest.py in _validate_y_class_weight(self, y)
    732
    733     def _validate_y_class_weight(self, y):
--> 734         check_classification_targets(y)
    735
    736         y = np.copy(y)

~\anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    195         "multilabel-sequences",
    196     ]:
--> 197         raise ValueError("Unknown label type: %r" % y_type)
    198
    199

ValueError: Unknown label type: 'unknown'

I tried running the the line:

classifier.fit(X_train, y_train) and I got an error saying ValueError: Unknown label type: 'unknown'.

I expected to get the output to show different parameter values of the random forest classifier used during the training process on the train data.


问:
Can I run sections of a local Jupyter Notebook on a remote server?
I am running a Jupyter Notebook on my laptop. Is it possible to run one/two cells of the script on a remote server that I have access to?

The remote server is more powerful, however I have been allocated a limited amount of storage on the server so the bulk of work has to happen on my device.

I have used OS.system to run a python script on the server from Jupyter on my laptop, but it seems inefficient.

Both devices are running Ubuntu.


问:
TypeError when creating a marshmallow schema from dataclass inherited from generic class
I'm trying to create a marshmallow schema from dataclass which is inherited from generic type:

users_schema = marshmallow_dataclass.class_schema(Users)()

This is my code:

```<code>from dataclasses import dataclass
from typing import Generic, List, TypeVar

T = TypeVar("T")

@dataclass
class Pagination(Generic[T]):
    items: List[T]

@dataclass
class User:
    pass

@dataclass
class Users(Pagination[User]):
    pass
</code>```

However I get this traceback:

```<code>src/c1client/entities/schemas.py:39: in <module>
    users_schema = marshmallow_dataclass.class_schema(Users)()
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:357: in class_schema
    return _internal_class_schema(clazz, base_schema, clazz_frame)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:403: in _internal_class_schema
    attributes.update(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:406: in <genexpr>
    field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:701: in field_for_schema
    generic_field = _field_for_generic_type(typ, base_schema, typ_frame, **metadata)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:505: in _field_for_generic_type
    child_type = field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:719: in field_for_schema
    if issubclass(typ, Enum):
E   TypeError: issubclass() arg 1 must be a class
</code>```

When I print typ variable from the traceback it is printed like ~T which is really not a class.

Also when I make Pagination class concrete - not generic, it works. So the problem is related to Generic.

Any ideas what could I do to make it work?

Body:
I'm trying to create a marshmallow schema from dataclass which is inherited from generic type:

users_schema = marshmallow_dataclass.class_schema(Users)()

This is my code:

from dataclasses import dataclass
from typing import Generic, List, TypeVar

T = TypeVar("T")

@dataclass
class Pagination(Generic[T]):
    items: List[T]

@dataclass
class User:
    pass

@dataclass
class Users(Pagination[User]):
    pass

However I get this traceback:

src/c1client/entities/schemas.py:39: in <module>
    users_schema = marshmallow_dataclass.class_schema(Users)()
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:357: in class_schema
    return _internal_class_schema(clazz, base_schema, clazz_frame)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:403: in _internal_class_schema
    attributes.update(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:406: in <genexpr>
    field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:701: in field_for_schema
    generic_field = _field_for_generic_type(typ, base_schema, typ_frame, **metadata)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:505: in _field_for_generic_type
    child_type = field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:719: in field_for_schema
    if issubclass(typ, Enum):
E   TypeError: issubclass() arg 1 must be a class

When I print typ variable from the traceback it is printed like ~T which is really not a class.

Also when I make Pagination class concrete - not generic, it works. So the problem is related to Generic.

Any ideas what could I do to make it work?


问:
Getting custom price for customer in priority?
How Can I send to priority: Item SKU, Customer Id, Quantity and get the custom item price?

Tried this API call /LOGPART('demo')?CUSTNAME=111&QNT=5


问:
Ag-grid Autocolumn - sort icon is hidden
I am working on an-grid angular.I would like to know about ag-grid-autocolumn. When sorting is applied the sorting icon,i.e.,sort icon corresponding to ascending || descending is not getting visible. Appreciate if any one can help me with ag-grid autocolumn.

NB:I am using API,Ngrx Store

Thanks in Advance

Tried using seperate actions, seperate functions. Changed styles in SCSS


问:
Spark streaming jobs are failing after running for few days
I am facing this issue, my spark streaming jobs keeps on failing after running for few days with below error:

```<code>AM Container for appattempt_1610108774021_0354_000001 exited with exitCode: -104
Failing this attempt.Diagnostics: Container [pid=31537,containerID=container_1610108774021_0354_01_000001] is running beyond physical memory limits. Current usage: 5.8 GB of 5.5 GB physical memory used; 8.0 GB of 27.3 GB virtual memory used. Killing container.
Dump of the process-tree for container_1610108774021_0354_01_000001 :
|- PID PPID PGRPID SESSID CMD_NAME USER_MODE_TIME(MILLIS) SYSTEM_TIME(MILLIS) VMEM_USAGE(BYTES) RSSMEM_USAGE(PAGES) FULL_CMD_LINE
|- 31742 31537 31537 31537 (java) 1583676 58530 8499392512 1507368 /usr/lib/jvm/java-openjdk/bin/java -server -Xmx5078m -
Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143
</code>```

spark submit:

```<code>spark-submit --name DWH-CDC-commonJob --deploy-mode cluster --master yarn --conf spark.sql.shuffle.partitions=10 --conf  spark.eventLog.enabled=false --conf spark.sql.caseSensitive=true --conf spark.driver.memory=5078M --class com.aos.Loader --jars file:////home/hadoop/lib/* --executor-memory 5000M  --conf "spark.alert.duration=4" --conf spark.dynamicAllocation.enabled=false --num-executors 3 --files /home/hadoop/log4j.properties,/home/hadoop/application.conf --conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:log4j.properties" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:log4j.properties" streams_2.11-1.0.jar application.conf
</code>```

Have tried increasing the spark.executor.memoryOverhead but it fails after few days, I want to understand how we can arrive to number  where it can run without any interruptions. Or is there any other configuration that I am missing.
Spark 2.4 version
aws EMR: 5.23
scala :2.11.12
Two data nodes( vCPU 4, 16 GB ram each).

Body:
I am facing this issue, my spark streaming jobs keeps on failing after running for few days with below error:

AM Container for appattempt_1610108774021_0354_000001 exited with exitCode: -104
Failing this attempt.Diagnostics: Container [pid=31537,containerID=container_1610108774021_0354_01_000001] is running beyond physical memory limits. Current usage: 5.8 GB of 5.5 GB physical memory used; 8.0 GB of 27.3 GB virtual memory used. Killing container.
Dump of the process-tree for container_1610108774021_0354_01_000001 :
|- PID PPID PGRPID SESSID CMD_NAME USER_MODE_TIME(MILLIS) SYSTEM_TIME(MILLIS) VMEM_USAGE(BYTES) RSSMEM_USAGE(PAGES) FULL_CMD_LINE
|- 31742 31537 31537 31537 (java) 1583676 58530 8499392512 1507368 /usr/lib/jvm/java-openjdk/bin/java -server -Xmx5078m -
Container killed on request. Exit code is 143
Container exited with a non-zero exit code 143

spark submit:

spark-submit --name DWH-CDC-commonJob --deploy-mode cluster --master yarn --conf spark.sql.shuffle.partitions=10 --conf  spark.eventLog.enabled=false --conf spark.sql.caseSensitive=true --conf spark.driver.memory=5078M --class com.aos.Loader --jars file:////home/hadoop/lib/* --executor-memory 5000M  --conf "spark.alert.duration=4" --conf spark.dynamicAllocation.enabled=false --num-executors 3 --files /home/hadoop/log4j.properties,/home/hadoop/application.conf --conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:log4j.properties" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:log4j.properties" streams_2.11-1.0.jar application.conf

Have tried increasing the spark.executor.memoryOverhead but it fails after few days, I want to understand how we can arrive to number  where it can run without any interruptions. Or is there any other configuration that I am missing.
Spark 2.4 version
aws EMR: 5.23
scala :2.11.12
Two data nodes( vCPU 4, 16 GB ram each).


问:
ngOnChanges() not working after data update
I have a problem with updating value using NgOnChanges.

I am sharing data between components using @Input() decorator.

Component 1 html:

```<code> <div class="container-right">
    <app-transaction-details [clickedElement] = clickedElement></app-transaction-details>
</div>
</code>```

Component 2

```<code>@Input() clickedElement?: Transaction
</code>```

Clicked element is a tr row which is selected and passed after click.

```<code><tr mat-row *matRowDef="let row; columns: displayedColumns"
            class="single-row" (click) = "clickedElement = row" ></tr>
</code>```

Now in my Component 2 I want to invoke function every time that clickedElement data changes.
I have tried implement OnChanges interface but it doesn't work - getPossibleBalance() is called only if I select different row.

```<code> export class TransactionDetailsComponent implements OnChanges {

  @Input() clickedElement?: Transaction
  possibleBalance = ""

  ngOnChanges(changes: SimpleChanges): void {
    if(changes.clickedElement){
      this.possibleBalance = this.getPossibleBalance()
    }
  }
</code>```

So my question is what am I doing wrong?

Body:
I have a problem with updating value using NgOnChanges.

I am sharing data between components using @Input() decorator.

Component 1 html:

    <app-transaction-details [clickedElement] = clickedElement></app-transaction-details>

Component 2

@Input() clickedElement?: Transaction

Clicked element is a tr row which is selected and passed after click.

Now in my Component 2 I want to invoke function every time that clickedElement data changes.
I have tried implement OnChanges interface but it doesn't work - getPossibleBalance() is called only if I select different row.

 export class TransactionDetailsComponent implements OnChanges {

  @Input() clickedElement?: Transaction
  possibleBalance = ""

  ngOnChanges(changes: SimpleChanges): void {
    if(changes.clickedElement){
      this.possibleBalance = this.getPossibleBalance()
    }
  }

So my question is what am I doing wrong?


问:
Unable to Handle Exception with @ErrorHandler Annotation
I'm new to Spring Boot. I'm trying to handle a exception when a value is null. Basically, its a value that I'm suppose to get from another external service (using restTemplate.exchange() method) which is currently down, so a null value gets assigned to that variable. Here's the code for the same service:

```<code>        ResponseEntity<AuthenticationResponse> respNode = null;
        try {
            respNode = restTemplate.exchange(url, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<AuthenticationResponse>() {});
        } catch (Exception e) {
            if (respNode == null) {
                log.info("Unable to reach: {} ", url);
                throw new AuthServerException("Auth Server Not Found");
            }
        }
</code>```

I created a custom Exception to handle the scenario if the value is null. The Exception is thrown and I'm able to read it in the logs, but I'm not able to handle it.

AuthServerException.java

```<code>package com.nokia.sp.module.myVerify.portalapp.exception;

public class AuthServerException extends NullPointerException {
    private static final long serialVersionUID = 1L;

    public AuthServerException(String message) {
        super(message);
    }
}
</code>```

Controller:

```<code>@Controller
@RequiredArgsConstructor
public class LandingPageController {
    @ExceptionHandler(AuthServerException.class)
    public ModelAndView AuthServerExceptionHandler(AuthServerException e) {
        log.info(e.getMessage());
        ModelAndView mav = new ModelAndView();
        mav.setViewName("auth-server-handler");
        return mav;
    }
}
</code>```

Am I missing something or have I made any syntax Error? Please do help me with the same. Thank you!

Body:
I'm new to Spring Boot. I'm trying to handle a exception when a value is null. Basically, its a value that I'm suppose to get from another external service (using restTemplate.exchange() method) which is currently down, so a null value gets assigned to that variable. Here's the code for the same service:

        ResponseEntity<AuthenticationResponse> respNode = null;
        try {
            respNode = restTemplate.exchange(url, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<AuthenticationResponse>() {});
        } catch (Exception e) {
            if (respNode == null) {
                log.info("Unable to reach: {} ", url);
                throw new AuthServerException("Auth Server Not Found");
            }
        }

I created a custom Exception to handle the scenario if the value is null. The Exception is thrown and I'm able to read it in the logs, but I'm not able to handle it.

AuthServerException.java

package com.nokia.sp.module.myVerify.portalapp.exception;

public class AuthServerException extends NullPointerException {
    private static final long serialVersionUID = 1L;

    public AuthServerException(String message) {
        super(message);
    }
}

Controller:

@Controller
@RequiredArgsConstructor
public class LandingPageController {
    @ExceptionHandler(AuthServerException.class)
    public ModelAndView AuthServerExceptionHandler(AuthServerException e) {
        log.info(e.getMessage());
        ModelAndView mav = new ModelAndView();
        mav.setViewName("auth-server-handler");
        return mav;
    }
}

Am I missing something or have I made any syntax Error? Please do help me with the same. Thank you!


问:
How can I download an excel file with sheetjs that the backend sends me?
I have been working with sheetjs for several days and I cannot download the file that it sends me, the library cannot process it and it blocks my entire page. What should I do?

this is the file that the backend sends me
this is the code i was using

```<code>axios.toExcel(datos).then((res)=>{
    const blob = new Blob([res])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'demo.xlsx'
    a.click()
})
</code>```

How can I download an excel file with sheetjs that the backend sends me?

Body:
I have been working with sheetjs for several days and I cannot download the file that it sends me, the library cannot process it and it blocks my entire page. What should I do?

this is the file that the backend sends me
this is the code i was using

axios.toExcel(datos).then((res)=>{
    const blob = new Blob([res])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'demo.xlsx'
    a.click()
})

How can I download an excel file with sheetjs that the backend sends me?


问:
Limit Download Speed PHP Remote Files
I am looking to limit download speed of a file, I have found the below thread on here which works wonders for locally stored files, however my files are stored on an external server and I'm not entirely sure how to make this work with said server.

Reference:
Limit download speed using PHP

Code:

```<code><?php
set_time_limit(0);

// local file that should be send to the client
$local_file = 'https://remoteserver.com/example.mp4';
// filename that the user gets as default
$download_file = 'https://remoteserver.com/example.mp4';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 1024;
if(file_exists($local_file) && is_file($local_file)) {
    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();
    // open file stream
    $file = fopen($local_file, "r");
    while(!feof($file)) {

        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));

        // flush the content to the browser
        flush();

        // sleep one second
        sleep(1);
    }

    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

if ($dl) {
} else {
    header('HTTP/1.0 503 Service Unavailable');
    die('Abort, you reached your download limit for this file.');
}
?>
</code>```

Both servers share the same base domain, just different subdomains. I could limit download speed using httpd configuration on the remote server, however I am looking to make different speeds for different user permissions and this would just result in an overall limitation.

My Solution:

I have used httpd / apache2 config to limit download speeds to a specified URL for example https://remoteserver.com/slow/... and https://remoteserver.com/fast/... using the below.

```<code><Location "/slow">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  5120
    SetEnv rate-initial-burst 5120
</Location>

<Location "/fast">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  204800
    SetEnv rate-initial-burst 204800
</Location>
</code>```

I then used .htaccess write to include that part of the URL for me as my file structure already existed and couldn't be split into subfolders.

```<code>RewriteEngine On
RewriteRule ^/?(?:slow|fast)(/downloads/.+)$ $1 [L,NC]
</code>```

Title: Limit Download Speed PHP Remote Files

Body:
I am looking to limit download speed of a file, I have found the below thread on here which works wonders for locally stored files, however my files are stored on an external server and I'm not entirely sure how to make this work with said server.

Reference:
Limit download speed using PHP

Code:

<?php
set_time_limit(0);

// local file that should be send to the client
$local_file = 'https://remoteserver.com/example.mp4';
// filename that the user gets as default
$download_file = 'https://remoteserver.com/example.mp4';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 1024;
if(file_exists($local_file) && is_file($local_file)) {
    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();
    // open file stream
    $file = fopen($local_file, "r");
    while(!feof($file)) {

        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));

        // flush the content to the browser
        flush();

        // sleep one second
        sleep(1);
    }

    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

if ($dl) {
} else {
    header('HTTP/1.0 503 Service Unavailable');
    die('Abort, you reached your download limit for this file.');
}
?>

Both servers share the same base domain, just different subdomains. I could limit download speed using httpd configuration on the remote server, however I am looking to make different speeds for different user permissions and this would just result in an overall limitation.

My Solution:

I have used httpd / apache2 config to limit download speeds to a specified URL for example https://remoteserver.com/slow/... and https://remoteserver.com/fast/... using the below.

<Location "/slow">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  5120
    SetEnv rate-initial-burst 5120
</Location>

<Location "/fast">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  204800
    SetEnv rate-initial-burst 204800
</Location>

I then used .htaccess write to include that part of the URL for me as my file structure already existed and couldn't be split into subfolders.

RewriteEngine On
RewriteRule ^/?(?:slow|fast)(/downloads/.+)$ $1 [L,NC]


问:
how to stop slick slider flickering at the end of a loop when using Iframe?
I am using slick slider for making an slider and for its item I am using some iframe. when you click at next button when a cycle ends and it wants to go to the first slide you can see a flickering (blinking ) . this does not happen if I use images instead of iframe or when I hit previous button. I used a lot of solution that I found like : useTransform : false or backface-visibility : hidden and some other CSS styles that others have suggested as solution but none of them worked. you can run my code snippet to see this problem. hit next button and see the flickering . sorry for styling its not the point.

$(".video-gallery__slick-slider").slick({
  autoplay: false,
  autoplaySpeed: 3000,
  draggable: true,
  arrows: true,
  dotsClass: "video-slick-dots",
  useTransform: false,
  dots: true,
  slidesToShow: 3,
  slidesToScroll: 3,
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video-gallery {
  &__category {
    margin: 8rem 6rem;
    &--row {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      gap: 1rem;
      margin: 2rem auto;
      width: 80%;
      border-bottom: 1px solid #ff4f00;

    }
  }
  &__slick-slider {
    background-color: transparent !important;
    width: 100%;
    ul {
      list-style: none !important;
      margin-bottom: 1rem;
    }
  }
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-arrow.slick-prev {
  right: 0% !important;
  top:9.85rem !important;
  width: 4rem;
  position:absolute
}

.slick-arrow.slick-next {
  right: -1.5rem !important;
  width: 3rem;
}

.video-slick-dots {
  display: flex;
  gap: 1rem;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  button {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: #ff4f00;
    color: #fff;
    font-size: 0.9rem;
    font-weight: bold;
  }
}

.iframe-container {
}
iframe {
  border: 2px solid #ff4f00;
  transition: all 0.5s;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  width: 100%;
  &:hover {
    transform: scale(1.05);
  }
}

.slick-slider {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  -webkit-perspective: 2000px;
  perspective: 2000px;
}
.slick-track,
.slick-list {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  -webkit-perspective: 2000px;
  perspective: 2000px;
}

.slick-slide,
.slick-slider .slick-track,
.slick-slider .slick-list {
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);

  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);

  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -ms-perspective: 1000;
  perspective: 1000;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  backface-visibility: hidden;
}</code>```

  <title>Insoo studio video Gallery</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">

  <link rel="stylesheet" href="../../css/style.css">

  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" />

```

Body:
I am using slick slider for making an slider and for its item I am using some iframe. when you click at next button when a cycle ends and it wants to go to the first slide you can see a flickering (blinking ) . this does not happen if I use images instead of iframe or when I hit previous button. I used a lot of solution that I found like : useTransform : false or backface-visibility : hidden and some other CSS styles that others have suggested as solution but none of them worked. you can run my code snippet to see this problem. hit next button and see the flickering . sorry for styling its not the point.

$(".video-gallery__slick-slider").slick({
  autoplay: false,
  autoplaySpeed: 3000,
  draggable: true,
  arrows: true,
  dotsClass: "video-slick-dots",
  useTransform: false,
  dots: true,
  slidesToShow: 3,
  slidesToScroll: 3,
});

.video-gallery {
  &__category {
    margin: 8rem 6rem;
    &--row {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      gap: 1rem;
      margin: 2rem auto;
      width: 80%;
      border-bottom: 1px solid #ff4f00;

    }
  }
  &__slick-slider {
    background-color: transparent !important;
    width: 100%;
    ul {
      list-style: none !important;
      margin-bottom: 1rem;
    }
  }
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-arrow.slick-prev {
  right: 0% !important;
  top:9.85rem !important;
  width: 4rem;
  position:absolute
}

.slick-arrow.slick-next {
  right: -1.5rem !important;
  width: 3rem;
}

.video-slick-dots {
  display: flex;
  gap: 1rem;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  button {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    background-color: #ff4f00;
    color: #fff;
    font-size: 0.9rem;
    font-weight: bold;
  }
}

.iframe-container {
}
iframe {
  border: 2px solid #ff4f00;
  transition: all 0.5s;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  width: 100%;
  &:hover {
    transform: scale(1.05);
  }
}

.slick-slider {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  -webkit-perspective: 2000px;
  perspective: 2000px;
}
.slick-track,
.slick-list {
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  -webkit-perspective: 2000px;
  perspective: 2000px;
}

.slick-slide,
.slick-slider .slick-track,
.slick-slider .slick-list {
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);

  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);

  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  -ms-perspective: 1000;
  perspective: 1000;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  backface-visibility: hidden;
}

  <title>Insoo studio video Gallery</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
    integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">

  <link rel="stylesheet" href="../../css/style.css">

  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" />


问:
Execution failed for task ':app:minifyReleaseWithR8' - jetified-opencv-4.1.0-runtime.jar:org
While building react native app android build, build fails with the below error.

```<code>* What went wrong:
Execution failed for task ':app:minifyReleaseWithR8'.
> com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: /Users/builder/.gradle/caches/transforms-3/9d54c56caf527c039b9b3330018afb36/transformed/jetified-opencv-4.1.0-runtime.jar:org/opencv/android/BaseLoaderCallback$4.class

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.9.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 2m 40s
859 actionable tasks: 859 executed
</code>```

And also I could find this in the logs

```<code>> Task :app:processReleaseMainManifest
[:@react-native-async-storage] /Users/builder/clone/node_modules/@react-native-async-storage/async-storage/android/build/intermediates/library_manifest/release/AndroidManifest.xml Warning:
    Package name 'com.reactnativecommunity.asyncstorage' used in: :@react-native-async-storage, :react-native-async-storage_async-storage.
[com.websitebeaver:opencv:4.1.0] /Users/builder/.gradle/caches/transforms-3/fcf304f50b7eebb3b0e77318cad199c2/transformed/jetified-opencv-4.1.0/AndroidManifest.xml Warning:
    Package name 'org.opencv' used in: com.websitebeaver:opencv:4.1.0, :openCVLibrary310.
/Users/builder/clone/android/app/src/main/AndroidManifest.xml:12:9-20:20 Warning:
    provider#com.reactnativecommunity.webview.RNCWebViewFileProvider@android:authorities was tagged at AndroidManifest.xml:12 to replace other declarations but no other declaration present
</code>```

So what can I do to resolve this error?

Body:
While building react native app android build, build fails with the below error.

* What went wrong:
Execution failed for task ':app:minifyReleaseWithR8'.
> com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: /Users/builder/.gradle/caches/transforms-3/9d54c56caf527c039b9b3330018afb36/transformed/jetified-opencv-4.1.0-runtime.jar:org/opencv/android/BaseLoaderCallback$4.class

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.9.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 2m 40s
859 actionable tasks: 859 executed

And also I could find this in the logs

> Task :app:processReleaseMainManifest
[:@react-native-async-storage] /Users/builder/clone/node_modules/@react-native-async-storage/async-storage/android/build/intermediates/library_manifest/release/AndroidManifest.xml Warning:
    Package name 'com.reactnativecommunity.asyncstorage' used in: :@react-native-async-storage, :react-native-async-storage_async-storage.
[com.websitebeaver:opencv:4.1.0] /Users/builder/.gradle/caches/transforms-3/fcf304f50b7eebb3b0e77318cad199c2/transformed/jetified-opencv-4.1.0/AndroidManifest.xml Warning:
    Package name 'org.opencv' used in: com.websitebeaver:opencv:4.1.0, :openCVLibrary310.
/Users/builder/clone/android/app/src/main/AndroidManifest.xml:12:9-20:20 Warning:
    provider#com.reactnativecommunity.webview.RNCWebViewFileProvider@android:authorities was tagged at AndroidManifest.xml:12 to replace other declarations but no other declaration present

So what can I do to resolve this error?


问:
Gitlab external job
I need to integrate security scans of my project files (SAST) in my Gitlab CI/CD pipeline, and it's easy to do with just another job in .gitlab-ci.yml, like:

```<code>security-scan:
  stage: test
  image: my_image:latest
  script:
    - scan run project/folder
</code>```

But the problem is that developers can easily comment this part of the code and prevent the job run.
How can I create some kind of external job which will always be running by the trigger and developers would not be able to modify it?

I found this discussion on the Gitlab forum, but I don't get it.

Title: Gitlab external job

Body:
I need to integrate security scans of my project files (SAST) in my Gitlab CI/CD pipeline, and it's easy to do with just another job in .gitlab-ci.yml, like:

security-scan:
  stage: test
  image: my_image:latest
  script:
    - scan run project/folder

But the problem is that developers can easily comment this part of the code and prevent the job run.
How can I create some kind of external job which will always be running by the trigger and developers would not be able to modify it?

I found this discussion on the Gitlab forum, but I don't get it.


问:
How to send data to Segment from a Vue/Nuxt app?
I'm trying to connect to a Segment source from a Vue/Nuxt application. I'm using the @dansmaculotte/nuxt-segment npm package for Segment setup.

Here's the code:

nuxt.config.js

```<code>config = {
  //...
  modules: [
    '@dansmaculotte/nuxt-segment'
  ],
  segment: {
    writeKey: 'SEGMENT_WRITE_KEY',
    disabled: false,
    useRouter: true
  },
  //...
}
</code>```

component.vue

```<code>this.$segment.identify('***', {
  name: '***',
  email: '**@**.com'
});
this.$segment.track('***', { plan: '***' });
this.$segment.page('***');
</code>```

Segment setup:

On the deployed app, Segment is being initialised and does make tracking calls successfully.

But with all that, the data does not come through on Segment. I didn't get any errors that can tell me what's wrong. Not sure what the problem is. Thanks in advance for whoever might be able to help.

Body:
I'm trying to connect to a Segment source from a Vue/Nuxt application. I'm using the @dansmaculotte/nuxt-segment npm package for Segment setup.

Here's the code:

nuxt.config.js

config = {
  //...
  modules: [
    '@dansmaculotte/nuxt-segment'
  ],
  segment: {
    writeKey: 'SEGMENT_WRITE_KEY',
    disabled: false,
    useRouter: true
  },
  //...
}

component.vue

this.$segment.identify('***', {
  name: '***',
  email: '**@**.com'
});
this.$segment.track('***', { plan: '***' });
this.$segment.page('***');

Segment setup:

On the deployed app, Segment is being initialised and does make tracking calls successfully.

But with all that, the data does not come through on Segment. I didn't get any errors that can tell me what's wrong. Not sure what the problem is. Thanks in advance for whoever might be able to help.


问:
Base class observable(variable) remains undefined in spec file - Angular unit testing
I have a componentA that inherits(extends) another one i.e componentB. The problem is unit tests of componentA are breaking because an observable defined in componentB remains undefined in spec.ts.

Relevant part of ComponentB(Base class)

this.storeObservable = this.store.select(selectCandidateState);

Accessing this in ComponentA,

```<code>this.storeObservable.subscribe((candidateState) => {
   this.candidateSkills = candidateState.skills;
   this.unsavedChanges = false;
  });
</code>```

Now the unit test of componentA are breaking with this message:

TypeError: Cannot read property 'subscribe' of undefined,

while pointing to this.storeObservable.subscribe

ComponentA

```<code>export class ComponentA extends ComponentB implements OnInit, OnDestroy
ngOnInit() {
     super.ngOnInit();

this.storeObservable.subscribe((candidateState) => {
  this.candidateSkills = candidateState.skills;
  this.unsavedChanges = false;
});
</code>```

The unit tests

```<code>    let shallow: Shallow<ComponentA>;

  beforeEach(() => {
    const actions$ = new Observable();
    const services = [Store];
    const mockedServices = [ConfigCzarServiceMock({ test: 'property' })];
    shallow = createShallowComponent(
      ComponentA,
      ProfileModule,
      [componentB],
      [],
      services,
      mockedServices,
     );

> All the tests break with above error. TypeError: Cannot read property
> 'subscribe' of undefined,

</code>```

Body:
I have a componentA that inherits(extends) another one i.e componentB. The problem is unit tests of componentA are breaking because an observable defined in componentB remains undefined in spec.ts.

Relevant part of ComponentB(Base class)

this.storeObservable = this.store.select(selectCandidateState);

Accessing this in ComponentA,

this.storeObservable.subscribe((candidateState) => {
   this.candidateSkills = candidateState.skills;
   this.unsavedChanges = false;
  });

Now the unit test of componentA are breaking with this message:

TypeError: Cannot read property 'subscribe' of undefined,

while pointing to this.storeObservable.subscribe

ComponentA

export class ComponentA extends ComponentB implements OnInit, OnDestroy
ngOnInit() {
     super.ngOnInit();

this.storeObservable.subscribe((candidateState) => {
  this.candidateSkills = candidateState.skills;
  this.unsavedChanges = false;
});

The unit tests

    let shallow: Shallow<ComponentA>;

  beforeEach(() => {
    const actions$ = new Observable();
    const services = [Store];
    const mockedServices = [ConfigCzarServiceMock({ test: 'property' })];
    shallow = createShallowComponent(
      ComponentA,
      ProfileModule,
      [componentB],
      [],
      services,
      mockedServices,
     );

> All the tests break with above error. TypeError: Cannot read property
> 'subscribe' of undefined,


问:
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project binance-futures-connector-java
the other day I tried to start using API from Binance. I stumbled across this library I found on Binance Git Hub (https://github.com/binance/binance-futures-connector-java). I never worked with Maven, so I was and still am quite a bit lost.
I followed the installation so firstly I downloaded ZIP. Unzipped it, went to the folder where was pom.xml file and from that path run command in cmd mvn install. I got this error:

```<code>Tests in error:
  testNewOrder(unit.cm_futures.account.TestCMNewOrder)
  testNewOrder(unit.um_futures.account.TestUMNewOrder)

Tests run: 302, Failures: 3, Errors: 2, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.241 s
[INFO] Finished at: 2023-01-12T12:55:38+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project binance-futures-connector-java: There are test failures.
</code>```

My pom.xml file is copy-paste what I downloaded

I see that error comes from tests in testNewOrder(unit.cm_futures.account.TestCMNewOrder) and testNewOrder(unit.um_futures.account.TestUMNewOrder), but I have no idea what to do.
I set the API and KEY in PrivateConfig.

I tried the following:

-Adding this piece of code to pom.xml

```<code><plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.12.4</version>
</plugin>
</code>```

-using command mvn clean install -U
Still getting the same error.

If I somehow fix this error later when I create a new project in IntelliJ IDEA. I choose Maven and in pom.xml just add(from installation instructions)

```<code>> <dependency>
>     <groupId>io.github.binance</groupId>
>     <artifactId>binance-futures-connector-java</artifactId>
>     <version>LATEST_VERSION(1.0.0)</version>
> </dependency>
</code>```

correct?

Thanks in advance!

Body:
the other day I tried to start using API from Binance. I stumbled across this library I found on Binance Git Hub (https://github.com/binance/binance-futures-connector-java). I never worked with Maven, so I was and still am quite a bit lost.
I followed the installation so firstly I downloaded ZIP. Unzipped it, went to the folder where was pom.xml file and from that path run command in cmd mvn install. I got this error:

Tests in error:
  testNewOrder(unit.cm_futures.account.TestCMNewOrder)
  testNewOrder(unit.um_futures.account.TestUMNewOrder)

Tests run: 302, Failures: 3, Errors: 2, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.241 s
[INFO] Finished at: 2023-01-12T12:55:38+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project binance-futures-connector-java: There are test failures.

My pom.xml file is copy-paste what I downloaded

I see that error comes from tests in testNewOrder(unit.cm_futures.account.TestCMNewOrder) and testNewOrder(unit.um_futures.account.TestUMNewOrder), but I have no idea what to do.
I set the API and KEY in PrivateConfig.

I tried the following:

-Adding this piece of code to pom.xml

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.12.4</version>
</plugin>

-using command mvn clean install -U
Still getting the same error.

If I somehow fix this error later when I create a new project in IntelliJ IDEA. I choose Maven and in pom.xml just add(from installation instructions)

> <dependency>
>     <groupId>io.github.binance</groupId>
>     <artifactId>binance-futures-connector-java</artifactId>
>     <version>LATEST_VERSION(1.0.0)</version>
> </dependency>

correct?

Thanks in advance!


问:
How to properly setup TTS in Android app?
So I'm creating my TextToSpeach instance in onCreate() method and i'm call textToSpeach.shutdown() in onDestroy(). It works fine until my app crashes. After my app crashed I get TTS app crash also. Can I prevent this behavior? Can I init TTS just befor call tts.speak() and shutdown it every time? Or do you have better solution?


问:
Fill missing dates with zero in a data.table by an inplace way
Firstly,
I checked the similar questions and answers but couldn't find an inplace solution for implementing solutions for a huge table. As a toy data, my data structure is like this;

```<code>  product location date       value
  <chr>   <chr>    <date>     <int>
1 A       X        2022-01-01    22
2 A       Y        2022-01-03    82
3 B       Y        2022-01-03    27
4 C       Z        2022-01-01    74
5 C       Z        2022-01-02    58
6 C       Z        2022-01-03    68
7 C       Z        2022-01-04    75
</code>```

To reproduce;

```<code>df <- structure(list(product = c("A", "A", "B", "C", "C", "C", "C"),
    location = c("X", "Y", "Y", "Z", "Z", "Z", "Z"), date = structure(c(18993,
    18995, 18995, 18993, 18994, 18995, 18996), class = "Date"),
    value = c(22L, 82L, 27L, 74L, 58L, 68L, 75L)), row.names = c(NA,
-7L), class = c("data.table", "data.frame"))
</code>```

I want to duplicate each product&location combination for a date range (2022-01-01 to 2022-01-04) and fill value column with zero.

The desired output should look like;

```<code>   product location date       value
   <chr>   <chr>    <date>     <int>
 1 A       X        2022-01-01    22
 2 A       X        2022-01-02     0
 3 A       X        2022-01-03     0
 4 A       X        2022-01-04     0
 5 A       Y        2022-01-01     0
 6 A       Y        2022-01-02     0
 7 A       Y        2022-01-03    82
 8 A       Y        2022-01-04     0
 9 B       Y        2022-01-01     0
10 B       Y        2022-01-02     0
11 B       Y        2022-01-03    27
12 B       Y        2022-01-04     0
13 C       Z        2022-01-01    74
14 C       Z        2022-01-02    58
15 C       Z        2022-01-03    68
16 C       Z        2022-01-04    75
</code>```

I am familiar with the solutions by tidyr::complete and making distinct tables and cross join them, but my original data is very huge and these solutions are memory inefficient for me. I also tried to split data into smaller parts then fill their missing dates with zero but again in that time I couldn't reunion them because of the memory issue.

How can I fill the missing dates with zero in an inplace way ?

Thanks in advance.

Body:
Firstly,
I checked the similar questions and answers but couldn't find an inplace solution for implementing solutions for a huge table. As a toy data, my data structure is like this;

  product location date       value
  <chr>   <chr>    <date>     <int>
1 A       X        2022-01-01    22
2 A       Y        2022-01-03    82
3 B       Y        2022-01-03    27
4 C       Z        2022-01-01    74
5 C       Z        2022-01-02    58
6 C       Z        2022-01-03    68
7 C       Z        2022-01-04    75

To reproduce;

df <- structure(list(product = c("A", "A", "B", "C", "C", "C", "C"),
    location = c("X", "Y", "Y", "Z", "Z", "Z", "Z"), date = structure(c(18993,
    18995, 18995, 18993, 18994, 18995, 18996), class = "Date"),
    value = c(22L, 82L, 27L, 74L, 58L, 68L, 75L)), row.names = c(NA,
-7L), class = c("data.table", "data.frame"))

I want to duplicate each product&location combination for a date range (2022-01-01 to 2022-01-04) and fill value column with zero.

The desired output should look like;

   product location date       value
   <chr>   <chr>    <date>     <int>
 1 A       X        2022-01-01    22
 2 A       X        2022-01-02     0
 3 A       X        2022-01-03     0
 4 A       X        2022-01-04     0
 5 A       Y        2022-01-01     0
 6 A       Y        2022-01-02     0
 7 A       Y        2022-01-03    82
 8 A       Y        2022-01-04     0
 9 B       Y        2022-01-01     0
10 B       Y        2022-01-02     0
11 B       Y        2022-01-03    27
12 B       Y        2022-01-04     0
13 C       Z        2022-01-01    74
14 C       Z        2022-01-02    58
15 C       Z        2022-01-03    68
16 C       Z        2022-01-04    75

I am familiar with the solutions by tidyr::complete and making distinct tables and cross join them, but my original data is very huge and these solutions are memory inefficient for me. I also tried to split data into smaller parts then fill their missing dates with zero but again in that time I couldn't reunion them because of the memory issue.

How can I fill the missing dates with zero in an inplace way ?

Thanks in advance.