问:
how to connect ClearDB -mysql database to my web app django project
i have deployed my first Dejango webapp to Heroku.
At the begining it was working but it was not connecting the database and loging and also create super user was not working either.

i changed database in heroku from Postgre to ClearDB database because this last one is free in Heroku.

the problem is when i try to python manage.py makemigrations or migrate or createsuperuser it does not work and shows this error:

```<code>**(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
**```

i changed the Database from settings.py but it was not working either:

```
<p>this is the database file from Settings.py</p>
```DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '******', here i have changed from my local database to the new name coming from heroku
        'USER': '******', here i have changed the user for the one coming from Heroku
        'PASSWORD': '******', here i have changed the passworkd for the one coming from Heroku
        'HOST': '****', here i have changed the HOST for the one coming from Heroku
        'PORT': 3306
    }
}
```
```

```
<p>this is the top of Settings.py</p>
```import os
import django_heroku
import dj_database_url
from decouple import config
```
<p>i also changed the allowed hosts</p>
```ALLOWED_HOSTS = ['.herokuapp.com']
```
```thanks

i tried to connec local mysql server but it is not working either.
i do not knwo what else to do
```

Body:
i have deployed my first Dejango webapp to Heroku.
At the begining it was working but it was not connecting the database and loging and also create super user was not working either.

i changed database in heroku from Postgre to ClearDB database because this last one is free in Heroku.

the problem is when i try to python manage.py makemigrations or migrate or createsuperuser it does not work and shows this error:

**(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
**```

i changed the Database from settings.py but it was not working either:

this is the database file from Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '******', here i have changed from my local database to the new name coming from heroku
        'USER': '******', here i have changed the user for the one coming from Heroku
        'PASSWORD': '******', here i have changed the passworkd for the one coming from Heroku
        'HOST': '****', here i have changed the HOST for the one coming from Heroku
        'PORT': 3306
    }
}

this is the top of Settings.py

import os
import django_heroku
import dj_database_url
from decouple import config

i also changed the allowed hosts

ALLOWED_HOSTS = ['.herokuapp.com']

thanks

i tried to connec local mysql server but it is not working either.
i do not knwo what else to do


来源: stackexchange

问:
Adding a Before/After Slider to a Leaflet Map in R
I am presently reading though Uber's H3 documentation and am wondering if its possible to add a before/after slider to a leaflet map created in R.

For visual reference,I am looking to figure out how to add this.

Is there anything readily available in the leaflet or shiny R packages, or do I need to work with javascript to make this?

ContentLicense: CC BY-SA 4.0


问:
How to intercept running python script and execute command within its context?
Here is the situation (as an example) - I ran a ML learning python script (which I wrote) for a long time but I didn't add functionality to save its weights.

My question in this situation is if it's possible to somehow intercept the running python interpreter and execute a command within the program context.

For example since I have model_seq global variable inside the running program - I would like to execute:

```<code>model_seq.save_weights("./model_weights")
</code>```

Inside the process.

I've heard this is somewhat possible with gdb.

(Personally I know this can be done for sure with a C program and gdb - but since Python is compiled and interpreted the steps are a bit unclear for me (and I'm not sure if I would actually need a special python3 build or the default ubuntu one I have running will work))

Body:
Here is the situation (as an example) - I ran a ML learning python script (which I wrote) for a long time but I didn't add functionality to save its weights.

My question in this situation is if it's possible to somehow intercept the running python interpreter and execute a command within the program context.

For example since I have model_seq global variable inside the running program - I would like to execute:

model_seq.save_weights("./model_weights")

Inside the process.

I've heard this is somewhat possible with gdb.

(Personally I know this can be done for sure with a C program and gdb - but since Python is compiled and interpreted the steps are a bit unclear for me (and I'm not sure if I would actually need a special python3 build or the default ubuntu one I have running will work))


问:
i get run time error while submitting my answer while submitting on leetcode. it running successfully and all test cases are correct
```<code>class MyCircularQueue {
    private:
    int * arr;
    int front;
    int rear;
    int size;
public:
    MyCircularQueue(int k) {
        size = k;
        arr = new int [size];
        front = rear = -1;

    }

    bool enQueue(int value) {
        if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
            // cout << "queue is full";
            return false;
        }
        else if(front == -1){
            rear = front = 0;

        }
        else if(rear == size-1 && front != 0){
            rear = 0;
        }
        else{
            rear++;
        }
        arr[rear]= value;
        return true;

    }

    bool deQueue() {
        int ans = arr[front];
        if(front == -1){
            // cout << "queue is Empty ";
            return -1;
        }

        else if(front == rear){
            front = rear = -1;
        }
        else if(front == size-1){
            front = 0;
         }
         else{
             front++;
         }
         return ans;

    }

    int Front() {
        if(front == -1){
            return -1;
        }
        else{
            return arr[front];
        }

    }

    int Rear() {
        if(front == -1){
            return -1;
        }
        else{
            return arr[rear];
        }

    }

    bool isEmpty() {
        if(front == -1){
            return -1;
        }
        else{
            return 1;
        }

    }

    bool isFull() {
        if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
            return 1;
        }
        else {
            return -1;
        }
    }
};

</code>```

run time error.

=================================================================
==34==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000057c at pc 0x00000034b71d bp 0x7ffc594a39b0 sp 0x7ffc594a39a8
READ of size 4 at 0x60300000057c thread T0
#4 0x7f8aefa020b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x60300000057c is located 4 bytes to the left of 24-byte region [0x603000000580,0x603000000598)
allocated by thread T0 here:
#4 0x7f8aefa020b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c067fff8050: fd fd fd fd fa fa fd fd fd fd fa fa fd fd fd fd
0x0c067fff8060: fa fa fd fd fd fd fa fa fd fd fd fa fa fa fd fd
0x0c067fff8070: fd fd fa fa fd fd fd fa fa fa fd fd fd fd fa fa
0x0c067fff8080: fd fd fd fd fa fa fd fd fd fa fa fa 00 00 00 00
0x0c067fff8090: fa fa fd fd fd fd fa fa 00 00 00 00 fa fa fd fd
=>0x0c067fff80a0: fd fd fa fa 00 00 00 00 fa fa 00 00 00 fa fa[fa]
0x0c067fff80b0: 00 00 00 fa fa fa fd fd fd fd fa fa fa fa fa fa
0x0c067fff80c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable:           00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone:       fa
Freed heap region:       fd
Stack left redzone:      f1
Stack mid redzone:       f2
Stack right redzone:     f3
Stack after return:      f5
Stack use after scope:   f8
Global redzone:          f9
Global init order:       f6
Poisoned by user:        f7
Container overflow:      fc
Array cookie:            ac
Intra object redzone:    bb
ASan internal:           fe
Left alloca redzone:     ca
Right alloca redzone:    cb
Shadow gap:              cc
==34==ABORTING

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

the above code is successfully running, but while submitting i get runtime error.

Body:
class MyCircularQueue {
    private:
    int * arr;
    int front;
    int rear;
    int size;
public:
    MyCircularQueue(int k) {
        size = k;
        arr = new int [size];
        front = rear = -1;

    }

    bool enQueue(int value) {
        if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
            // cout << "queue is full";
            return false;
        }
        else if(front == -1){
            rear = front = 0;

        }
        else if(rear == size-1 && front != 0){
            rear = 0;
        }
        else{
            rear++;
        }
        arr[rear]= value;
        return true;

    }

    bool deQueue() {
        int ans = arr[front];
        if(front == -1){
            // cout << "queue is Empty ";
            return -1;
        }

        else if(front == rear){
            front = rear = -1;
        }
        else if(front == size-1){
            front = 0;
         }
         else{
             front++;
         }
         return ans;

    }

    int Front() {
        if(front == -1){
            return -1;
        }
        else{
            return arr[front];
        }

    }

    int Rear() {
        if(front == -1){
            return -1;
        }
        else{
            return arr[rear];
        }

    }

    bool isEmpty() {
        if(front == -1){
            return -1;
        }
        else{
            return 1;
        }

    }

    bool isFull() {
        if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
            return 1;
        }
        else {
            return -1;
        }
    }
};

run time error.

=================================================================
==34==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000057c at pc 0x00000034b71d bp 0x7ffc594a39b0 sp 0x7ffc594a39a8
READ of size 4 at 0x60300000057c thread T0
#4 0x7f8aefa020b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x60300000057c is located 4 bytes to the left of 24-byte region [0x603000000580,0x603000000598)
allocated by thread T0 here:
#4 0x7f8aefa020b2  (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c067fff8050: fd fd fd fd fa fa fd fd fd fd fa fa fd fd fd fd
0x0c067fff8060: fa fa fd fd fd fd fa fa fd fd fd fa fa fa fd fd
0x0c067fff8070: fd fd fa fa fd fd fd fa fa fa fd fd fd fd fa fa
0x0c067fff8080: fd fd fd fd fa fa fd fd fd fa fa fa 00 00 00 00
0x0c067fff8090: fa fa fd fd fd fd fa fa 00 00 00 00 fa fa fd fd
=>0x0c067fff80a0: fd fd fa fa 00 00 00 00 fa fa 00 00 00 fa fa[fa]
0x0c067fff80b0: 00 00 00 fa fa fa fd fd fd fd fa fa fa fa fa fa
0x0c067fff80c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable:           00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone:       fa
Freed heap region:       fd
Stack left redzone:      f1
Stack mid redzone:       f2
Stack right redzone:     f3
Stack after return:      f5
Stack use after scope:   f8
Global redzone:          f9
Global init order:       f6
Poisoned by user:        f7
Container overflow:      fc
Array cookie:            ac
Intra object redzone:    bb
ASan internal:           fe
Left alloca redzone:     ca
Right alloca redzone:    cb
Shadow gap:              cc
==34==ABORTING

the above code is successfully running, but while submitting i get runtime error.


问:
Cannot knit HTML and loading packages problematic
Recently, I stopped being able to knit to html. I did not care at first because my projects just required pdfs. But, then I also experienced problems accessing some packages and downloading packages. I think some how or another when I last updated R (now have the latest version: 4.2.2). I am pretty certain somehow the pathways got crossed or changed or something. I am really not sure.

I would really like to know how to consolidate every R file into just one location (it also somehow got stuck in Onedrive which is problematic for many other reasons). But also I want to knit htmls and use packages (like Hmisc which I used before, but now cannot be found). I asked ChatGPT first and it also could not make sense of the error (or I could not understand its reply)

Here is the error message:

```<code>Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'htmltools' 0.5.3 is already loaded, but >= 0.5.4 is required
Calls: <Anonymous> ... is_bs_theme -> loadNamespace -> namespaceImport -> loadNamespace
Execution halted
</code>```

I tried to make sure all of the necessary permissions were granted at every level of the R files.

I asked ChatGPT and searched the internet

I tried update.packages('htmltools')

and I tried

update.packages()

Got this message:

The downloaded binary packages are in C:\Users\jeffd\AppData\Local\Temp\Rtmp2l6Yt0\downloaded_packages
Warning in install.packages(update[instlib == l, "Package"], l, repos = repos,  :
'lib = "C:/Program Files/R/R-4.2.2/library"' is not writable

I selected "yes" to choose a personal library instead and got this message:

Warning messages:
1: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\cli\libs\x64\cli.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\cli\libs\x64\cli.dll: Permission denied
2: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\digest\libs\x64\digest.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\digest\libs\x64\digest.dll: Permission denied
3: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\htmltools\libs\x64\htmltools.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\htmltools\libs\x64\htmltools.dll: Permission denied
4: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\xfun\libs\x64\xfun.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\xfun\libs\x64\xfun.dll: Permission denied

Body:
Recently, I stopped being able to knit to html. I did not care at first because my projects just required pdfs. But, then I also experienced problems accessing some packages and downloading packages. I think some how or another when I last updated R (now have the latest version: 4.2.2). I am pretty certain somehow the pathways got crossed or changed or something. I am really not sure.

I would really like to know how to consolidate every R file into just one location (it also somehow got stuck in Onedrive which is problematic for many other reasons). But also I want to knit htmls and use packages (like Hmisc which I used before, but now cannot be found). I asked ChatGPT first and it also could not make sense of the error (or I could not understand its reply)

Here is the error message:

Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'htmltools' 0.5.3 is already loaded, but >= 0.5.4 is required
Calls: <Anonymous> ... is_bs_theme -> loadNamespace -> namespaceImport -> loadNamespace
Execution halted

I tried to make sure all of the necessary permissions were granted at every level of the R files.

I asked ChatGPT and searched the internet

I tried update.packages('htmltools')

and I tried

update.packages()

Got this message:

The downloaded binary packages are in C:\Users\jeffd\AppData\Local\Temp\Rtmp2l6Yt0\downloaded_packages
Warning in install.packages(update[instlib == l, "Package"], l, repos = repos,  :
'lib = "C:/Program Files/R/R-4.2.2/library"' is not writable

I selected "yes" to choose a personal library instead and got this message:

Warning messages:
1: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\cli\libs\x64\cli.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\cli\libs\x64\cli.dll: Permission denied
2: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\digest\libs\x64\digest.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\digest\libs\x64\digest.dll: Permission denied
3: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\htmltools\libs\x64\htmltools.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\htmltools\libs\x64\htmltools.dll: Permission denied
4: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\jeffd\AppData\Local\R\win-library\4.2\00LOCK\xfun\libs\x64\xfun.dll to C:\Users\jeffd\AppData\Local\R\win-library\4.2\xfun\libs\x64\xfun.dll: Permission denied


问:
Use of Fortran Modules
When is it customarily appropriate to use modules in fortran.  Ordinarily, one can put subroutines in a file and compile that without problems.  So why and on what conditions is better to use a module?  What advantages do modules have from just the normal subroutines?

I have used modules before.  But at work, the libraries are basically a long list of files that do not use modules.  Thus the question.

Title: Use of Fortran Modules


问:
How to upload log file from Zebra enterprise browser to https server
Zebra Enterpise browser v 2.0 is used in Android 8 in Zebra PS20 personal shopper scanner.
Posting log to https server as described in
https://techdocs.zebra.com/enterprise-browser/3-3/api/Log

with javascript in browser using

```<code>EB.Log.destinationURI = 'https://example.com/cradle/ReceiveLogFile';
EB.Log.sendLogFile()
</code>```

does not send log. Log file contains error

RhodesAppBase.cpp: 245| send_log failed : network error - -1; Body -

Tried to add web logger to browser Config.xml file by adding second LogFile element using

```<code><Logger>
    <LogProtocol   value="FILE"/>
    <LogPort       value="80"/>
    <LogURI        value="file://%INSTALLDIR%/Log.txt"/>
    <LogError      value="1"/>
    <LogWarning    value="1"/>
    <LogInfo       value="1"/>
    <LogTrace      value="0"/>
    <LogUser       value="0"/>
    <LogMemory     value="0"/>
    <LogMemPeriod  value="5000"/>
    <LogMaxSize    value="5000"/>
</Logger>
</code>```

throws the same error. How to send log files to https from browser ?
Log server sample code in

https://github.com/rhomobile/rhologs

psots to http server. Is https supported? All other https urls work in Enterpise Browser

Body:
Zebra Enterpise browser v 2.0 is used in Android 8 in Zebra PS20 personal shopper scanner.
Posting log to https server as described in
https://techdocs.zebra.com/enterprise-browser/3-3/api/Log

with javascript in browser using

EB.Log.destinationURI = 'https://example.com/cradle/ReceiveLogFile';
EB.Log.sendLogFile()

does not send log. Log file contains error

RhodesAppBase.cpp: 245| send_log failed : network error - -1; Body -

Tried to add web logger to browser Config.xml file by adding second LogFile element using

<Logger>
    <LogProtocol   value="FILE"/>
    <LogPort       value="80"/>
    <LogURI        value="file://%INSTALLDIR%/Log.txt"/>
    <LogError      value="1"/>
    <LogWarning    value="1"/>
    <LogInfo       value="1"/>
    <LogTrace      value="0"/>
    <LogUser       value="0"/>
    <LogMemory     value="0"/>
    <LogMemPeriod  value="5000"/>
    <LogMaxSize    value="5000"/>
</Logger>

throws the same error. How to send log files to https from browser ?
Log server sample code in

https://github.com/rhomobile/rhologs

psots to http server. Is https supported? All other https urls work in Enterpise Browser


问:
JavaFx Resizing imageview to fit the container Pane and set it on the center
I'm trying to make an imageview fit the size of its container (in my case a Pane), and at the same time place it in the center of the Pane in JavaFx, in detail I can't do both at the same time i can get it to fit the container, but not put it in the center.

here is the code i use to make it fit in the container Pane

```<code>        //imgContainer is the pane that contains the image
        //photo is my imageview
        photo.fitWidthProperty().bind(imgContainer.widthProperty());
        photo.fitHeightProperty().bind(imgContainer.heightProperty());
        photo.setImage(new Image(post.getPhoto()));
</code>```

this is the output that is produced, the photo adapts to the Pane dimensions, but it is located to the left of the container(the dark background is the Pane container)  would to put it in the center of the pane and i couldn't find a method to do it keeping the dimensions of the Pane for the imageview, putting it on a hbox or stackPane allows to put it in the center but the image no longer keeps the container sizes well, so i don't know how to get it centered and fits the container at the same time

Body:
I'm trying to make an imageview fit the size of its container (in my case a Pane), and at the same time place it in the center of the Pane in JavaFx, in detail I can't do both at the same time i can get it to fit the container, but not put it in the center.

here is the code i use to make it fit in the container Pane

        //imgContainer is the pane that contains the image
        //photo is my imageview
        photo.fitWidthProperty().bind(imgContainer.widthProperty());
        photo.fitHeightProperty().bind(imgContainer.heightProperty());
        photo.setImage(new Image(post.getPhoto()));

this is the output that is produced, the photo adapts to the Pane dimensions, but it is located to the left of the container(the dark background is the Pane container)  would to put it in the center of the pane and i couldn't find a method to do it keeping the dimensions of the Pane for the imageview, putting it on a hbox or stackPane allows to put it in the center but the image no longer keeps the container sizes well, so i don't know how to get it centered and fits the container at the same time


问:
Inconsistent delay time for executing code
I'm trying to write some code to play animations with the help of the react package framer-motion:

```<code>import React from "react";
import './Line.css';
import { motion, useAnimation } from 'framer-motion';

export const Line = ({speed}) => {
    const [goingRight, setGoingRight] = React.useState(false);
    const [delay, setDelay] = React.useState(1);
    const [oldTime, setOldTime] = React.useState(new Date().getTime());
    const controls = useAnimation()

    React.useEffect(() => {
        controls.start({
            x: 280,
            transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
        })
    }, [])
    const start = async () => {
        setDelay((new Date().getTime()) - oldTime);
        setOldTime(new Date().getTime());
        await setGoingRight(!goingRight);
        if (goingRight) {
            await controls.start({
                x: 280,
                transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
            })
        } else {
            await controls.start({
                x: 0,
                transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
            })
        }
    }
    return (
        <>
            {delay}
            <div className='outer'>
                <motion.div className='ball'
                    animate={controls}
                    onAnimationComplete={() => start()}
                />
                <div className='line'/>
            </div>
        </>
    )
}
</code>```

This component renders a horizontal line and a circle that sits on that line, the circle starts at the left side of the line and is animated to the right. After that, another animation is made to move the circle back to the left and then the cycle continues.

Each animation takes as long as the speed property (in seconds).

I'm also displaying the delay state variable which does the appropriate math to so determine how many milliseconds the most recent animation took since the last animation.

Here's my problem, let's say I render this component with a speed property of 1. In a perfect world, delay would always = 1000, but of course, there's some time loss for executing the code in the start() function so delay usually = 1017 instead. That would be fine because I could account for the difference, but strangely, delay is sometimes exactly 1000 instead (around 1 in every 4 animations it seems, but it's not consistent).

I need these animation times to be precise and this is too much of a deviation for what I need and I can't seem to figure out how to fix it. I have a suspicion this might be just be the nature of doing all this in real time and that it may be an unsolvable problem, but I figured I'd ask in case anyone has found themselves in a scenario like this before.

Instead of using multiple animation that are run after another, I've tried just using one infinitely repeating animation like this:

```<code>controls.start({
            x: 280,
            transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' repeat: Infinity, repeatType: 'reverse', }
        })
</code>```

The problem with doing this is that I need code to run after the circle hits the end of the line every time, which before I was using onAnimationComplete to accomplish, but onAnimationComplete seems to only be triggered when the entire animation completes, not also when it repeats

Body:
I'm trying to write some code to play animations with the help of the react package framer-motion:

import React from "react";
import './Line.css';
import { motion, useAnimation } from 'framer-motion';

export const Line = ({speed}) => {
    const [goingRight, setGoingRight] = React.useState(false);
    const [delay, setDelay] = React.useState(1);
    const [oldTime, setOldTime] = React.useState(new Date().getTime());
    const controls = useAnimation()

    React.useEffect(() => {
        controls.start({
            x: 280,
            transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
        })
    }, [])
    const start = async () => {
        setDelay((new Date().getTime()) - oldTime);
        setOldTime(new Date().getTime());
        await setGoingRight(!goingRight);
        if (goingRight) {
            await controls.start({
                x: 280,
                transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
            })
        } else {
            await controls.start({
                x: 0,
                transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' }
            })
        }
    }
    return (
        <>
            {delay}

                <motion.div className='ball'
                    animate={controls}
                    onAnimationComplete={() => start()}
                />

        </>
    )
}

This component renders a horizontal line and a circle that sits on that line, the circle starts at the left side of the line and is animated to the right. After that, another animation is made to move the circle back to the left and then the cycle continues.

Each animation takes as long as the speed property (in seconds).

I'm also displaying the delay state variable which does the appropriate math to so determine how many milliseconds the most recent animation took since the last animation.

Here's my problem, let's say I render this component with a speed property of 1. In a perfect world, delay would always = 1000, but of course, there's some time loss for executing the code in the start() function so delay usually = 1017 instead. That would be fine because I could account for the difference, but strangely, delay is sometimes exactly 1000 instead (around 1 in every 4 animations it seems, but it's not consistent).

I need these animation times to be precise and this is too much of a deviation for what I need and I can't seem to figure out how to fix it. I have a suspicion this might be just be the nature of doing all this in real time and that it may be an unsolvable problem, but I figured I'd ask in case anyone has found themselves in a scenario like this before.

Instead of using multiple animation that are run after another, I've tried just using one infinitely repeating animation like this:

controls.start({
            x: 280,
            transition: { delay: 0, duration: speed, type: 'tween', ease: 'linear' repeat: Infinity, repeatType: 'reverse', }
        })

The problem with doing this is that I need code to run after the circle hits the end of the line every time, which before I was using onAnimationComplete to accomplish, but onAnimationComplete seems to only be triggered when the entire animation completes, not also when it repeats


问:
Bluetooth extender to control outdoor Bluetooth LED light Strips
I have outdoor LED strips that are bluetooth controlled, Govee ones. I presently have to go to different regions in the house to turn them on and off from my phone via bluetooth connecttion to the light strips, all 5 individually. Is there a bluetooth range extender I can get to have better coverage to the LED strips? I see range extenders, but they are all for audio, I am just looking to have better access to the strips. Any product if it exists to help for this would be much appreciated, thanks
Reno

Tried connecting locally, no problem but need to go somewhat close. Found some bluetooth extenders, but they are geared for audio


问:
Determine if two Trees are Identical
This is the question of Binary Tree. Level: Easy

In the second code, in while loop I just stored the value of popped integer value from stack in int variables and then wrote the condition of if loop. But in first I did not stored them in any variables I directly used them in if condition of while loop. Can anyone please explain why is it creating a difference?

This was my approach, in this if the input trees are 333 and 333 then it gives "no"(trees are not identical).
`
class Solution
{

```<code>    public void preOrder(Node root,Stack<Integer> stack){
        if(root==null){
            return ;
        }
        stack.push(root.data);
        preOrder(root.left,stack);
        preOrder(root.right,stack);

    }
    boolean isIdentical(Node root1, Node root2)
    {
        // Code Here
        if(root1==null||root2==null)
        return false;
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        preOrder(root1,stack1);
        preOrder(root2,stack2);

        if(stack1.size()!=stack2.size())
        return false;

        while(!stack1.isEmpty()&&!stack2.isEmpty()){
            if(stack1.pop()!=stack2.pop())
            return false;
        }

        return true;

    }
}`
</code>```

But, in this the same input trees(333 and 333) gave correct output i.e "yes".

` class Solution
{

```<code>    public void preOrder(Node root,Stack<Integer> stack){
        if(root==null){
            return ;
        }
        stack.push(root.data);
        preOrder(root.left,stack);
        preOrder(root.right,stack);

    }
    boolean isIdentical(Node root1, Node root2)
    {
        // Code Here
        if(root1==null||root2==null)
        return false;
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        preOrder(root1,stack1);
        preOrder(root2,stack2);

        if(stack1.size()!=stack2.size())
        return false;

        while(!stack1.isEmpty()&&!stack2.isEmpty()){
            int n1 = stack1.pop();
            int n2 = stack2.pop();
            if(n1!=n2)
            return false;
        }

        return true;

    }

}`
</code>```

Title: Determine if two Trees are Identical

Body:
This is the question of Binary Tree. Level: Easy

In the second code, in while loop I just stored the value of popped integer value from stack in int variables and then wrote the condition of if loop. But in first I did not stored them in any variables I directly used them in if condition of while loop. Can anyone please explain why is it creating a difference?

This was my approach, in this if the input trees are 333 and 333 then it gives "no"(trees are not identical).
`
class Solution
{

    public void preOrder(Node root,Stack<Integer> stack){
        if(root==null){
            return ;
        }
        stack.push(root.data);
        preOrder(root.left,stack);
        preOrder(root.right,stack);

    }
    boolean isIdentical(Node root1, Node root2)
    {
        // Code Here
        if(root1==null||root2==null)
        return false;
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        preOrder(root1,stack1);
        preOrder(root2,stack2);

        if(stack1.size()!=stack2.size())
        return false;

        while(!stack1.isEmpty()&&!stack2.isEmpty()){
            if(stack1.pop()!=stack2.pop())
            return false;
        }

        return true;

    }
}`

But, in this the same input trees(333 and 333) gave correct output i.e "yes".

` class Solution
{

    public void preOrder(Node root,Stack<Integer> stack){
        if(root==null){
            return ;
        }
        stack.push(root.data);
        preOrder(root.left,stack);
        preOrder(root.right,stack);

    }
    boolean isIdentical(Node root1, Node root2)
    {
        // Code Here
        if(root1==null||root2==null)
        return false;
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        preOrder(root1,stack1);
        preOrder(root2,stack2);

        if(stack1.size()!=stack2.size())
        return false;

        while(!stack1.isEmpty()&&!stack2.isEmpty()){
            int n1 = stack1.pop();
            int n2 = stack2.pop();
            if(n1!=n2)
            return false;
        }

        return true;

    }

}`


问:
Docker containers not accessible from internet (using jwilder's nginx+letsencrypt solution)
I have been using the jwilder's nginx + letsencrypt solution to access my containers online.

Last week my server crashed and after a restart, I couldn't access any of my containers from the internet. Accessing them from LAN works but I get "refused to connect" errors when I use the web address (I'm using DDNS with a domain I own).

Checking the logs, I immediately saw errors in letsencrypt logs like:
:Verify error:: Fetching http:///.well-known/acme-challenge/oSGmRMyB-df4XEN3ZW-8ksBvtxxO8m2Di50mhpWWuu8: Connection refused

I have already double checked port forwarding on my Router and things seem to be ok. I can even use port 22 to SSH into my machine, just to validate that the port forwarding is working.

I also checked UFW status, thinking of firewall issues on my server and UFW is inactive as well.

Any suggestions on how can I debug this further?


问:
Handle multiple non-renewable subscription for the same product in StoreKit 2
I want to offer non renewable subscriptions in my app. 1 month access and 3 months access. I am implementing in-app purchase functionality for non-renewable subscriptions in my app. I am able to handle new subscriptions, but I am having difficulty handling the scenario where a user has an active subscription but wants to extend it before it expires. Using Transaction.currentEntitlements only returns the latest transaction for a product, so I am unable to determine if a user has multiple transactions for the same subscription duration. I am considering using Transaction.all and filtering out invalid transactions by checking the revocationDate property, but I am unsure if this is the best approach or if there are any potential issues I should be aware of. Is it sufficient to just check transaction.revocationDate to filter out invalid transactions, or are there other considerations I should take into account? Is there anyone else with similar use cases who can provide input on this issue?

Here the filtering logic:

```<code>let transaction = try checkVerified(result)

guard transaction.revocationDate == nil else {
   continue
}
</code>```

here is the full function:

```<code>@MainActor
    private func updateCustomerProductStatus() async {
        var purchasedNonConsumables: [Purchase] = []
        var purchasedNonRenewableSubscriptions: [Purchase] = []

        //Iterate through all of the user's purchased products.
        for await result in Transaction.all {
            do {
                //Check whether the transaction is verified. If it isn’t, catch `failedVerification` error.
                let transaction = try checkVerified(result)

                guard transaction.revocationDate == nil else {
                    continue
                }

                //Check the `productType` of the transaction and get the corresponding product from the store.
                switch transaction.productType {
                case .nonConsumable:
                    if let nonConsumable = nonConsumables.first(where: { $0.id == transaction.productID }) {
                        let purchase = Purchase(product: nonConsumable, transaction: transaction)
                        purchasedNonConsumables.append(purchase)
                    }
                case .nonRenewable:
                    if let nonRenewable = nonRenewables.first(where: { $0.id == transaction.productID }) {
                        //Non-renewing subscriptions have no inherent expiration date, so they're always
                        //contained in `Transaction.currentEntitlements` after the user purchases them.
                        //This app defines this non-renewing subscription's expiration date to be one year after purchase.
                        //If the current date is within one year of the `purchaseDate`, the user is still entitled to this
                        //product.
                        let numberOfMonths = transaction.productID == StoreProduct.threeMonthsSubscription.identifier ? 3 : 1
                        let currentDate = Date()
                        let expirationDate = Calendar(identifier: .gregorian).date(byAdding: DateComponents(month: numberOfMonths),
                                                                   to: transaction.purchaseDate)!

                        let purchase = Purchase(product: nonRenewable, transaction: transaction)
                        purchasedNonRenewableSubscriptions.append(purchase)
                    }
                default:
                    break
                }
            } catch {
                print()
            }
        }

        //Update the store information with the purchased products.
        self.purchasedNonConsumables = purchasedNonConsumables
        self.purchasedNonRenewableSubscriptions = purchasedNonRenewableSubscriptions
    }
</code>```

Body:
I want to offer non renewable subscriptions in my app. 1 month access and 3 months access. I am implementing in-app purchase functionality for non-renewable subscriptions in my app. I am able to handle new subscriptions, but I am having difficulty handling the scenario where a user has an active subscription but wants to extend it before it expires. Using Transaction.currentEntitlements only returns the latest transaction for a product, so I am unable to determine if a user has multiple transactions for the same subscription duration. I am considering using Transaction.all and filtering out invalid transactions by checking the revocationDate property, but I am unsure if this is the best approach or if there are any potential issues I should be aware of. Is it sufficient to just check transaction.revocationDate to filter out invalid transactions, or are there other considerations I should take into account? Is there anyone else with similar use cases who can provide input on this issue?

Here the filtering logic:

let transaction = try checkVerified(result)

guard transaction.revocationDate == nil else {
   continue
}

here is the full function:

@MainActor
    private func updateCustomerProductStatus() async {
        var purchasedNonConsumables: [Purchase] = []
        var purchasedNonRenewableSubscriptions: [Purchase] = []

        //Iterate through all of the user's purchased products.
        for await result in Transaction.all {
            do {
                //Check whether the transaction is verified. If it isn’t, catch `failedVerification` error.
                let transaction = try checkVerified(result)

                guard transaction.revocationDate == nil else {
                    continue
                }

                //Check the `productType` of the transaction and get the corresponding product from the store.
                switch transaction.productType {
                case .nonConsumable:
                    if let nonConsumable = nonConsumables.first(where: { $0.id == transaction.productID }) {
                        let purchase = Purchase(product: nonConsumable, transaction: transaction)
                        purchasedNonConsumables.append(purchase)
                    }
                case .nonRenewable:
                    if let nonRenewable = nonRenewables.first(where: { $0.id == transaction.productID }) {
                        //Non-renewing subscriptions have no inherent expiration date, so they're always
                        //contained in `Transaction.currentEntitlements` after the user purchases them.
                        //This app defines this non-renewing subscription's expiration date to be one year after purchase.
                        //If the current date is within one year of the `purchaseDate`, the user is still entitled to this
                        //product.
                        let numberOfMonths = transaction.productID == StoreProduct.threeMonthsSubscription.identifier ? 3 : 1
                        let currentDate = Date()
                        let expirationDate = Calendar(identifier: .gregorian).date(byAdding: DateComponents(month: numberOfMonths),
                                                                   to: transaction.purchaseDate)!

                        let purchase = Purchase(product: nonRenewable, transaction: transaction)
                        purchasedNonRenewableSubscriptions.append(purchase)
                    }
                default:
                    break
                }
            } catch {
                print()
            }
        }

        //Update the store information with the purchased products.
        self.purchasedNonConsumables = purchasedNonConsumables
        self.purchasedNonRenewableSubscriptions = purchasedNonRenewableSubscriptions
    }


问:
FFT on an image, using butterfly notation with decimation in spatial domain
I'm trying to implement FFT, using butterfly notation with decimation in spatial domain. I have two separated functions, one to calculate the FFT on 1D array, and the other that applies the first function over columns of the image, puts these columns in a temporary array, and then computes the FFT of rows in the temporary array.
Here is the code

```<code>public static Complex[] FFT(Complex[] input)
    {
        // Get the length of the input array
        int n = input.Length;

        Complex I = new Complex(0, 1);
        // Check if the input has a length of 1
        if (n == 1)
        {
            return input;
        }

        // Split the input into even and odd elements
        Complex[] even = new Complex[n / 2];
        Complex[] odd = new Complex[n / 2];

        for (int i = 0; i < n; i++)
        {
            if (i % 2 == 0)
            {
                even[i / 2] = input[i];
            }
            else
            {
                odd[(i - 1) / 2] = input[i];
            }
        }

        // Compute the FFT of the even and odd elements
        Complex[] evenFFT = FFT(even);
        Complex[] oddFFT = FFT(odd);

        // Combine the FFT of the even and odd elements using the butterfly notation
        Complex[] output = new Complex[n];
        for (int i = 0; i < n / 2; i++)
        {
            Complex w = Complex.Exp(-2 * I * Math.PI * i / n);
            output[i] = evenFFT[i] + w * oddFFT[i];
            output[i + n / 2] = evenFFT[i] - w * oddFFT[i];
        }

        return output;
    }
    public static Complex[,] FFT2D(Complex[,] input)
    {
        int N = input.GetLength(0);
        int M = input.GetLength(1);

        Complex[,] output = new Complex[128, 128];
        Complex[,] columnsFFT = new Complex[128, 128];

        //Perform FFT over the columns of the input
        for(int i = 0; i < M; i++)
        {
            //Put all the values from i'th column in the tempColumn variable
            var tempColumn = new Complex[128];
            for(int j = 0; j < N; j++)
            {
                tempColumn[j] = input[j, i];
            }
            //Calculate the FFT of i'th column
            tempColumn = FFT(tempColumn);
            //Assign the column to columnsFFT, after calculating its FFT
            for(int z = 0; z < 128; z++)
            {
                columnsFFT[z, i] = tempColumn[z];
            }
        }

        //Perform FFT over the rows of the columnsFFT
        for(int i = 0; i < N; i++)
        {
            //Put the values from i'th row in tempRow, so we can perform the FFT on its entirety
            var tempRow = new Complex[128];
            for(int j = 0; j < M; j++)
            {
                tempRow[j] = columnsFFT[i, j];
            }
            //Calculate the FFT on tempRow
            tempRow = FFT(tempRow);
            //Assign the tempRow to the output
            for(int z = 0; z < M; z++)
            {
                if (i == 0)
                    Console.WriteLine(tempRow[z].Real);
                output[i, z] = tempRow[z];
            }
        }

        return output;
    }
</code>```

The problem that i have is that it simply doesn't work, or i think it doesn't, based on the image output i get.
Input image

Output

What is it that i'm doing wrong here?

Body:
I'm trying to implement FFT, using butterfly notation with decimation in spatial domain. I have two separated functions, one to calculate the FFT on 1D array, and the other that applies the first function over columns of the image, puts these columns in a temporary array, and then computes the FFT of rows in the temporary array.
Here is the code

public static Complex[] FFT(Complex[] input)
    {
        // Get the length of the input array
        int n = input.Length;

        Complex I = new Complex(0, 1);
        // Check if the input has a length of 1
        if (n == 1)
        {
            return input;
        }

        // Split the input into even and odd elements
        Complex[] even = new Complex[n / 2];
        Complex[] odd = new Complex[n / 2];

        for (int i = 0; i < n; i++)
        {
            if (i % 2 == 0)
            {
                even[i / 2] = input[i];
            }
            else
            {
                odd[(i - 1) / 2] = input[i];
            }
        }

        // Compute the FFT of the even and odd elements
        Complex[] evenFFT = FFT(even);
        Complex[] oddFFT = FFT(odd);

        // Combine the FFT of the even and odd elements using the butterfly notation
        Complex[] output = new Complex[n];
        for (int i = 0; i < n / 2; i++)
        {
            Complex w = Complex.Exp(-2 * I * Math.PI * i / n);
            output[i] = evenFFT[i] + w * oddFFT[i];
            output[i + n / 2] = evenFFT[i] - w * oddFFT[i];
        }

        return output;
    }
    public static Complex[,] FFT2D(Complex[,] input)
    {
        int N = input.GetLength(0);
        int M = input.GetLength(1);

        Complex[,] output = new Complex[128, 128];
        Complex[,] columnsFFT = new Complex[128, 128];

        //Perform FFT over the columns of the input
        for(int i = 0; i < M; i++)
        {
            //Put all the values from i'th column in the tempColumn variable
            var tempColumn = new Complex[128];
            for(int j = 0; j < N; j++)
            {
                tempColumn[j] = input[j, i];
            }
            //Calculate the FFT of i'th column
            tempColumn = FFT(tempColumn);
            //Assign the column to columnsFFT, after calculating its FFT
            for(int z = 0; z < 128; z++)
            {
                columnsFFT[z, i] = tempColumn[z];
            }
        }

        //Perform FFT over the rows of the columnsFFT
        for(int i = 0; i < N; i++)
        {
            //Put the values from i'th row in tempRow, so we can perform the FFT on its entirety
            var tempRow = new Complex[128];
            for(int j = 0; j < M; j++)
            {
                tempRow[j] = columnsFFT[i, j];
            }
            //Calculate the FFT on tempRow
            tempRow = FFT(tempRow);
            //Assign the tempRow to the output
            for(int z = 0; z < M; z++)
            {
                if (i == 0)
                    Console.WriteLine(tempRow[z].Real);
                output[i, z] = tempRow[z];
            }
        }

        return output;
    }

The problem that i have is that it simply doesn't work, or i think it doesn't, based on the image output i get.
Input image

Output

What is it that i'm doing wrong here?


问:
user.is_authenticated returns anonymoususer even user already authenticated
main.html

```<code>{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="{% static 'main/main.css' %}">
</head>
<body>
    Welcome to our online store
    <div class="account">
        <div class="img">
            <img src="" alt="">
        </div>
        <div class="clearfix"></div>
        {{ request.user }}
        {% if request.user.is_authenticated %}
            <p>{{ user.email }}</p>
            <a href="">Settings</a>
            <a href="{% url 'auth:logout' %}">Log out</a>
        {% else %}
            <a href="{% url 'auth:login' %}">Log in</a>
            <a href="{% url 'auth:signup' %}">Sign up</a>
        {% endif %}
    </div>
</body>
</html>
</code>```

output
AnonymousUser

authentication/views.py

```<code>from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.views.generic import CreateView, ListView, DetailView, DeleteView, UpdateView, RedirectView
from django.http import HttpResponse
from .forms import UserForm, passwordForm, loginForm
from django.contrib.auth import views, forms, logout, login, authenticate
from django.contrib.auth.hashers import make_password, check_password
from django.core.exceptions import ImproperlyConfigured
from django.utils.http import urlsafe_base64_encode
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_bytes
from .models import Users
from django.contrib import messages
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.forms import AuthenticationForm
from django.conf.global_settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from django.contrib.auth.views import LoginView, LogoutView

app_name = 'authentication'

class loginView(View):
    template_name = f'{app_name}/login/login.html'

    def get(self, *args, **kwargs):
        return render(self.request, self.template_name)

    def post(self, request, *args, **kwargs):
        email = request.POST.get('email')
        password = request.POST.get('password1')
        user = authenticate(request=request, username=email, password=password)
        if user is not None:
            login(request, user)
            print(user)
            print(user.is_authenticated)
            return redirect('main:main_page')
        else:
            return render(request, self.template_name, {
                'password_or_email_error': True
            })
</code>```

authentication/urls.py

```<code>
from django.urls import path
from . import views

app_name = 'auth'

urlpatterns = [
    path('login/', views.loginView.as_view(), name='login'),
    path('logout/', views.logoutView.as_view(), name='logout'),
    path('new/', views.signupView.as_view(), name='signup'),
    path('password_reset/', views.passwordResetView.as_view(), name='password_reset'),
    path('password_reset/done/', views.passwordResetDoneView.as_view(), name='password_reset_done'),
    path('password/reset/<uidb64>/<token>/', views.passwordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('password_reset/complete/', views.passwordResetCompleteView.as_view(), name='password_reset_complete')
]
</code>```

main/views.py

```<code>from django.shortcuts import render
from django.views import View

app_name = 'main'

class main_page(View):
    template_name = f'{app_name}/main/main.html'

    def get(self, request, *args, **kwargs):
        print(self.request.user, request.user)
        return render(self.request, self.template_name)
</code>```

main/urls.py

```<code>from django.urls import path
from . import views

app_name = 'main'

urlpatterns = [
    path('', views.main_page.as_view(), name='main_page'),
]
</code>```

authentication/models.py

```<code>import sys
sys.path.append('..')

from django.contrib.auth.models import UserManager, AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from config import *
from django.utils import timezone

class Users(AbstractUser):
    GENDERS = (
        ('male', 'Male'),
        ('female', 'Female'),
        ('rns', 'Rather not say')
    )
    first_name = models.CharField(max_length=50, validators=[validate_str, min_length_for_name])
    last_name = models.CharField(max_length=50, null=True, blank=True, validators=[validate_str, min_length_for_name])
    email = models.EmailField(max_length=100, unique=True, validators=[min_length_for_email])
    password1 = models.CharField(max_length=100, validators=[min_length_for_password])
    password2 = models.CharField(max_length=100, validators=[min_length_for_password])
    birth_date = models.DateField(validators=[min_year, max_year])
    gender = models.CharField(max_length=10, choices=GENDERS, validators=[validate_gender])

    password = models.CharField(_("password"), max_length=128, null=True, blank=True)
    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[AbstractUser.username_validator],
        error_messages={
            "unique": _("A user with that username already exists."),
        },
        null=True, blank=True
    )
    date_joined = models.DateTimeField(_("date joined"), default=timezone.now, null=True, blank=True)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'birth_date', 'gender']

    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'

        app_label = 'authentication'
        db_table = 'users'

    def __str__(self):
        return f'{self.first_name} {self.last_name}'
</code>```

I tried django's login and authenticate function then return redirect to main page but in the main page request.user is anonymous, in the login function user is not anonymous. If i try to check user in login function user.is_authenticated return True but in main page return False

Body:
main.html

{% load static %}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="{% static 'main/main.css' %}">

    Welcome to our online store

        {{ request.user }}
        {% if request.user.is_authenticated %}

{{ user.email }}

            Settings
            Log out
        {% else %}
            Log in
            Sign up
        {% endif %}

output
AnonymousUser

authentication/views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.views.generic import CreateView, ListView, DetailView, DeleteView, UpdateView, RedirectView
from django.http import HttpResponse
from .forms import UserForm, passwordForm, loginForm
from django.contrib.auth import views, forms, logout, login, authenticate
from django.contrib.auth.hashers import make_password, check_password
from django.core.exceptions import ImproperlyConfigured
from django.utils.http import urlsafe_base64_encode
from django.contrib.auth.tokens import default_token_generator
from django.utils.encoding import force_bytes
from .models import Users
from django.contrib import messages
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.forms import AuthenticationForm
from django.conf.global_settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from django.contrib.auth.views import LoginView, LogoutView

app_name = 'authentication'

class loginView(View):
    template_name = f'{app_name}/login/login.html'

    def get(self, *args, **kwargs):
        return render(self.request, self.template_name)

    def post(self, request, *args, **kwargs):
        email = request.POST.get('email')
        password = request.POST.get('password1')
        user = authenticate(request=request, username=email, password=password)
        if user is not None:
            login(request, user)
            print(user)
            print(user.is_authenticated)
            return redirect('main:main_page')
        else:
            return render(request, self.template_name, {
                'password_or_email_error': True
            })

authentication/urls.py

from django.urls import path
from . import views

app_name = 'auth'

urlpatterns = [
    path('login/', views.loginView.as_view(), name='login'),
    path('logout/', views.logoutView.as_view(), name='logout'),
    path('new/', views.signupView.as_view(), name='signup'),
    path('password_reset/', views.passwordResetView.as_view(), name='password_reset'),
    path('password_reset/done/', views.passwordResetDoneView.as_view(), name='password_reset_done'),
    path('password/reset/<uidb64>/<token>/', views.passwordResetConfirmView.as_view(), name='password_reset_confirm'),
    path('password_reset/complete/', views.passwordResetCompleteView.as_view(), name='password_reset_complete')
]

main/views.py

from django.shortcuts import render
from django.views import View

app_name = 'main'

class main_page(View):
    template_name = f'{app_name}/main/main.html'

    def get(self, request, *args, **kwargs):
        print(self.request.user, request.user)
        return render(self.request, self.template_name)

main/urls.py

from django.urls import path
from . import views

app_name = 'main'

urlpatterns = [
    path('', views.main_page.as_view(), name='main_page'),
]

authentication/models.py

import sys
sys.path.append('..')

from django.contrib.auth.models import UserManager, AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from config import *
from django.utils import timezone

class Users(AbstractUser):
    GENDERS = (
        ('male', 'Male'),
        ('female', 'Female'),
        ('rns', 'Rather not say')
    )
    first_name = models.CharField(max_length=50, validators=[validate_str, min_length_for_name])
    last_name = models.CharField(max_length=50, null=True, blank=True, validators=[validate_str, min_length_for_name])
    email = models.EmailField(max_length=100, unique=True, validators=[min_length_for_email])
    password1 = models.CharField(max_length=100, validators=[min_length_for_password])
    password2 = models.CharField(max_length=100, validators=[min_length_for_password])
    birth_date = models.DateField(validators=[min_year, max_year])
    gender = models.CharField(max_length=10, choices=GENDERS, validators=[validate_gender])

    password = models.CharField(_("password"), max_length=128, null=True, blank=True)
    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[AbstractUser.username_validator],
        error_messages={
            "unique": _("A user with that username already exists."),
        },
        null=True, blank=True
    )
    date_joined = models.DateTimeField(_("date joined"), default=timezone.now, null=True, blank=True)

    objects = UserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'birth_date', 'gender']

    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'

        app_label = 'authentication'
        db_table = 'users'

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

I tried django's login and authenticate function then return redirect to main page but in the main page request.user is anonymous, in the login function user is not anonymous. If i try to check user in login function user.is_authenticated return True but in main page return False


问:
Mongoose - How to enable strictQuery for a schema?
I want the query to follow strict mode because if I search for a user and pass in accidentally something not defined in schema i do not want the query to return all documents.

I tried:

```<code>const userSchema = new mongoose.Schema({
    email: {
        type: String
    },
    password: {
        type: String
    },
}, {strict: true, strictQuery: true});
</code>```

it doesnt work. I also tried:

```<code>mongoose.set('strictQuery',true);
</code>```

also doesnt work. WHat am I doing wrong?

Body:
I want the query to follow strict mode because if I search for a user and pass in accidentally something not defined in schema i do not want the query to return all documents.

I tried:

const userSchema = new mongoose.Schema({
    email: {
        type: String
    },
    password: {
        type: String
    },
}, {strict: true, strictQuery: true});

it doesnt work. I also tried:

mongoose.set('strictQuery',true);

also doesnt work. WHat am I doing wrong?


问:
Building Splittable DoFn (SDF) to list objects in GCS
I am trying to develop custom source for parallel GCS content scanning. The naive approach would be to loop through listObjects function calls:

```<code>while (...) {
    Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken);
    pageToken = objects.getNextPageToken();
    ...
}
</code>```

The problem is performance for the tens of millions objects.
Instead of the single thread code we can add delimiter / and submit parallel processed for each prefix found:

```<code>...
Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken, "/");
for (String subPrefix : object.getPrefixes()) {
    scanAsync(bucket, subPrefix);
}
...
</code>```

Next idea was to try to wrap this logic in Splittable DoFn.

Choice of RestrictionTracker: I don't see how can be used any of exiting RestrictionTracker. So decided to write own. Restriction itself is basically list of prefixes to scan. tryClaim checks if there is more prefixes left and receive newly scanned to append them to current restriction. trySplit splits list of prefixes.

The problem that I faced that trySplit can be called before all subPrefixes are found. In this case current restriction may receive more work to do after it was splitted. And it seems that trySplit is being called until it returns a not null value for a given RestrictionTracker: after certain number of elements goes to the output or after 1 second via scheduler or when ProcessContext.resume() returned. This doesn't work in my case as new prefixes can be found at any time. And I can't checkpoint via return ProcessContext.resume() because if split was already done, possible work that left in current restriction will cause checkDone() function to fail.

Another problem that I suspect that I couldn't achieve parallel execution in DirectRunner. As trySplit was always called with fractionOfRemainder=0 and new RestrictionTracker was started only after current one completed its piece of work.

It would be also great to read more detailed explanation about Splittable DoFn components lifecycle. How parallel execution per element is achieved. And how and when state of RestrictionTracker can be modified.

UPD: Adding simplified code that should show intended implementation

```<code>@DoFn.BoundedPerElement
private static class ScannerDoFn extends DoFn<String, String> {
    private transient GcsUtil gcsUtil;

    @GetInitialRestriction
    public ScannerRestriction getInitialRestriction(@Element String bucket) {
        return ScannerRestriction.init(bucket);
    }

    @ProcessElement
    public ProcessContinuation processElement(
            ProcessContext c,
            @Element String bucket,
            RestrictionTracker<ScannerRestriction, ScannerPosition> tracker,
            OutputReceiver<String> outputReceiver) {
        if (gcsUtil == null) {
            gcsUtil = c.getPipelineOptions().as(GcsOptions.class).getGcsUtil();
        }
        ScannerRestriction currentRestriction = tracker.currentRestriction();
        ScannerPosition position = new ScannerPosition();
        while (true) {
            if (tracker.tryClaim(position)) {
                if (position.completedCurrent) {
                    // position.clear();
                    // ideally I would to get checkpoint here before starting new work
                    return ProcessContinuation.resume();
                }
                try {
                    Objects objects = gcsUtil.listObjects(
                            currentRestriction.bucket,
                            position.currentPrefix,
                            position.currentPageToken,
                            "/");
                    if (objects.getItems() != null) {
                        for (StorageObject o : objects.getItems()) {
                            outputReceiver.output(o.getName());
                        }
                    }
                    if (objects.getPrefixes() != null) {
                        position.newPrefixes.addAll(objects.getPrefixes());
                    }
                    position.currentPageToken = objects.getNextPageToken();
                    if (position.currentPageToken == null) {
                        position.completedCurrent = true;
                    }
                } catch (Throwable throwable) {
                    logger.error("Error during scan", throwable);
                }
            } else {
                return ProcessContinuation.stop();
            }
        }
    }

    @NewTracker
    public RestrictionTracker<ScannerRestriction, ScannerPosition> restrictionTracker(@Restriction ScannerRestriction restriction) {
        return new ScannerRestrictionTracker(restriction);
    }

    @GetRestrictionCoder
    public Coder<ScannerRestriction> getRestrictionCoder() {
        return ScannerRestriction.getCoder();
    }
}

public static class ScannerPosition {
    private String currentPrefix;
    private String currentPageToken;
    private final List<String> newPrefixes;
    private boolean completedCurrent;
    public ScannerPosition() {
        this.currentPrefix = null;
        this.currentPageToken = null;
        this.newPrefixes = Lists.newArrayList();
        this.completedCurrent = false;
    }
    public void clear() {
        this.currentPageToken = null;
        this.currentPrefix = null;
        this.completedCurrent = false;
    }
}

private static class ScannerRestriction {
    private final String bucket;
    private final LinkedList<String> prefixes;
    private ScannerRestriction(String bucket) {
        this.bucket = bucket;
        this.prefixes = Lists.newLinkedList();
    }

    public static ScannerRestriction init(String bucket) {
        ScannerRestriction res = new ScannerRestriction(bucket);
        res.prefixes.add("");
        return res;
    }

    public ScannerRestriction empty() {
        return new ScannerRestriction(bucket);
    }

    public boolean isEmpty() {
        return prefixes.isEmpty();
    }

    public static Coder<ScannerRestriction> getCoder() {
        return ScannerRestrictionCoder.INSTANCE;
    }

    private static class ScannerRestrictionCoder extends AtomicCoder<ScannerRestriction> {
        private static final ScannerRestrictionCoder INSTANCE = new ScannerRestrictionCoder();
        private final static Coder<List<String>> listCoder = ListCoder.of(StringUtf8Coder.of());

        @Override
        public void encode(ScannerRestriction value, OutputStream outStream) throws IOException {
            NullableCoder.of(StringUtf8Coder.of()).encode(value.bucket, outStream);
            listCoder.encode(value.prefixes, outStream);
        }

        @Override
        public ScannerRestriction decode(InputStream inStream) throws IOException {
            String bucket = NullableCoder.of(StringUtf8Coder.of()).decode(inStream);
            List<String> prefixes = listCoder.decode(inStream);
            ScannerRestriction res = new ScannerRestriction(bucket);
            res.prefixes.addAll(prefixes);
            return res;
        }
    }
}

private static class ScannerRestrictionTracker extends RestrictionTracker<ScannerRestriction, ScannerPosition> {
    private ScannerRestriction restriction;
    private ScannerPosition lastPosition = null;
    ScannerRestrictionTracker(ScannerRestriction restriction) {
        this.restriction = restriction;
    }

    @Override
    public boolean tryClaim(ScannerPosition position) {
        restriction.prefixes.addAll(position.newPrefixes);
        position.newPrefixes.clear();

        if (position.completedCurrent) {
            // completed work for current prefix
            assert lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix);
            lastPosition = null;
            return true; // return true but we would need to claim again if we need to get next prefix
        } else if (lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix)) {
            // proceed work for current prefix
            lastPosition = position;
            return true;
        }
        // looking for next prefix
        assert position.currentPrefix == null;
        assert lastPosition == null;
        if (restriction.isEmpty()) {
            // no work to do
            return false;
        }
        position.currentPrefix = restriction.prefixes.poll();
        lastPosition = position;
        return true;
    }

    @Override
    public ScannerRestriction currentRestriction() {
        return restriction;
    }

    @Override
    public SplitResult<ScannerRestriction> trySplit(double fractionOfRemainder) {
        if (lastPosition == null && restriction.isEmpty()) {
            // no work at all
            return null;
        }

        if (lastPosition != null && restriction.isEmpty()) {
            // work at the moment only at currently scanned prefix
            return SplitResult.of(restriction, restriction.empty());
        }

        int size = restriction.prefixes.size();
        int newSize = new Double(Math.round(fractionOfRemainder * size)).intValue();

        if (newSize == 0) {
            ScannerRestriction residual = restriction;
            restriction = restriction.empty();
            return SplitResult.of(restriction, residual);
        }

        ScannerRestriction residual = restriction.empty();
        for (int i=newSize; i<=size; i++) {
            residual.prefixes.add(restriction.prefixes.removeLast());
        }
        return SplitResult.of(restriction, residual);
    }

    @Override
    public void checkDone() throws IllegalStateException {
        if (lastPosition  != null) {
            throw new IllegalStateException("Called checkDone on not completed job");
        }
    }

    @Override
    public IsBounded isBounded() {
        return IsBounded.UNBOUNDED;
    }

}
</code>```

Body:
I am trying to develop custom source for parallel GCS content scanning. The naive approach would be to loop through listObjects function calls:

while (...) {
    Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken);
    pageToken = objects.getNextPageToken();
    ...
}

The problem is performance for the tens of millions objects.
Instead of the single thread code we can add delimiter / and submit parallel processed for each prefix found:

...
Objects objects = gcsUtil.listObjects(bucket, prefix, pageToken, "/");
for (String subPrefix : object.getPrefixes()) {
    scanAsync(bucket, subPrefix);
}
...

Next idea was to try to wrap this logic in Splittable DoFn.

Choice of RestrictionTracker: I don't see how can be used any of exiting RestrictionTracker. So decided to write own. Restriction itself is basically list of prefixes to scan. tryClaim checks if there is more prefixes left and receive newly scanned to append them to current restriction. trySplit splits list of prefixes.

The problem that I faced that trySplit can be called before all subPrefixes are found. In this case current restriction may receive more work to do after it was splitted. And it seems that trySplit is being called until it returns a not null value for a given RestrictionTracker: after certain number of elements goes to the output or after 1 second via scheduler or when ProcessContext.resume() returned. This doesn't work in my case as new prefixes can be found at any time. And I can't checkpoint via return ProcessContext.resume() because if split was already done, possible work that left in current restriction will cause checkDone() function to fail.

Another problem that I suspect that I couldn't achieve parallel execution in DirectRunner. As trySplit was always called with fractionOfRemainder=0 and new RestrictionTracker was started only after current one completed its piece of work.

It would be also great to read more detailed explanation about Splittable DoFn components lifecycle. How parallel execution per element is achieved. And how and when state of RestrictionTracker can be modified.

UPD: Adding simplified code that should show intended implementation

@DoFn.BoundedPerElement
private static class ScannerDoFn extends DoFn<String, String> {
    private transient GcsUtil gcsUtil;

    @GetInitialRestriction
    public ScannerRestriction getInitialRestriction(@Element String bucket) {
        return ScannerRestriction.init(bucket);
    }

    @ProcessElement
    public ProcessContinuation processElement(
            ProcessContext c,
            @Element String bucket,
            RestrictionTracker<ScannerRestriction, ScannerPosition> tracker,
            OutputReceiver<String> outputReceiver) {
        if (gcsUtil == null) {
            gcsUtil = c.getPipelineOptions().as(GcsOptions.class).getGcsUtil();
        }
        ScannerRestriction currentRestriction = tracker.currentRestriction();
        ScannerPosition position = new ScannerPosition();
        while (true) {
            if (tracker.tryClaim(position)) {
                if (position.completedCurrent) {
                    // position.clear();
                    // ideally I would to get checkpoint here before starting new work
                    return ProcessContinuation.resume();
                }
                try {
                    Objects objects = gcsUtil.listObjects(
                            currentRestriction.bucket,
                            position.currentPrefix,
                            position.currentPageToken,
                            "/");
                    if (objects.getItems() != null) {
                        for (StorageObject o : objects.getItems()) {
                            outputReceiver.output(o.getName());
                        }
                    }
                    if (objects.getPrefixes() != null) {
                        position.newPrefixes.addAll(objects.getPrefixes());
                    }
                    position.currentPageToken = objects.getNextPageToken();
                    if (position.currentPageToken == null) {
                        position.completedCurrent = true;
                    }
                } catch (Throwable throwable) {
                    logger.error("Error during scan", throwable);
                }
            } else {
                return ProcessContinuation.stop();
            }
        }
    }

    @NewTracker
    public RestrictionTracker<ScannerRestriction, ScannerPosition> restrictionTracker(@Restriction ScannerRestriction restriction) {
        return new ScannerRestrictionTracker(restriction);
    }

    @GetRestrictionCoder
    public Coder<ScannerRestriction> getRestrictionCoder() {
        return ScannerRestriction.getCoder();
    }
}

public static class ScannerPosition {
    private String currentPrefix;
    private String currentPageToken;
    private final List<String> newPrefixes;
    private boolean completedCurrent;
    public ScannerPosition() {
        this.currentPrefix = null;
        this.currentPageToken = null;
        this.newPrefixes = Lists.newArrayList();
        this.completedCurrent = false;
    }
    public void clear() {
        this.currentPageToken = null;
        this.currentPrefix = null;
        this.completedCurrent = false;
    }
}

private static class ScannerRestriction {
    private final String bucket;
    private final LinkedList<String> prefixes;
    private ScannerRestriction(String bucket) {
        this.bucket = bucket;
        this.prefixes = Lists.newLinkedList();
    }

    public static ScannerRestriction init(String bucket) {
        ScannerRestriction res = new ScannerRestriction(bucket);
        res.prefixes.add("");
        return res;
    }

    public ScannerRestriction empty() {
        return new ScannerRestriction(bucket);
    }

    public boolean isEmpty() {
        return prefixes.isEmpty();
    }

    public static Coder<ScannerRestriction> getCoder() {
        return ScannerRestrictionCoder.INSTANCE;
    }

    private static class ScannerRestrictionCoder extends AtomicCoder<ScannerRestriction> {
        private static final ScannerRestrictionCoder INSTANCE = new ScannerRestrictionCoder();
        private final static Coder<List<String>> listCoder = ListCoder.of(StringUtf8Coder.of());

        @Override
        public void encode(ScannerRestriction value, OutputStream outStream) throws IOException {
            NullableCoder.of(StringUtf8Coder.of()).encode(value.bucket, outStream);
            listCoder.encode(value.prefixes, outStream);
        }

        @Override
        public ScannerRestriction decode(InputStream inStream) throws IOException {
            String bucket = NullableCoder.of(StringUtf8Coder.of()).decode(inStream);
            List<String> prefixes = listCoder.decode(inStream);
            ScannerRestriction res = new ScannerRestriction(bucket);
            res.prefixes.addAll(prefixes);
            return res;
        }
    }
}

private static class ScannerRestrictionTracker extends RestrictionTracker<ScannerRestriction, ScannerPosition> {
    private ScannerRestriction restriction;
    private ScannerPosition lastPosition = null;
    ScannerRestrictionTracker(ScannerRestriction restriction) {
        this.restriction = restriction;
    }

    @Override
    public boolean tryClaim(ScannerPosition position) {
        restriction.prefixes.addAll(position.newPrefixes);
        position.newPrefixes.clear();

        if (position.completedCurrent) {
            // completed work for current prefix
            assert lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix);
            lastPosition = null;
            return true; // return true but we would need to claim again if we need to get next prefix
        } else if (lastPosition != null && lastPosition.currentPrefix.equals(position.currentPrefix)) {
            // proceed work for current prefix
            lastPosition = position;
            return true;
        }
        // looking for next prefix
        assert position.currentPrefix == null;
        assert lastPosition == null;
        if (restriction.isEmpty()) {
            // no work to do
            return false;
        }
        position.currentPrefix = restriction.prefixes.poll();
        lastPosition = position;
        return true;
    }

    @Override
    public ScannerRestriction currentRestriction() {
        return restriction;
    }

    @Override
    public SplitResult<ScannerRestriction> trySplit(double fractionOfRemainder) {
        if (lastPosition == null && restriction.isEmpty()) {
            // no work at all
            return null;
        }

        if (lastPosition != null && restriction.isEmpty()) {
            // work at the moment only at currently scanned prefix
            return SplitResult.of(restriction, restriction.empty());
        }

        int size = restriction.prefixes.size();
        int newSize = new Double(Math.round(fractionOfRemainder * size)).intValue();

        if (newSize == 0) {
            ScannerRestriction residual = restriction;
            restriction = restriction.empty();
            return SplitResult.of(restriction, residual);
        }

        ScannerRestriction residual = restriction.empty();
        for (int i=newSize; i<=size; i++) {
            residual.prefixes.add(restriction.prefixes.removeLast());
        }
        return SplitResult.of(restriction, residual);
    }

    @Override
    public void checkDone() throws IllegalStateException {
        if (lastPosition  != null) {
            throw new IllegalStateException("Called checkDone on not completed job");
        }
    }

    @Override
    public IsBounded isBounded() {
        return IsBounded.UNBOUNDED;
    }

}


问:
VScode Intellisense when using data property in the route Angular
I have a small question, when I use the data property in the route (to pass isEditMode):

```<code>const adminChildrenRoute: Routes = [
  { path: 'donuts', component: DonutListComponent },
  {
    path: 'donuts/new',
    component: DonutSingleComponent,
    data: { isEditMode: false },
  },
  {
    path: 'donuts/:id',
    component: DonutSingleComponent,
    data: { isEditMode: true },
  },
];
</code>```

In the component to get the , I use this:

```<code>ngOnInit(): void {
 this.isEditMode =       this.activatedRout.snapshot.data.isEditMode;

  }
</code>```

But VScode doesn't give me intellisence to choose the isEditMode, ma question there is any way to have this intellisence? thank you

Body:
I have a small question, when I use the data property in the route (to pass isEditMode):

const adminChildrenRoute: Routes = [
  { path: 'donuts', component: DonutListComponent },
  {
    path: 'donuts/new',
    component: DonutSingleComponent,
    data: { isEditMode: false },
  },
  {
    path: 'donuts/:id',
    component: DonutSingleComponent,
    data: { isEditMode: true },
  },
];

In the component to get the , I use this:

ngOnInit(): void {
 this.isEditMode =       this.activatedRout.snapshot.data.isEditMode;

  }

But VScode doesn't give me intellisence to choose the isEditMode, ma question there is any way to have this intellisence? thank you


问:
Adding text to x and y axsis to javaScript using Plotly.newPlot("plotArea", trace);
I am using the following code when trying to add titles to the x and y axsis in JavaScript. When I  run this I get an error message in the html console that reads calling Plotly.plot as if redrawing with this container doesn't yet have a
,,,

.
,,,
I tried adding the missing htlm code, but I may not have entered it correctly. Can someone help a newbie out, please?
```<code>var trace = {
    x: ["cat", "dog", "bird"],
    y: [21, 15, 6],
    type: "bar"
};

var layout = {
    title: "Pet Survey",
    xaxis: {title: "Pet Preference"},
    yaxis: {title: "Number of Respondents"}

};

Plotly.newPlot("plotArea", trace, layout);

</code>```

I took out the new js code out and it worked as expected. Then added the new code again and got the same error. Tried adding what the console said was the error and still not getting the expected result. Looked up the error message and I did not find what I was looking for. So I came here.

Body:
I am using the following code when trying to add titles to the x and y axsis in JavaScript. When I  run this I get an error message in the html console that reads calling Plotly.plot as if redrawing with this container doesn't yet have a
,,,

.
,,,
I tried adding the missing htlm code, but I may not have entered it correctly. Can someone help a newbie out, please?

var trace = {
    x: ["cat", "dog", "bird"],
    y: [21, 15, 6],
    type: "bar"
};

var layout = {
    title: "Pet Survey",
    xaxis: {title: "Pet Preference"},
    yaxis: {title: "Number of Respondents"}

};

Plotly.newPlot("plotArea", trace, layout);

I took out the new js code out and it worked as expected. Then added the new code again and got the same error. Tried adding what the console said was the error and still not getting the expected result. Looked up the error message and I did not find what I was looking for. So I came here.