问:
render fails after pushing image
so, i've been trying all day to deploy my project (SpringBoot) in render with docker. All day it has been giving me errors of all kind, after a lot of time and configurations, now happens this, i click manual deploy in render, wait, and then:

```<code>Jan 7 11:49:44 AM  ==> Cloning from https://github.com/KateClysm/BackEnd-Portfolio-PPA...
Jan 7 11:49:48 AM  ==> Checking out commit d2982e0e149b6e90b51265bcb926c1c602f4bc66 in branch main
Jan 7 11:49:53 AM  #1 [internal] load .dockerignore
Jan 7 11:49:53 AM  #1 transferring context: 2B done
Jan 7 11:49:53 AM  #1 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #2 [internal] load build definition from Dockerfile
Jan 7 11:49:53 AM  #2 transferring dockerfile: 205B done
Jan 7 11:49:53 AM  #2 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #3 [internal] load metadata for docker.io/library/amazoncorretto:19-alpine-jdk
Jan 7 11:49:53 AM  #3 ...
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #4 [auth] library/amazoncorretto:pull token for registry-1.docker.io
Jan 7 11:49:53 AM  #4 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #3 [internal] load metadata for docker.io/library/amazoncorretto:19-alpine-jdk
Jan 7 11:49:54 AM  #3 DONE 1.0s
Jan 7 11:49:54 AM
Jan 7 11:49:54 AM  #5 [1/2] FROM docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387
Jan 7 11:49:54 AM  #5 resolve docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387 0.1s done
Jan 7 11:49:54 AM  #5 DONE 0.1s
Jan 7 11:49:54 AM
Jan 7 11:49:54 AM  #6 [internal] load build context
Jan 7 11:49:55 AM  #6 transferring context: 43.14MB 1.9s done
Jan 7 11:49:55 AM  #6 DONE 1.9s
Jan 7 11:49:55 AM
Jan 7 11:49:55 AM  #5 [1/2] FROM docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387
Jan 7 11:49:55 AM  #5 extracting sha256:ca7dd9ec2225f2385955c43b2379305acd51543c28cf1d4e94522b3d94cce3ce 0.6s done
Jan 7 11:49:57 AM  #5 extracting sha256:b953496144a820faf3b5884ddfc542a98cc07f6a24635f26015e7c8d0ef19efe
Jan 7 11:50:00 AM  #5 extracting sha256:b953496144a820faf3b5884ddfc542a98cc07f6a24635f26015e7c8d0ef19efe 3.4s done
Jan 7 11:50:00 AM  #5 DONE 6.4s
Jan 7 11:50:00 AM
Jan 7 11:50:00 AM  #7 [2/2] COPY target/mm-0.0.1-SNAPSHOT.jar mm-0.0.1-SNAPSHOT.jar
Jan 7 11:50:00 AM  #7 DONE 0.1s
Jan 7 11:50:00 AM
Jan 7 11:50:00 AM  #8 exporting to oci image format
Jan 7 11:50:00 AM  #8 exporting layers
Jan 7 11:50:02 AM  #8 exporting layers 2.0s done
Jan 7 11:50:02 AM  #8 exporting manifest sha256:64870a046ea759b329252fecb6255049c33b7b4372b0d30cb785c7fed8d1fb60 done
Jan 7 11:50:02 AM  #8 exporting config sha256:36ccfedfb44c6ca4b7ef9bd3b86498a12a33d4daa9eb7b353c2c540d0cf726b4 done
Jan 7 11:50:10 AM  #8 DONE 10.2s
Jan 7 11:50:10 AM
Jan 7 11:50:10 AM  #9 exporting cache
Jan 7 11:50:18 AM  #9 DONE 7.3s
Jan 7 11:50:19 AM  Pushing image to registry...
Jan 7 11:50:24 AM  Upload succeeded
Jan 7 11:50:24 AM  DONE
</code>```

No more lines, no explanation, and the deploy fails.

my Dockerfile:

```<code>FROM amazoncorretto:19-alpine-jdk
MAINTAINER emaaristimuno
COPY target/mm-0.0.1-SNAPSHOT.jar mm-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","/mm-0.0.1-SNAPSHOT.jar"]
</code>```

ps: I'm using NetBeans.

The docs about Docker and MySQL in Render are this:
https://render.com/docs/deploy-mysql
But they don't really help me much.

My POM:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.portfolio</groupId>
    <artifactId>mm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mm</name>
    <description>Portfolio Maria Monchot</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

my application.properties:

```<code>#Ambientes de prueba
#spring.datasource.url=jdbc:mysql://localhost:3306/backendmm?useSSL=false&serverTimezone=UTC
#spring.datasource.username=root
#spring.datasorce.password=

#Ambientes de producción
spring.datasource.url=jdbc:mysql:urlfrommydatabase
spring.datasource.username=userfrommydatabase
spring.datasorce.password=passwordfrommydatabase

#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.ddl-auto=none
spring.datasource.hikari.maximum-pool-size=2

#JWT
jwt.secret = secret
jwt.expiration = 3600
</code>```

The path of my JAR:
C:\Users\Katerina\Desktop\Proyecto Portfolio PPA\BackEnd-Portfolio-PPA\target\mm-0.0.1-SNAPSHOT.jar

Title: render fails after pushing image

Body:
so, i've been trying all day to deploy my project (SpringBoot) in render with docker. All day it has been giving me errors of all kind, after a lot of time and configurations, now happens this, i click manual deploy in render, wait, and then:

Jan 7 11:49:44 AM  ==> Cloning from https://github.com/KateClysm/BackEnd-Portfolio-PPA...
Jan 7 11:49:48 AM  ==> Checking out commit d2982e0e149b6e90b51265bcb926c1c602f4bc66 in branch main
Jan 7 11:49:53 AM  #1 [internal] load .dockerignore
Jan 7 11:49:53 AM  #1 transferring context: 2B done
Jan 7 11:49:53 AM  #1 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #2 [internal] load build definition from Dockerfile
Jan 7 11:49:53 AM  #2 transferring dockerfile: 205B done
Jan 7 11:49:53 AM  #2 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #3 [internal] load metadata for docker.io/library/amazoncorretto:19-alpine-jdk
Jan 7 11:49:53 AM  #3 ...
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #4 [auth] library/amazoncorretto:pull token for registry-1.docker.io
Jan 7 11:49:53 AM  #4 DONE 0.0s
Jan 7 11:49:53 AM
Jan 7 11:49:53 AM  #3 [internal] load metadata for docker.io/library/amazoncorretto:19-alpine-jdk
Jan 7 11:49:54 AM  #3 DONE 1.0s
Jan 7 11:49:54 AM
Jan 7 11:49:54 AM  #5 [1/2] FROM docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387
Jan 7 11:49:54 AM  #5 resolve docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387 0.1s done
Jan 7 11:49:54 AM  #5 DONE 0.1s
Jan 7 11:49:54 AM
Jan 7 11:49:54 AM  #6 [internal] load build context
Jan 7 11:49:55 AM  #6 transferring context: 43.14MB 1.9s done
Jan 7 11:49:55 AM  #6 DONE 1.9s
Jan 7 11:49:55 AM
Jan 7 11:49:55 AM  #5 [1/2] FROM docker.io/library/amazoncorretto:19-alpine-jdk@sha256:46be4d85ae0f45ee7144fcb0d785907b960ee273f6e3d759b6e0c39bf03e5387
Jan 7 11:49:55 AM  #5 extracting sha256:ca7dd9ec2225f2385955c43b2379305acd51543c28cf1d4e94522b3d94cce3ce 0.6s done
Jan 7 11:49:57 AM  #5 extracting sha256:b953496144a820faf3b5884ddfc542a98cc07f6a24635f26015e7c8d0ef19efe
Jan 7 11:50:00 AM  #5 extracting sha256:b953496144a820faf3b5884ddfc542a98cc07f6a24635f26015e7c8d0ef19efe 3.4s done
Jan 7 11:50:00 AM  #5 DONE 6.4s
Jan 7 11:50:00 AM
Jan 7 11:50:00 AM  #7 [2/2] COPY target/mm-0.0.1-SNAPSHOT.jar mm-0.0.1-SNAPSHOT.jar
Jan 7 11:50:00 AM  #7 DONE 0.1s
Jan 7 11:50:00 AM
Jan 7 11:50:00 AM  #8 exporting to oci image format
Jan 7 11:50:00 AM  #8 exporting layers
Jan 7 11:50:02 AM  #8 exporting layers 2.0s done
Jan 7 11:50:02 AM  #8 exporting manifest sha256:64870a046ea759b329252fecb6255049c33b7b4372b0d30cb785c7fed8d1fb60 done
Jan 7 11:50:02 AM  #8 exporting config sha256:36ccfedfb44c6ca4b7ef9bd3b86498a12a33d4daa9eb7b353c2c540d0cf726b4 done
Jan 7 11:50:10 AM  #8 DONE 10.2s
Jan 7 11:50:10 AM
Jan 7 11:50:10 AM  #9 exporting cache
Jan 7 11:50:18 AM  #9 DONE 7.3s
Jan 7 11:50:19 AM  Pushing image to registry...
Jan 7 11:50:24 AM  Upload succeeded
Jan 7 11:50:24 AM  DONE

No more lines, no explanation, and the deploy fails.

my Dockerfile:

FROM amazoncorretto:19-alpine-jdk
MAINTAINER emaaristimuno
COPY target/mm-0.0.1-SNAPSHOT.jar mm-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java","-jar","/mm-0.0.1-SNAPSHOT.jar"]

ps: I'm using NetBeans.

The docs about Docker and MySQL in Render are this:
https://render.com/docs/deploy-mysql
But they don't really help me much.

My POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
        <relativePath/>
    </parent>
    <groupId>com.portfolio</groupId>
    <artifactId>mm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mm</name>
    <description>Portfolio Maria Monchot</description>
    <properties>
        <java.version>19</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

my application.properties:

#Ambientes de prueba
#spring.datasource.url=jdbc:mysql://localhost:3306/backendmm?useSSL=false&serverTimezone=UTC
#spring.datasource.username=root
#spring.datasorce.password=

#Ambientes de producción
spring.datasource.url=jdbc:mysql:urlfrommydatabase
spring.datasource.username=userfrommydatabase
spring.datasorce.password=passwordfrommydatabase

#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.ddl-auto=none
spring.datasource.hikari.maximum-pool-size=2

#JWT
jwt.secret = secret
jwt.expiration = 3600

The path of my JAR:
C:\Users\Katerina\Desktop\Proyecto Portfolio PPA\BackEnd-Portfolio-PPA\target\mm-0.0.1-SNAPSHOT.jar


来源: stackexchange

问:
Matplotlib plots distorted shapes instead of a polygon and a wedge
I am trying to add a function to the pycircos module written by ponnhide on https://github.com/ponnhide/pyCircos/blob/master/pycircos/pycircos.py. I tried to add a circular arrow in the circular plot, which is a patch collection from a ring and an arrow. However, when I call the function I put into the pycircos module in my python notebook, I get a very distorted shape, which has nothing to do with the ring (wedge) or the arrow (polygon).

I have integrated the following function from https://github.com/NaysanSaran/markov-chain/blob/master/notebooks/Drawing.ipynb in the following pycircos module:

```<code>def draw_self_loop(self, center=(0, 0), radius=500, facecolor='#2693de', edgecolor='#000000', theta1=-30, theta2=240):

        # Add the ring
        rwidth = 0.02
        ring = mpatches.Wedge(center, radius, theta1, theta2, width=rwidth)
        # Triangle edges
        offset = 0.02
        xcent  = center[0] - radius + (rwidth/2)
        left   = [xcent - offset, center[1]]
        right  = [xcent + offset, center[1]]
        bottom = [(left[0]+right[0])/2., center[1]-0.05]
        arrow  = plt.Polygon([left, right, bottom, left])
        p = PatchCollection(
            [ring, arrow],
            edgecolor = edgecolor,
            facecolor = facecolor
        )
        self.ax.add_collection(p)
</code>```

In my python notebook, I have called the function from the class object "circle" at the second last line:

```<code>%matplotlib inline
import pycircos
import matplotlib.pyplot as plt
import collections
from Bio import SeqIO
Garc    = pycircos.Garc
Gcircle = pycircos.Gcircle
arcList_size = []
arcList_name = []
circle = Gcircle(figsize=(8,8))
with open("BIM_data_general.txt") as f:
    f.readline()
    for line in f:
        line   = line.rstrip().split(",")
        name   = line[0]
        length = int(line[-1])
        arc    = Garc(arc_id=name, size=length, interspace=2, raxis_range=(990,1000),
                      labelposition=50,facecolor="#FFFFFF",edgecolor="#FFFFFF",labelsize=15, label_visible=False)
        arcList_size.append(arc.size)
        arcList_name.append(arc.arc_id)
        circle.add_garc(arc)
circle.set_garcs(0,360)
circle.draw_self_loop()
circle.figure
</code>```

instead of this example  , I get this distorted shape

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add a function to the pycircos module written by ponnhide on https://github.com/ponnhide/pyCircos/blob/master/pycircos/pycircos.py. I tried to add a circular arrow in the circular plot, which is a patch collection from a ring and an arrow. However, when I call the function I put into the pycircos module in my python notebook, I get a very distorted shape, which has nothing to do with the ring (wedge) or the arrow (polygon).

I have integrated the following function from https://github.com/NaysanSaran/markov-chain/blob/master/notebooks/Drawing.ipynb in the following pycircos module:

def draw_self_loop(self, center=(0, 0), radius=500, facecolor='#2693de', edgecolor='#000000', theta1=-30, theta2=240):

        # Add the ring
        rwidth = 0.02
        ring = mpatches.Wedge(center, radius, theta1, theta2, width=rwidth)
        # Triangle edges
        offset = 0.02
        xcent  = center[0] - radius + (rwidth/2)
        left   = [xcent - offset, center[1]]
        right  = [xcent + offset, center[1]]
        bottom = [(left[0]+right[0])/2., center[1]-0.05]
        arrow  = plt.Polygon([left, right, bottom, left])
        p = PatchCollection(
            [ring, arrow],
            edgecolor = edgecolor,
            facecolor = facecolor
        )
        self.ax.add_collection(p)

In my python notebook, I have called the function from the class object "circle" at the second last line:

%matplotlib inline
import pycircos
import matplotlib.pyplot as plt
import collections
from Bio import SeqIO
Garc    = pycircos.Garc
Gcircle = pycircos.Gcircle
arcList_size = []
arcList_name = []
circle = Gcircle(figsize=(8,8))
with open("BIM_data_general.txt") as f:
    f.readline()
    for line in f:
        line   = line.rstrip().split(",")
        name   = line[0]
        length = int(line[-1])
        arc    = Garc(arc_id=name, size=length, interspace=2, raxis_range=(990,1000),
                      labelposition=50,facecolor="#FFFFFF",edgecolor="#FFFFFF",labelsize=15, label_visible=False)
        arcList_size.append(arc.size)
        arcList_name.append(arc.arc_id)
        circle.add_garc(arc)
circle.set_garcs(0,360)
circle.draw_self_loop()
circle.figure

instead of this example  , I get this distorted shape


问:
How to download surge.sh repository?
How to download surge.sh repository? I deployed application, then lost code. How to recover it from surge.sh? Github repository was not updated.

Until 2016, it was not possible: https://github.com/sintaxi/surge/issues/192

Title: How to download surge.sh repository?


问:
How to count reapeted lists/dictionaries into a list?
i'm recently learning python, and my question is: How to count repeated lists which is contained by a list.

For example: list1 = [[sublist1],[sublist2], [sublist3]] and so on.

I understand by elements it's required to use the fuction count(), but I don't know how to execute my program neither to lists into lists nor dict into lists.

Thank you guys!

I'm really lost. I've searched a lot, but without success.


问:
How could I add a confirm dialog to one of Laravel Nova's (4.0) MenuItems?
I thought this would be fairly simple to implement but after some trial & error I'm not getting very far. Laravel Nova 4.0 does not have a 'confirm' or an 'onbefore' method for MenuItems. I tried using vanilla javascript but I think because Inertia is being used my listeners are being ignored:

MenuItem::link('Update Prices', '/consume-pricing')
                    ->name('Update Prices')
                    ->withBadge(Badge::make('Force', 'info'))
                    ->openInNewTab()
```
<pre class="lang-js prettyprint-override"><code>const consume_pricing_link = document.querySelectorAll("a[href*='/consume-pricing']")[0];
consume_pricing_link.addEventListener('click', function (event) {
    if (!confirm('Are you sure?')) {
        event.preventDefault();
    }
});
</code>```

Is there possibly some way I can hook into the Inertia action's onBefore method?

It'd be a bonus if I could use Nova's native confirmation dialog instead of a generic JavaScript one, but not essential. Thanks for the help.

Body:
I thought this would be fairly simple to implement but after some trial & error I'm not getting very far. Laravel Nova 4.0 does not have a 'confirm' or an 'onbefore' method for MenuItems. I tried using vanilla javascript but I think because Inertia is being used my listeners are being ignored:

MenuItem::link('Update Prices', '/consume-pricing')
                    ->name('Update Prices')
                    ->withBadge(Badge::make('Force', 'info'))
                    ->openInNewTab()

const consume_pricing_link = document.querySelectorAll("a[href*='/consume-pricing']")[0];
consume_pricing_link.addEventListener('click', function (event) {
    if (!confirm('Are you sure?')) {
        event.preventDefault();
    }
});

Is there possibly some way I can hook into the Inertia action's onBefore method?

It'd be a bonus if I could use Nova's native confirmation dialog instead of a generic JavaScript one, but not essential. Thanks for the help.


问:
IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed:
enter code hereEstou com problemas referente a arrays dimensionais

Esperava Plotar no grafito algo do gênero: enter image description here

Codigo: [enter image description here][1]

Problema: [enter image description here][2]

```<code>fig, ax = plt.subplots(figsize = (20,15))

def grafico(group):
    color = "black" if (group["train_test"] < 0).all() else "blue"
    lw = 4.0
    ax.plot(group.index, group.Retorno_Modelo_Acumulado, c = color, linewidth = lw)
    plt.xlabel("Ano"
           , fontsize = 18);
    plt.ylabel("Retorno Acumulado (%)"
           , fontsize = 18);
    plt.title("Ensemble - 19 anos de IND FUT", fontsize = 24)
    plt.axvline( x = end_train, color='purple', linestyle = "--", lw = 2)
    setup = dict(size = 16, color = "darkgreen")
    setup2 = dict(size = 14, color = "black")
    plt.text("2010-03-01", 400, "Treinamento: 2003-2009", **setup)
    plt.text("2010-03-01", 380, "Teste: 2010-2021", **setup)
    plt.text("2010-03-01", 360, ".", **setup2)

base_agregada.groupby((base_agregada["train_test"].shift() * base_agregada["train_test"] < 0).cumsum()).apply(grafico)```

  [1]: https://i.stack.imgur.com/q8C5P.png
  [2]: https://i.stack.imgur.com/1I9aV.png
```

Body:
enter code hereEstou com problemas referente a arrays dimensionais

Esperava Plotar no grafito algo do gênero: enter image description here

Codigo: [enter image description here][1]

Problema: [enter image description here][2]

fig, ax = plt.subplots(figsize = (20,15))

def grafico(group):
    color = "black" if (group["train_test"] < 0).all() else "blue"
    lw = 4.0
    ax.plot(group.index, group.Retorno_Modelo_Acumulado, c = color, linewidth = lw)
    plt.xlabel("Ano"
           , fontsize = 18);
    plt.ylabel("Retorno Acumulado (%)"
           , fontsize = 18);
    plt.title("Ensemble - 19 anos de IND FUT", fontsize = 24)
    plt.axvline( x = end_train, color='purple', linestyle = "--", lw = 2)
    setup = dict(size = 16, color = "darkgreen")
    setup2 = dict(size = 14, color = "black")
    plt.text("2010-03-01", 400, "Treinamento: 2003-2009", **setup)
    plt.text("2010-03-01", 380, "Teste: 2010-2021", **setup)
    plt.text("2010-03-01", 360, ".", **setup2)

base_agregada.groupby((base_agregada["train_test"].shift() * base_agregada["train_test"] < 0).cumsum()).apply(grafico)```

  [1]: https://i.stack.imgur.com/q8C5P.png
  [2]: https://i.stack.imgur.com/1I9aV.png


问:
Using Python Pandas, why is my vectorized gradient descent so much slower than my gradient descent using loops?
Here is my vectorized version:

```<code>import pandas as pd
import numpy as np

alpha=.001

data = [    (2, 3),    (4, 7),    (6, 11),    (8, 17),    (10, 23),    (12, 31),    (14, 39),    (16, 49),    (18, 59),    (20, 71),    (22, 83),    (24, 97),    (26, 113),    (28, 131),    (30, 149),    (32, 169),    (34, 191),    (36, 214),    (38, 239),    (40, 266),    (42, 295),    (44, 326),    (46, 359),    (48, 394),    (50, 431)]

##CREATE EXAMPLES MATRIX
x_coordinates = [x[0] for x in data]
x_coords=[]
[x_coords.append([1,x]) for x in x_coordinates]
#Creates a list of all x-coordinates with a 1 column

examples=pd.DataFrame(x_coords).transpose()
#uses that list to create a dataframe.  Must transpose so it is dimsion 2,25.  rows are features, columns are specific examples.

##CREATE THETA MATRIX/VECTOR
theta_list = [1, 2]
theta = pd.DataFrame(theta_list).transpose()
#creates a df of dimension 1,2.

##CREATE Y VECTOR/MATRIX
y_coordinates = [x[1] for x in data]
y=pd.DataFrame(y_coordinates).transpose()

deriv=pd.DataFrame([])
count=0
while (deriv != 0).all().all() and count <= 500000:

    length=len(data)

    #theta*X
    thetaX=theta.dot(examples)
    error=thetaX-y
    error_pt2=error.dot(examples.T)
    deriv=alpha*(1/length)*error_pt2

    theta=theta-deriv

    print(theta)
    count+=1
    print(count)
</code>```

Here is my version made with loops:

```<code>total=0
th0=0
th1=0
alpha=0.001
deriv0=1
deriv1=1
count=0
while deriv0 and deriv1 != 0 and count<=1000000:
    total0=0
    total1=0
    #th0
    for i in data:

        hyp=th0+(th1*i[0])
        #print("Hyp is {}".format(hyp))

        total0+=(hyp-i[1])

    deriv0=(1/25)*total0

    th0temp=th0-(alpha*(deriv0))

    #th1
    for i in data:
        hyp=th0+(th1*i[0])

        total1+=(hyp-i[1])*i[0]

    deriv1=(1/25)*total1
    th1temp=th1-(alpha*(deriv1))

    th0=th0temp
    th1=th1temp

    th0temp=0
    th1temp=0

    count+=1

    print("Theta 0: {} \n  Theta 1: {} \n\n".format(th0,th1))

print(count)
</code>```

When I run the vectorized version, it takes almost 10 times as long to run.  I would have expected using vectors would make this code much more efficient than running multiple loops.  What gives?  Is it just the computational overhead of Pandas which is making this run slower?  Maybe Pandas isn't suited for this sort of algorithm

Body:
Here is my vectorized version:

import pandas as pd
import numpy as np

alpha=.001

data = [    (2, 3),    (4, 7),    (6, 11),    (8, 17),    (10, 23),    (12, 31),    (14, 39),    (16, 49),    (18, 59),    (20, 71),    (22, 83),    (24, 97),    (26, 113),    (28, 131),    (30, 149),    (32, 169),    (34, 191),    (36, 214),    (38, 239),    (40, 266),    (42, 295),    (44, 326),    (46, 359),    (48, 394),    (50, 431)]

##CREATE EXAMPLES MATRIX
x_coordinates = [x[0] for x in data]
x_coords=[]
[x_coords.append([1,x]) for x in x_coordinates]
#Creates a list of all x-coordinates with a 1 column

examples=pd.DataFrame(x_coords).transpose()
#uses that list to create a dataframe.  Must transpose so it is dimsion 2,25.  rows are features, columns are specific examples.

##CREATE THETA MATRIX/VECTOR
theta_list = [1, 2]
theta = pd.DataFrame(theta_list).transpose()
#creates a df of dimension 1,2.

##CREATE Y VECTOR/MATRIX
y_coordinates = [x[1] for x in data]
y=pd.DataFrame(y_coordinates).transpose()

deriv=pd.DataFrame([])
count=0
while (deriv != 0).all().all() and count <= 500000:

    length=len(data)

    #theta*X
    thetaX=theta.dot(examples)
    error=thetaX-y
    error_pt2=error.dot(examples.T)
    deriv=alpha*(1/length)*error_pt2

    theta=theta-deriv

    print(theta)
    count+=1
    print(count)

Here is my version made with loops:

total=0
th0=0
th1=0
alpha=0.001
deriv0=1
deriv1=1
count=0
while deriv0 and deriv1 != 0 and count<=1000000:
    total0=0
    total1=0
    #th0
    for i in data:

        hyp=th0+(th1*i[0])
        #print("Hyp is {}".format(hyp))

        total0+=(hyp-i[1])

    deriv0=(1/25)*total0

    th0temp=th0-(alpha*(deriv0))

    #th1
    for i in data:
        hyp=th0+(th1*i[0])

        total1+=(hyp-i[1])*i[0]

    deriv1=(1/25)*total1
    th1temp=th1-(alpha*(deriv1))

    th0=th0temp
    th1=th1temp

    th0temp=0
    th1temp=0

    count+=1

    print("Theta 0: {} \n  Theta 1: {} \n\n".format(th0,th1))

print(count)

When I run the vectorized version, it takes almost 10 times as long to run.  I would have expected using vectors would make this code much more efficient than running multiple loops.  What gives?  Is it just the computational overhead of Pandas which is making this run slower?  Maybe Pandas isn't suited for this sort of algorithm


问:
Syslog not sending logs to Papertrail
This code snippet, linked here, should be sending a log message to Papertrail, unfortunately, there's nothing happening at all (no error message either). I did replace the "N" and the "XXXXX" with my own values. The environment is Python 3.10.6 and I'm inside of a virtual environment created by Poetry.

I would expect calling an undefined function to log an exception to Papertrail.

Telnet works fine and my other applications work fine as well.

```<code>import logging
import socket
from logging.handlers import SysLogHandler

syslog = SysLogHandler(address=('logsN.papertrailapp.com', XXXXX))
format = '%(asctime)s YOUR_APP: %(message)s'
formatter = logging.Formatter(format, datefmt='%b %d %H:%M:%S')
syslog.setFormatter(formatter)

logger = logging.getLogger()
logger.addHandler(syslog)
logger.setLevel(logging.INFO)

def my_handler(type, value, tb):
  logger.exception('Uncaught exception: {0}'.format(str(value)))

# Install exception handler
sys.excepthook = my_handler

logger.info('This is a message')
nofunction() #log an uncaught exception
</code>```

Title: Syslog not sending logs to Papertrail

Body:
This code snippet, linked here, should be sending a log message to Papertrail, unfortunately, there's nothing happening at all (no error message either). I did replace the "N" and the "XXXXX" with my own values. The environment is Python 3.10.6 and I'm inside of a virtual environment created by Poetry.

I would expect calling an undefined function to log an exception to Papertrail.

Telnet works fine and my other applications work fine as well.

import logging
import socket
from logging.handlers import SysLogHandler

syslog = SysLogHandler(address=('logsN.papertrailapp.com', XXXXX))
format = '%(asctime)s YOUR_APP: %(message)s'
formatter = logging.Formatter(format, datefmt='%b %d %H:%M:%S')
syslog.setFormatter(formatter)

logger = logging.getLogger()
logger.addHandler(syslog)
logger.setLevel(logging.INFO)

def my_handler(type, value, tb):
  logger.exception('Uncaught exception: {0}'.format(str(value)))

# Install exception handler
sys.excepthook = my_handler

logger.info('This is a message')
nofunction() #log an uncaught exception


问:
I am getting an access error while deploying the angular app on heroku
I am getting an error access while deploying the angular app on heroku.But when I build it with the same command on my machine it's passing well.
I have already tried to delete package-lock.json and node modules ,then npm isntall.It didn't work.
Does anybody know why am I getting this error and how can I fix it?

Error:

```<code>Compiling @angular/core : es2015 as esm2015

       chunk {main} main.js, main.js.map (main) 592 bytes [initial] [rendered]
       chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 637 bytes [initial] [rendered]
       chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
       chunk {styles} styles.js, styles.js.map (styles) 49.6 kB [initial] [rendered]
ERROR in EACCES: permission denied, open '/tmp/build_5fc79d16/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js'
       Date: 2023-01-07T00:28:38.382Z - Hash: dcb91659efb59917b4c9 - Time: 5632ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! microsoft-login@0.0.0 heroku-postbuild: `ng build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the microsoft-login@0.0.0 heroku-postbuild script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.3gKmp/_logs/2023-01-07T00_28_38_419Z-debug.log

</code>```

package.json:

```<code>{
  "name": "microsoft-login",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "heroku-postbuild": "ng build --prod"
  },
  "engines":{"node":"10.13.0","npm":"6.11.0"},
  "private": true,
  "dependencies": {
    "@angular/animations": "~10.1.6",
    "@angular/common": "~10.1.6",
    "@angular/compiler": "~10.1.6",
    "@angular/core": "~10.1.6",
    "@angular/forms": "~10.1.6",
    "@angular/platform-browser": "~10.1.6",
    "@angular/platform-browser-dynamic": "~10.1.6",
    "@angular/router": "~10.1.6",
    "@azure/msal-angular": "^2.0.0-alpha.6",
    "@azure/msal-browser": "^2.11.2",
    "msal": "^1.4.6",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1001.7",
    "@angular/cli": "~10.1.7",
    "@angular/compiler-cli": "~10.1.6",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}
</code>```

Body:
I am getting an error access while deploying the angular app on heroku.But when I build it with the same command on my machine it's passing well.
I have already tried to delete package-lock.json and node modules ,then npm isntall.It didn't work.
Does anybody know why am I getting this error and how can I fix it?

Error:

Compiling @angular/core : es2015 as esm2015

       chunk {main} main.js, main.js.map (main) 592 bytes [initial] [rendered]
       chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 637 bytes [initial] [rendered]
       chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
       chunk {styles} styles.js, styles.js.map (styles) 49.6 kB [initial] [rendered]
ERROR in EACCES: permission denied, open '/tmp/build_5fc79d16/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js'
       Date: 2023-01-07T00:28:38.382Z - Hash: dcb91659efb59917b4c9 - Time: 5632ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! microsoft-login@0.0.0 heroku-postbuild: `ng build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the microsoft-login@0.0.0 heroku-postbuild script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /tmp/npmcache.3gKmp/_logs/2023-01-07T00_28_38_419Z-debug.log

package.json:

{
  "name": "microsoft-login",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "heroku-postbuild": "ng build --prod"
  },
  "engines":{"node":"10.13.0","npm":"6.11.0"},
  "private": true,
  "dependencies": {
    "@angular/animations": "~10.1.6",
    "@angular/common": "~10.1.6",
    "@angular/compiler": "~10.1.6",
    "@angular/core": "~10.1.6",
    "@angular/forms": "~10.1.6",
    "@angular/platform-browser": "~10.1.6",
    "@angular/platform-browser-dynamic": "~10.1.6",
    "@angular/router": "~10.1.6",
    "@azure/msal-angular": "^2.0.0-alpha.6",
    "@azure/msal-browser": "^2.11.2",
    "msal": "^1.4.6",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1001.7",
    "@angular/cli": "~10.1.7",
    "@angular/compiler-cli": "~10.1.6",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}


问:
Use WebSocket wrapper for all iframe, ws requests
I'm trying to experiment if I can force all elements within an iframe (of dask-labextension to be precise) to use a custom web socket wrapper following answers to this question with the following snippet:

```<code>const iframe = document.getElementsByTagName("iframe")[0];
const originalSocket = iframe.contentWindow.WebSocket;
iframe.contentWindow.WebSocket = function(...args) {
    const socket = originalSocket(...args);
    console.log("Creating new socket: ", socket);
    return socket;
};

iframe.contentWindow.WebSocket.prototype = originalSocket.prototype;
iframe.contentWindow.WebSocket.prototype.constructor = iframe.contentWindow.WebSocket;
</code>```

JupyterLab's Dask Extension loads a bunch of dashboards as iframes, each of which includes the following bokeh js files:

```<code><head>
    <meta charset="utf-8">
    <title>Bokeh Application</title>
    <script type="text/javascript" src="static/js/bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314"></script>
    <script type="text/javascript" src="static/js/bokeh-gl.min.js?v=e5df31fd9010eacff0aa72d315264604b5e34972ba445acea6fce98080eecf33acf2d2986126360faaa5852813cffa16f6f6f4889923318300f062497c02da4e"></script>
    <script type="text/javascript" src="static/js/bokeh-widgets.min.js?v=8a1ff6f5aa0d967f4998d275803bbb111d928fd9f605ef9e1f30cfd021df0e77224ee3d13f83edb3a942f6e4ccc569ee5dd8951a8aa6cb600602463b90c65a87"></script>
    <script type="text/javascript" src="static/js/bokeh-tables.min.js?v=ae2903e57cf57f52819fdf4d938c648982b51c34f73b6e653a0f3bb3c8ab44f338505931ace43eafc1636e215492e2314acf54c54baffb47813b86b4923a7fe0"></script>
    <script type="text/javascript" src="static/js/bokeh-mathjax.min.js?v=176c36fdbcd8fc1019fc828101a2804081a35baf4018d7f2633cd263156b593aa73112f400112b662daa0590138b74851bc91f1f2a5fbf5416ee8c876c3e0d0c"></script>
    <script type="text/javascript">
        Bokeh.set_log_level("info");
    </script>
  </head>
</code>```

But it looks like all of Bokeh's websocket requests goes through a separate WebSocket object, instead of my custom wrapper. The following are console logs coming from Bokeh:

```<code>[bokeh] setting log level to: 'info'
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:587 [bokeh] Websocket connection 0 is now open
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:165 [bokeh] document idle at 94 ms
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:163 Bokeh items were rendered successfully
</code>```

The console output seems to be missing the console log I have around my custom wrapper, which makes me think it uses a different WebSocket function.

Is there a way to force Bokeh (or any other included script's) websockets to use my custom wrapper?

Body:
I'm trying to experiment if I can force all elements within an iframe (of dask-labextension to be precise) to use a custom web socket wrapper following answers to this question with the following snippet:

const iframe = document.getElementsByTagName("iframe")[0];
const originalSocket = iframe.contentWindow.WebSocket;
iframe.contentWindow.WebSocket = function(...args) {
    const socket = originalSocket(...args);
    console.log("Creating new socket: ", socket);
    return socket;
};

iframe.contentWindow.WebSocket.prototype = originalSocket.prototype;
iframe.contentWindow.WebSocket.prototype.constructor = iframe.contentWindow.WebSocket;

JupyterLab's Dask Extension loads a bunch of dashboards as iframes, each of which includes the following bokeh js files:

    <meta charset="utf-8">
    <title>Bokeh Application</title>

But it looks like all of Bokeh's websocket requests goes through a separate WebSocket object, instead of my custom wrapper. The following are console logs coming from Bokeh:

[bokeh] setting log level to: 'info'
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:587 [bokeh] Websocket connection 0 is now open
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:165 [bokeh] document idle at 94 ms
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:163 Bokeh items were rendered successfully

The console output seems to be missing the console log I have around my custom wrapper, which makes me think it uses a different WebSocket function.

Is there a way to force Bokeh (or any other included script's) websockets to use my custom wrapper?


问:
what is the slution to this problem Failed to launch Pixel 2 API 30: Error: Emulator didn't connect within 60 seconds
I have a problem with the emulator; however, I have tried everything to fix it, but nothing has worked.
I created an emulator, and I did wipe its data and restart Android Studio, and HAXM is also installed.
and I'm using Flutter paltform in VS code BTW!
I did try this:  adb kill-server, and VT-X is enabled and every SDK tool is installed!
and shows the following error message: Failed to launch Pixel 2 API 30: Error: Emulator didn't connect within 60 seconds


问:
Can I extend Joi schema using a existent rule?
I have a schema like this (the real one is doble the size):

const optionalIfPatch = { patch: (schema: AnySchema) => schema.optional() };

const personValidator = Joi.object({
  username: Joi.string().token().lowercase().min(5).required().alter(optionalIfPatch),
  password: Joi.string().min(6).required().alter(optionalIfPatch),
  fullName: Joi.string().min(5).required().alter(optionalIfPatch),
  email: Joi.string().email().required().alter(optionalIfPatch),
  userProfile: Joi.string().valid(...Object.keys(UserProfile)).default(UserProfile.default),
  address: Joi.object({
    streetAddress: Joi.string().min(5),
    city: Joi.string().min(3),
    state: Joi.string().min(3),
    zipCode: Joi.string().min(3),
  }),
}).options({ abortEarly: false });
```
<p>Basically I want make required fields optional with the <code>personValidator.tailor()</code> function at validation time. It works this way, but I was trying to make this behavior into an extension:</p>
<pre class="lang-js prettyprint-override"><code>const joiExtensions: Joi.ExtensionFactory[] = [
  (joi: Joi.Root) => ({
    type: /.*/,
    rules: {
      requiredButPatchable: {
        alias: 'reqOrPatch',
        method() {
          return this.required().alter(optionalIfPatch); // GOT STUCK HERE
        }
      },
    },
  }),
];
</code>```

To be used like this:

Joi.string().token().lowercase().min(5).requiredButPatchable()
```

But to be honest, I've been researching for three days and couldn't find a proper explanation of how to build an extension like this (using Joi itself).

(Also, when I extend the Joi model, I loose the autocompletion for VSCode... is there a way arround it?)

I've tried the Joi docs, git issues, stack overflow questions... couldn't find a proper answer.
I want to use the alter()and tailor() functionalities as an extension so I can reduce the repeated code...

Body:
I have a schema like this (the real one is doble the size):

const optionalIfPatch = { patch: (schema: AnySchema) => schema.optional() };

const personValidator = Joi.object({
  username: Joi.string().token().lowercase().min(5).required().alter(optionalIfPatch),
  password: Joi.string().min(6).required().alter(optionalIfPatch),
  fullName: Joi.string().min(5).required().alter(optionalIfPatch),
  email: Joi.string().email().required().alter(optionalIfPatch),
  userProfile: Joi.string().valid(...Object.keys(UserProfile)).default(UserProfile.default),
  address: Joi.object({
    streetAddress: Joi.string().min(5),
    city: Joi.string().min(3),
    state: Joi.string().min(3),
    zipCode: Joi.string().min(3),
  }),
}).options({ abortEarly: false });

Basically I want make required fields optional with the personValidator.tailor() function at validation time. It works this way, but I was trying to make this behavior into an extension:

const joiExtensions: Joi.ExtensionFactory[] = [
  (joi: Joi.Root) => ({
    type: /.*/,
    rules: {
      requiredButPatchable: {
        alias: 'reqOrPatch',
        method() {
          return this.required().alter(optionalIfPatch); // GOT STUCK HERE
        }
      },
    },
  }),
];

To be used like this:

Joi.string().token().lowercase().min(5).requiredButPatchable()

But to be honest, I've been researching for three days and couldn't find a proper explanation of how to build an extension like this (using Joi itself).

(Also, when I extend the Joi model, I loose the autocompletion for VSCode... is there a way arround it?)

I've tried the Joi docs, git issues, stack overflow questions... couldn't find a proper answer.
I want to use the alter()and tailor() functionalities as an extension so I can reduce the repeated code...


问:
anaconda prompt can't open it's showing error of mentioned below
Unable to create process using 'C:\Users\My Name\anaconda3\python.exe "C:\Users\My Name\anaconda3\Scripts\conda-script.py" shell.powershell activate "C:\Users\My Name\anaconda3"'
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Users\Amirah Trini Raehana\anaconda3\shell\condabin\Conda.psm1:76 char:36

```<code>    Invoke-Expression -Command $activateCommand;
</code>```

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

CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException

FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Invo
keExpressionCommand

Previously when I installed Microsoft Visual Studio and Microsoft Visual C++ 2022 then I opened Anaconda and it didn't run,
I have tried to uninstall Microsoft Visual Studio and Anaconda and tried to reinstall Anaconda, the error above still appears

Body:
Unable to create process using 'C:\Users\My Name\anaconda3\python.exe "C:\Users\My Name\anaconda3\Scripts\conda-script.py" shell.powershell activate "C:\Users\My Name\anaconda3"'
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Users\Amirah Trini Raehana\anaconda3\shell\condabin\Conda.psm1:76 char:36

    Invoke-Expression -Command $activateCommand;

                               ~~~~~~

CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException

FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Invo
keExpressionCommand

Previously when I installed Microsoft Visual Studio and Microsoft Visual C++ 2022 then I opened Anaconda and it didn't run,
I have tried to uninstall Microsoft Visual Studio and Anaconda and tried to reinstall Anaconda, the error above still appears


问:
document.querySelectorAll() not returning expected results (in puppeteer)
Using puppeteer in nodejs and trying to extract links from a page.

  let response;
  try {
    response = await page.goto(url)
    const noOfLinks = await page.evaluate(_ => document.querySelectorAll('a[href$=".pgn"]'));
    console.log({ status: response.status(), noOfLinks})
    console.log({href: noOfLinks[0].getAttribute('href')})
  } catch (e) {
    console.log(e.toString())
  }
```
<p>However, noOfLinks.getAttribute() returns an error:
<code>TypeError: noOfLinks[0].getAttribute is not a function</code></p>
<p>It's obvious why from the previous log statement:</p>
```{
  status: 200,
  noOfLinks: {
    '0': {},
    '1': {},...
```

Each link looks like an empty object. If I run .querySelectorAll and .getAttribute in a browser console for that page, I get the expected return values.

Is there something I need to do differently in puppeteer?

Body:
Using puppeteer in nodejs and trying to extract links from a page.

  let response;
  try {
    response = await page.goto(url)
    const noOfLinks = await page.evaluate(_ => document.querySelectorAll('a[href$=".pgn"]'));
    console.log({ status: response.status(), noOfLinks})
    console.log({href: noOfLinks[0].getAttribute('href')})
  } catch (e) {
    console.log(e.toString())
  }

However, noOfLinks.getAttribute() returns an error:
TypeError: noOfLinks[0].getAttribute is not a function

It's obvious why from the previous log statement:

{
  status: 200,
  noOfLinks: {
    '0': {},
    '1': {},...

Each link looks like an empty object. If I run .querySelectorAll and .getAttribute in a browser console for that page, I get the expected return values.

Is there something I need to do differently in puppeteer?


问:
Auth0 works locally with built-in macOS php dev server but not with mamp
I'm using Auth0's example code for the php sdk, which works fine when I run it from the macOS dev server (php -S 127.0.0.1:3000 index.php) but it doesn't work with mamp. With mamp, it doesn't go to the universal login, but instead routes to 127.0.0.1:3000/login, which doesn't exist as a page because the login() method is supposed to route to Auth0's universal login.

index.php

```<code>
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Import the Composer Autoloader to make the SDK classes accessible:
require 'vendor/autoload.php';

// Load our environment variables from the .env file:
(Dotenv\Dotenv::createImmutable(__DIR__))->load();

// Now instantiate the Auth0 class with our configuration:
$auth0 = new \Auth0\SDK\Auth0([
    'domain' => $_ENV['AUTH0_DOMAIN'],
    'clientId' => $_ENV['AUTH0_CLIENT_ID'],
    'clientSecret' => $_ENV['AUTH0_CLIENT_SECRET'],
    'cookieSecret' => $_ENV['AUTH0_COOKIE_SECRET']
]);

// Import our router library:
use Steampixel\Route;

// Define route constants:
define('ROUTE_URL_INDEX', rtrim($_ENV['AUTH0_BASE_URL'], '/'));
define('ROUTE_URL_LOGIN', ROUTE_URL_INDEX . '/login');
define('ROUTE_URL_CALLBACK', ROUTE_URL_INDEX . '/callback');
define('ROUTE_URL_LOGOUT', ROUTE_URL_INDEX . '/logout');

Route::add('/', function() use ($auth0) {
  $session = $auth0->getCredentials();

  if ($session === null) {
    // The user isn't logged in.
    include_once "landing/index.php";

  }

  // The user is logged in.
  echo '```';
  print_r($session->user);
  echo '```';

  echo '<p>You can now log out.</p>';

  include_once "app/main.php";

});

Route::add('/login', function() use ($auth0) {
    // It's a good idea to reset user sessions each time they go to login to avoid "invalid state" errors, should they hit network issues or other problems that interrupt a previous login process:
    $auth0->clear();

    // Finally, set up the local application session, and redirect the user to the Auth0 Universal Login Page to authenticate.
    header("Location: " . $auth0->login(ROUTE_URL_CALLBACK));
    exit;
});

Route::add('/callback', function() use ($auth0) {
    // Have the SDK complete the authentication flow:
    $auth0->exchange(ROUTE_URL_CALLBACK);

    // Finally, redirect our end user back to the / index route, to display their user profile:
    header("Location: " . ROUTE_URL_INDEX);
    exit;
});

Route::add('/logout', function() use ($auth0) {
    // Clear the user's local session with our app, then redirect them to the Auth0 logout endpoint to clear their Auth0 session.
    header("Location: " . $auth0->logout(ROUTE_URL_INDEX));
    exit;
});

// This tells our router that we've finished configuring our routes, and we're ready to begin routing incoming HTTP requests:
Route::run('/');
</code>```

The landing page shows up as expected when the user is not logged in. But when the login button is clicked, the login() method is not called as is supposed to happen; instead, it redirects to 127.0.0.1:3000/login, which expectedly throws a 404 because that page doesn't exist. This error only happens with mamp. When I stop mamp and switch to the built-in macOS dev server, everything works fine.

I tried downgrading php from 8.1.9 to 8.1.0 to match the latest php version for mamp but it still didn't work. I've been struggling with this for days and can't figure it out.

Body:
I'm using Auth0's example code for the php sdk, which works fine when I run it from the macOS dev server (php -S 127.0.0.1:3000 index.php) but it doesn't work with mamp. With mamp, it doesn't go to the universal login, but instead routes to 127.0.0.1:3000/login, which doesn't exist as a page because the login() method is supposed to route to Auth0's universal login.

index.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Import the Composer Autoloader to make the SDK classes accessible:
require 'vendor/autoload.php';

// Load our environment variables from the .env file:
(Dotenv\Dotenv::createImmutable(__DIR__))->load();

// Now instantiate the Auth0 class with our configuration:
$auth0 = new \Auth0\SDK\Auth0([
    'domain' => $_ENV['AUTH0_DOMAIN'],
    'clientId' => $_ENV['AUTH0_CLIENT_ID'],
    'clientSecret' => $_ENV['AUTH0_CLIENT_SECRET'],
    'cookieSecret' => $_ENV['AUTH0_COOKIE_SECRET']
]);

// Import our router library:
use Steampixel\Route;

// Define route constants:
define('ROUTE_URL_INDEX', rtrim($_ENV['AUTH0_BASE_URL'], '/'));
define('ROUTE_URL_LOGIN', ROUTE_URL_INDEX . '/login');
define('ROUTE_URL_CALLBACK', ROUTE_URL_INDEX . '/callback');
define('ROUTE_URL_LOGOUT', ROUTE_URL_INDEX . '/logout');

Route::add('/', function() use ($auth0) {
  $session = $auth0->getCredentials();

  if ($session === null) {
    // The user isn't logged in.
    include_once "landing/index.php";

  }

  // The user is logged in.
  echo '
';
  print_r($session->user);
  echo '
';

  echo '
You can now log out.
';

  include_once "app/main.php";

});

Route::add('/login', function() use ($auth0) {
    // It's a good idea to reset user sessions each time they go to login to avoid "invalid state" errors, should they hit network issues or other problems that interrupt a previous login process:
    $auth0->clear();

    // Finally, set up the local application session, and redirect the user to the Auth0 Universal Login Page to authenticate.
    header("Location: " . $auth0->login(ROUTE_URL_CALLBACK));
    exit;
});

Route::add('/callback', function() use ($auth0) {
    // Have the SDK complete the authentication flow:
    $auth0->exchange(ROUTE_URL_CALLBACK);

    // Finally, redirect our end user back to the / index route, to display their user profile:
    header("Location: " . ROUTE_URL_INDEX);
    exit;
});

Route::add('/logout', function() use ($auth0) {
    // Clear the user's local session with our app, then redirect them to the Auth0 logout endpoint to clear their Auth0 session.
    header("Location: " . $auth0->logout(ROUTE_URL_INDEX));
    exit;
});

// This tells our router that we've finished configuring our routes, and we're ready to begin routing incoming HTTP requests:
Route::run('/');

The landing page shows up as expected when the user is not logged in. But when the login button is clicked, the login() method is not called as is supposed to happen; instead, it redirects to 127.0.0.1:3000/login, which expectedly throws a 404 because that page doesn't exist. This error only happens with mamp. When I stop mamp and switch to the built-in macOS dev server, everything works fine.

I tried downgrading php from 8.1.9 to 8.1.0 to match the latest php version for mamp but it still didn't work. I've been struggling with this for days and can't figure it out.


问:
How to import a function from one class to another class that are in the same file
i have created a function called New_button that is in a class called Maths class. There is another class within the same file called New maths class which opens when the user click on new maths class and they are asked to enter the name of the class and click submit.When they do the name is saved onto a database and a message box appears stating that the data has been saved and there's an option to click yes. When 'yes' is clicked i would like the function New_button from the class in Maths class to be called as the button with the new class name to be displayed.

This is my code

```<code>class Maths_class(tk.Frame):
    def __init__(self, master):
    tk.Frame.__init__(self, master)
    master.title('Maths class ')
    master.configure(bg='white')

    tk.Label(self, text="Year 7 Wizards Maths Game\n Maths classes", font= ('Calbiri 20 bold'), bg='white').pack()
    tk.Button(self, text="New maths class", width=30, height=2,borderwidth=0,command=lambda:master.switch_frame('PageTwelve')).pack()

    def new_button():
        cursor.execute("SELECT classes_name FROM maths_class")
        classes=cursor.fetchall()
        NewClass=classes[-1]
        data_str = ','.join([str(row) for row in NewClass])

        tk.Button(self,text=data_str).pack()

class New_maths_class (tk.Frame):
    def __init__(self, master):
    tk.Frame.__init__(self, master)

     # genreate class code
    code = ""
    for i in range(0, 6):
        code_char = random.choice(char)
        code = code + code_char

    #class ID
    x = 0
    cursor.execute("SELECT * FROM maths_class")
    for row in cursor.fetchall():
        x = row[0]
    Class_ID = x+1
    #leaderboard ID
    y = 0
    cursor.execute("SELECT * FROM leaderboard")
    for row in cursor.fetchall():
        y = row[0]
    Leaderboard_ID = y+1
    def new_button():
        cursor.execute("SELECT classes_name FROM maths_class")
        classes=cursor.fetchall()
        NewClass=classes[-1]
        data_str = ','.join([str(row) for row in NewClass])

        tk.Button(self,text=data_str).pack()

    def Insert_new_class():
        New_class=New_class_box.get()
        Teacher=teacher_box.get()
        cursor.execute('INSERT INTO leaderboard (leaderboard_ID) VALUES (?)', Leaderboard_ID)
        conn.commit()
        cursor.execute("SELECT Teacher_login_ID FROM teacherlogin WHERE teacher_username=?",(Teacher))
        Teacher_name=cursor.fetchone()
        if Teacher_name:
            Teacher_name=Teacher_name
            Teacher_ID=Teacher_name[0]

        try:

            cursor.execute('INSERT INTO maths_class (classes_ID,classes_name,class_code,teacher_login_ID,leaderboard_ID) VALUES (?,?,?,?,?)', Class_ID,New_class,code,Teacher_ID,Leaderboard_ID)
            conn.commit()
            print('Data Inserted')
            msg_box = tk.messagebox.askquestion('Contiue to main application', 'New class has been created')
            if msg_box == 'yes':
                    master.switch_frame("PageEleven")
                    new_button()

        except pyodbc.Error as e:
            print("Error in Connection", e)

    teacher_name = Label(self, text="User Name")
    teacher_name.pack()

    teacher_box=Entry(self)
    teacher_box.pack()

    class_name = Label(self, text="Class Name")
    class_name.pack()

    New_class_box=Entry(self)
    New_class_box.pack()
    submit_button = Button(self, text="submit",borderwidth=0,command=lambda: Insert_new_class())
    submit_button.pack()
</code>```

Body:
i have created a function called New_button that is in a class called Maths class. There is another class within the same file called New maths class which opens when the user click on new maths class and they are asked to enter the name of the class and click submit.When they do the name is saved onto a database and a message box appears stating that the data has been saved and there's an option to click yes. When 'yes' is clicked i would like the function New_button from the class in Maths class to be called as the button with the new class name to be displayed.

This is my code

class Maths_class(tk.Frame):
    def __init__(self, master):
    tk.Frame.__init__(self, master)
    master.title('Maths class ')
    master.configure(bg='white')

    tk.Label(self, text="Year 7 Wizards Maths Game\n Maths classes", font= ('Calbiri 20 bold'), bg='white').pack()
    tk.Button(self, text="New maths class", width=30, height=2,borderwidth=0,command=lambda:master.switch_frame('PageTwelve')).pack()

    def new_button():
        cursor.execute("SELECT classes_name FROM maths_class")
        classes=cursor.fetchall()
        NewClass=classes[-1]
        data_str = ','.join([str(row) for row in NewClass])

        tk.Button(self,text=data_str).pack()

class New_maths_class (tk.Frame):
    def __init__(self, master):
    tk.Frame.__init__(self, master)

     # genreate class code
    code = ""
    for i in range(0, 6):
        code_char = random.choice(char)
        code = code + code_char

    #class ID
    x = 0
    cursor.execute("SELECT * FROM maths_class")
    for row in cursor.fetchall():
        x = row[0]
    Class_ID = x+1
    #leaderboard ID
    y = 0
    cursor.execute("SELECT * FROM leaderboard")
    for row in cursor.fetchall():
        y = row[0]
    Leaderboard_ID = y+1
    def new_button():
        cursor.execute("SELECT classes_name FROM maths_class")
        classes=cursor.fetchall()
        NewClass=classes[-1]
        data_str = ','.join([str(row) for row in NewClass])

        tk.Button(self,text=data_str).pack()

    def Insert_new_class():
        New_class=New_class_box.get()
        Teacher=teacher_box.get()
        cursor.execute('INSERT INTO leaderboard (leaderboard_ID) VALUES (?)', Leaderboard_ID)
        conn.commit()
        cursor.execute("SELECT Teacher_login_ID FROM teacherlogin WHERE teacher_username=?",(Teacher))
        Teacher_name=cursor.fetchone()
        if Teacher_name:
            Teacher_name=Teacher_name
            Teacher_ID=Teacher_name[0]

        try:

            cursor.execute('INSERT INTO maths_class (classes_ID,classes_name,class_code,teacher_login_ID,leaderboard_ID) VALUES (?,?,?,?,?)', Class_ID,New_class,code,Teacher_ID,Leaderboard_ID)
            conn.commit()
            print('Data Inserted')
            msg_box = tk.messagebox.askquestion('Contiue to main application', 'New class has been created')
            if msg_box == 'yes':
                    master.switch_frame("PageEleven")
                    new_button()

        except pyodbc.Error as e:
            print("Error in Connection", e)

    teacher_name = Label(self, text="User Name")
    teacher_name.pack()

    teacher_box=Entry(self)
    teacher_box.pack()

    class_name = Label(self, text="Class Name")
    class_name.pack()

    New_class_box=Entry(self)
    New_class_box.pack()
    submit_button = Button(self, text="submit",borderwidth=0,command=lambda: Insert_new_class())
    submit_button.pack()


问:
ValueError: With n_samples=0, test_size=0.25 and train_size=0.75, the resulting train set will be empty. Adjust any of the aforementioned parameters
I'm making a prize pick best pick analyzer using the FanatsyData Api IDK if the issue is getting the data or getting the code. I'm getting this error  ValueError: With n_samples=0, test_size=0.25 and train_size=0.75, the resulting train set will be empty. Adjust any of the aforementioned parameters.

Can someone please help?

```<code>Traceback (most recent call last):
  File "C:\Users\markn\OneDrive\Desktop\Important\CS\Projects\PrizePicks\main.py", line 99, in <module>
    model = create_player_performance_model(player_data)
  File "C:\Users\markn\OneDrive\Desktop\Important\CS\Projects\PrizePicks\main.py", line 63, in create_player_performance_model
    X_train, X_test, y_train, y_test = train_test_split(df[features], df[features], test_size=0.25, random_state=42, train_size=.75)
  File "C:\Users\markn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\sklearn\model_selection\_split.py", line 2562, in train_test_split
    n_train, n_test = _validate_shuffle_split(
  File "C:\Users\markn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\sklearn\model_selection\_split.py", line 2236, in _validate_shuffle_split
    raise ValueError(
ValueError: With n_samples=0, test_size=0.25 and train_size=0.75, the resulting train set will be empty. Adjust any of the aforementioned parameters.
</code>```
```<code>import requests
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

import datetime
def collect_player_data():
  """Collects data on player performance using the FantasyData API"""
  player_data = []

  # Set up the API request
  api_key = "46a723ebe82d4b9f9620bf0bb10d4fc9"
  base_url = "https://www.fantasydata.com/v3/nfl/stats/JSON/PlayerSeasonStats"
  headers = { "Ocp-Apim-Subscription-Key": api_key }

  # Get today's date in the correct format for the API request
  today = datetime.datetime.now()
  date_str = today.strftime("%Y-%m-%d")

  # Send a request for each sport
  for sport in ["nba"]:
    endpoint = f"{base_url}/{sport}"
    response = requests.get(endpoint, headers=headers)

    # Check the response status code
    if response.status_code != 200:
      print(f"Error: {response.status_code}")
      print(response.content)
      return

    # Print the content of the response to check if it is a valid JSON string
    print(response.content)

    # Extract the player data from the response
    try:
      sport_data = response.json()
    except Exception as e:
      print(f"Error: {e}")
      return
    player_data.extend(sport_data["Players"])

  return player_data

def create_player_performance_model(player_data):
  """Creates a model for predicting player performance using machine learning"""

  # Convert the player data into a Pandas DataFrame
  df = pd.DataFrame(player_data)
  # Print the list of columns in the DataFrame
  print(df.columns)

  # Select the features to use for the model
  features = ["Rebounds", "Assists", "Steals", "Blocks", "MinutesPlayed", "FieldGoalsMade", "ThreePointersMade", "FreeThrowsMade", "Points", "Turnovers"]
  # Make sure all the columns in the features list exist in the DataFrame
  features = [col for col in features if col in df.columns]

  # Split the data into training and testing sets
  # X_train, X_test, y_train, y_test = train_test_split(df[features], test_size=0.25, random_state=42)

  X_train, X_test, y_train, y_test = train_test_split(df[features], df[features], test_size=0.25, random_state=42, train_size=.75)

  # Train a Random Forest Regressor model on the training data
  model = LinearRegression()
  model.fit(X_train, y_train)

  # Evaluate the model on the testing data
  score = model.score(X_test, y_test)
  print(f"Model score: {score:.2f}")

  return model

def generate_picks(model, games, features):
  """Generates picks for the given games using the given model"""
  picks = []

  for game in games:
    players = game["players"]

    # Use the model to predict the fantasy points for each player
    predictions = model.predict(players[features])

    # Select the player with the highest predicted fantasy points
    top_picks = players[predictions.argsort()[-6:][::-1]]
    picks.extend(top_picks)

  return picks

def make_picks(picks):
  """Makes the given picks on the PrizePicks website"""
  # TODO: Implement this function
  pass

# Collect data on player performance
player_data = collect_player_data()

# Use machine learning to analyze the data and create a model for predicting player performance
model = create_player_performance_model(player_data)
</code>```

Body:
I'm making a prize pick best pick analyzer using the FanatsyData Api IDK if the issue is getting the data or getting the code. I'm getting this error  ValueError: With n_samples=0, test_size=0.25 and train_size=0.75, the resulting train set will be empty. Adjust any of the aforementioned parameters.

Can someone please help?

Traceback (most recent call last):
  File "C:\Users\markn\OneDrive\Desktop\Important\CS\Projects\PrizePicks\main.py", line 99, in <module>
    model = create_player_performance_model(player_data)
  File "C:\Users\markn\OneDrive\Desktop\Important\CS\Projects\PrizePicks\main.py", line 63, in create_player_performance_model
    X_train, X_test, y_train, y_test = train_test_split(df[features], df[features], test_size=0.25, random_state=42, train_size=.75)
  File "C:\Users\markn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\sklearn\model_selection\_split.py", line 2562, in train_test_split
    n_train, n_test = _validate_shuffle_split(
  File "C:\Users\markn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\sklearn\model_selection\_split.py", line 2236, in _validate_shuffle_split
    raise ValueError(
ValueError: With n_samples=0, test_size=0.25 and train_size=0.75, the resulting train set will be empty. Adjust any of the aforementioned parameters.

import requests
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

import datetime
def collect_player_data():
  """Collects data on player performance using the FantasyData API"""
  player_data = []

  # Set up the API request
  api_key = "46a723ebe82d4b9f9620bf0bb10d4fc9"
  base_url = "https://www.fantasydata.com/v3/nfl/stats/JSON/PlayerSeasonStats"
  headers = { "Ocp-Apim-Subscription-Key": api_key }

  # Get today's date in the correct format for the API request
  today = datetime.datetime.now()
  date_str = today.strftime("%Y-%m-%d")

  # Send a request for each sport
  for sport in ["nba"]:
    endpoint = f"{base_url}/{sport}"
    response = requests.get(endpoint, headers=headers)

    # Check the response status code
    if response.status_code != 200:
      print(f"Error: {response.status_code}")
      print(response.content)
      return

    # Print the content of the response to check if it is a valid JSON string
    print(response.content)

    # Extract the player data from the response
    try:
      sport_data = response.json()
    except Exception as e:
      print(f"Error: {e}")
      return
    player_data.extend(sport_data["Players"])

  return player_data

def create_player_performance_model(player_data):
  """Creates a model for predicting player performance using machine learning"""

  # Convert the player data into a Pandas DataFrame
  df = pd.DataFrame(player_data)
  # Print the list of columns in the DataFrame
  print(df.columns)

  # Select the features to use for the model
  features = ["Rebounds", "Assists", "Steals", "Blocks", "MinutesPlayed", "FieldGoalsMade", "ThreePointersMade", "FreeThrowsMade", "Points", "Turnovers"]
  # Make sure all the columns in the features list exist in the DataFrame
  features = [col for col in features if col in df.columns]

  # Split the data into training and testing sets
  # X_train, X_test, y_train, y_test = train_test_split(df[features], test_size=0.25, random_state=42)

  X_train, X_test, y_train, y_test = train_test_split(df[features], df[features], test_size=0.25, random_state=42, train_size=.75)

  # Train a Random Forest Regressor model on the training data
  model = LinearRegression()
  model.fit(X_train, y_train)

  # Evaluate the model on the testing data
  score = model.score(X_test, y_test)
  print(f"Model score: {score:.2f}")

  return model

def generate_picks(model, games, features):
  """Generates picks for the given games using the given model"""
  picks = []

  for game in games:
    players = game["players"]

    # Use the model to predict the fantasy points for each player
    predictions = model.predict(players[features])

    # Select the player with the highest predicted fantasy points
    top_picks = players[predictions.argsort()[-6:][::-1]]
    picks.extend(top_picks)

  return picks

def make_picks(picks):
  """Makes the given picks on the PrizePicks website"""
  # TODO: Implement this function
  pass

# Collect data on player performance
player_data = collect_player_data()

# Use machine learning to analyze the data and create a model for predicting player performance
model = create_player_performance_model(player_data)


问:
Optimal schema to store ordered list of different objects types in postgres (or recommend another DB solution)?
relatively new to system design so looking for some advice on a project.In summary, I want to create a view of data which is comprised of an ordered list of different object types.

In this example I am building an activity page that multiple users will be sharing and adding/removing/etc. different activities (new activity pages can be created too). Each type of activity is rigid in its data model so I would like to keep them in their own tables i.e. a table for restaurants, a separate table for dance_venues, a separate table for hikes. However a user can add any of these activity types to the shared activity page.

For example I login to view activity page 1 and I see a page like

Activity Page 1

9am - Starbucks

location

open hours

Park Hike

length

difficulty

Outback steakhouse

location

open hours

Karaoke

hours

cost

21+

The list of activities could theoretically be represented by a linked list where each node is its own type but I am unsure of how to optimal store this in postgres.

Any and all advice is appreciated!

Some possible solutions I am considering.

Have an activity table that has a column for every possible foreign key type (or every possible type of activity) where in practice only one column would over be filled which is the one I would use to query for the activity itself.

activity_page
restaurant_key
dance_venues_key

activity page1
rest key

activity page1

dance key

activity page2

dance key

This is not ideal as I have no idea how many activity types there will be (and new ones will always be added) and I have to do some ugly query manipulation to only get one activity back per activity_page row

Denormalize and store the entire activity page as JSONB col. This has the obvious trade off that I am losing a single source of truth for these activity types and it will be basically impossible to manage the activity JSONB column with 100% fidelity but it is cleaner in a sense and helps in the cases of users trying to change the order of different activities on an activity page at the same time (and does not require additional queries to fetch the related objects). If I am doing this I might as well use a no-sql solution (see below). I am also unclear on the size limitation of JSONB

2.5 Denormalize and store the activity page JSON data in no-sql document solution like firebase/firestore where activates are read/copied from the postgres tables and added to the activity page documents in firestore. However I don't have much experience in pub/sub or subscribing to updates to the firestore documents if someone could comment on how easy or hard it is to have multiple users making changes to the same document.

Somehow store the type of foreign key that is at each node in the list. I have tried researching if this is possible in Postgres but have not found anything that promising. Something like

activity_page
foreign_key
foreign_table

activity page1
key
table

activity page1
key
table

activity page2
key
table

This seems the cleanest if it's possible but I am not sure how to accomplish it.

Other notes:

I am using a graphql yoga server side

I don't expect each activity page's list to exceed 100 activities


问:
Stimulus does not identify outlets in Rails 7 app
In a Rails 7 app, clicking an icon toggles the display property of a form. Both HTML elements connect properly to their respective controllers (toggler and togglee). The form (togglee) is an outlet of the icon (toggler).
The problem: The toggler controller does not recognize the togglee outlet. The five outlet properties (e.g. this.toggleeOutlets) remain undefined.

HTML:

toggler#handleClick" title="Asset Filter">

and below

```<code><div id="filter-form" style="display:none" data-controller="togglee">
  ...
/div>
</code>```

Controllers:

```<code>\\ toggler_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static outlets = [ "togglee" ]

  connect() {
    console.log("Toggler controller connected")
  }

  handleClick(event) {
    console.log("toggler controller: handleClick")
    event.preventDefault();

    console.log("outlet controllers:", this.toggleeOutlets)
    ...
  }
}

</code>```
```<code>\\ togglee_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    console.log("Togglee controller connected")
  }
}
</code>```

Console output shows the controllers connect, and react to the click:

```<code>Toggler controller connected
Togglee controller connected
toggler controller: handleClick
outlet controllers: undefined
</code>```

...but the outlet-related properties (such as this.toggleeOutlets) are undefined.

What's wrong?

(BTW - I confirmed that the selector string #filter-form identifies the div element correctly)

Versions:

rails (7.0.1)
stimulus-rails (1.2.1)
turbo-rails (1.3.2)

Body:
In a Rails 7 app, clicking an icon toggles the display property of a form. Both HTML elements connect properly to their respective controllers (toggler and togglee). The form (togglee) is an outlet of the icon (toggler).
The problem: The toggler controller does not recognize the togglee outlet. The five outlet properties (e.g. this.toggleeOutlets) remain undefined.

HTML:

toggler#handleClick" title="Asset Filter">

and below

  ...
/div>

Controllers:

\\ toggler_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static outlets = [ "togglee" ]

  connect() {
    console.log("Toggler controller connected")
  }

  handleClick(event) {
    console.log("toggler controller: handleClick")
    event.preventDefault();

    console.log("outlet controllers:", this.toggleeOutlets)
    ...
  }
}

\\ togglee_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    console.log("Togglee controller connected")
  }
}

Console output shows the controllers connect, and react to the click:

Toggler controller connected
Togglee controller connected
toggler controller: handleClick
outlet controllers: undefined

...but the outlet-related properties (such as this.toggleeOutlets) are undefined.

What's wrong?

(BTW - I confirmed that the selector string #filter-form identifies the div element correctly)

Versions:

rails (7.0.1)
stimulus-rails (1.2.1)
turbo-rails (1.3.2)


问:
What is wrong with my binary search python code?
Exercise 1: “Search and Destroy... But Nicer”

As a web developer working for a retail store, your job is to create a website where the store can sell its products online. Your first task is to create a search option for the customers, so they can easily find specific items they are looking for in your shop.

Each item in your shop corresponds to a specific 4-digit code. Starting with a pre-defined list, perform both searching algorithms (Linear and Binary) to find your items. Ask the user to input an item (using a number code) and your program should output if the code was able to find your item in the list.

The predefined list should contain the following values in this order:
4599, 3102, 1024, 9980, 2912, 1569, 4205, 9811, 1001, 7638, 4733, 1989, 5555, 5000, 3861

So this is my code for binary.

```<code>def binary_search(item_list,code):
  start = 0
  end = len(item_list)-1
  if start >= end: #check base case
    mid = int((start + end) / 2)
    if item_list[mid] == code:
      return mid
    if item_list[mid] > code:
      end = mid + 1
    if item_list[mid] < code:
      start = mid - 1
  else:
    return -1
</code>```

I tried running it but it will not really determine. It will just always say they found it for every numbers I enter even though it's not on the list. I actually tried anything but the results would be either found for all numbers or not found for all numbers. For more context, this is my entire code:

```<code>print ("WELCOME TO OUR SHOP")
print ("-------------------")
# Linear search function
def linear_search(code, item_list):
  for i in range(len(item_list)):
    if item_list[i] == code:
      return True
  return False

# Binary search function
def binary_search(item_list,code):
  start = 0
  end = len(item_list)-1
  if start >= end: #check base case
    mid = int((start + end) / 2)
    if item_list[mid] == code:
      return mid
    elif item_list[mid] > code:
      end = mid + 1
    else:
      start = mid - 1
  else:
    return -1

# Predefined list of items
item_list = [4599, 3102, 1024, 9980, 2912, 1569, 4205, 9811, 1001, 7638, 4733, 1989, 5555, 5000, 3861]

#ask user to input an item code
code = int(input("Find an item: \n"))

# Use linear search to find the item
result = linear_search(code, item_list)

print("\nLinear Search")
print("searching...\n")
if result:
  print("The Item",code,"was found.")
else:
  print("The Item",code,"was not found.")

# Use binary search to find the item
result = binary_search(item_list, code)

print("\nBinary Search")
print("searching...\n")
if result:
  print("The Item",code,"was found.")
else:
  print("The Item",code,"was not found.")
</code>```

Body:
Exercise 1: “Search and Destroy... But Nicer”

As a web developer working for a retail store, your job is to create a website where the store can sell its products online. Your first task is to create a search option for the customers, so they can easily find specific items they are looking for in your shop.

Each item in your shop corresponds to a specific 4-digit code. Starting with a pre-defined list, perform both searching algorithms (Linear and Binary) to find your items. Ask the user to input an item (using a number code) and your program should output if the code was able to find your item in the list.

The predefined list should contain the following values in this order:
4599, 3102, 1024, 9980, 2912, 1569, 4205, 9811, 1001, 7638, 4733, 1989, 5555, 5000, 3861

So this is my code for binary.

def binary_search(item_list,code):
  start = 0
  end = len(item_list)-1
  if start >= end: #check base case
    mid = int((start + end) / 2)
    if item_list[mid] == code:
      return mid
    if item_list[mid] > code:
      end = mid + 1
    if item_list[mid] < code:
      start = mid - 1
  else:
    return -1

I tried running it but it will not really determine. It will just always say they found it for every numbers I enter even though it's not on the list. I actually tried anything but the results would be either found for all numbers or not found for all numbers. For more context, this is my entire code:

print ("WELCOME TO OUR SHOP")
print ("-------------------")
# Linear search function
def linear_search(code, item_list):
  for i in range(len(item_list)):
    if item_list[i] == code:
      return True
  return False

# Binary search function
def binary_search(item_list,code):
  start = 0
  end = len(item_list)-1
  if start >= end: #check base case
    mid = int((start + end) / 2)
    if item_list[mid] == code:
      return mid
    elif item_list[mid] > code:
      end = mid + 1
    else:
      start = mid - 1
  else:
    return -1

# Predefined list of items
item_list = [4599, 3102, 1024, 9980, 2912, 1569, 4205, 9811, 1001, 7638, 4733, 1989, 5555, 5000, 3861]

#ask user to input an item code
code = int(input("Find an item: \n"))

# Use linear search to find the item
result = linear_search(code, item_list)

print("\nLinear Search")
print("searching...\n")
if result:
  print("The Item",code,"was found.")
else:
  print("The Item",code,"was not found.")

# Use binary search to find the item
result = binary_search(item_list, code)

print("\nBinary Search")
print("searching...\n")
if result:
  print("The Item",code,"was found.")
else:
  print("The Item",code,"was not found.")


问:
addEventListener does not work if there is another addEventListener of a non-existent html element before it
With @Don't Panic's suggestions, which I thank very much, I did various other tests and realized that the problem is reducible to the following:

In the same view I've a form (#form-create-comment) and a button (#btn-test) both linked with related addEventListeners included in the script tag.

```<code><form id="form-create-comment" class="mb-5" action="/comment/store" method="POST">
    <!-- Submit -->
    <button type="submit" class="btn btn-primary">Post Comment</button>
</form>

<button id="btn-test" class="btn btn-success">Button Test</button>

<script>
    document.getElementById('form-create-comment').addEventListener('submit', function() {
        alert('form-create-comment');
    });

    document.querySelector('#btn-test').addEventListener('click', function(){
        alert('#btn-test');
    });
</script>
</code>```

In this way all works but if I delete the button (#btn-test), the addEventListener of the form doesn't works unless this one in the script tag comes before the other addEventListner (#btn-test).

The same to the opposite: if I delete the form, in the scripti tag the addEventListener of the button (#btn-test) must comes before the other addEventListener (#form-create-comment).

This happened because it can't exist an addEventListener without without its reference html element or is there another explanation?

Body:
With @Don't Panic's suggestions, which I thank very much, I did various other tests and realized that the problem is reducible to the following:

In the same view I've a form (#form-create-comment) and a button (#btn-test) both linked with related addEventListeners included in the script tag.

<form id="form-create-comment" class="mb-5" action="/comment/store" method="POST">

    <button type="submit" class="btn btn-primary">Post Comment</button>
</form>

<button id="btn-test" class="btn btn-success">Button Test</button>

In this way all works but if I delete the button (#btn-test), the addEventListener of the form doesn't works unless this one in the script tag comes before the other addEventListner (#btn-test).

The same to the opposite: if I delete the form, in the scripti tag the addEventListener of the button (#btn-test) must comes before the other addEventListener (#form-create-comment).

This happened because it can't exist an addEventListener without without its reference html element or is there another explanation?


问:
I have an issue in pine editor on tradingview. This is the error I'm getting: Mismatched input 'end of line without line continuation' expecting ')'
```<code>fibonacci(close, length) =>
    result = array.new<float>(1, 1)
    array.set(result, 0, close)  // Set the first element of the 'result' array to 'close'
    for i = 2 to length - 1
        next = sum(result[i-1]) + sum(result[i-2])
        array.set(result, i, next)
    ret = object.new(
        ret_0_0=result[0] / result[length - 1],
        ret_23_6=result[1] / result[length - 1],
        ret_38_2=result[2] / result[length - 1],
        ret_50_0=result[3] / result[length - 1],
        ret_61_8=result[4] / result[length - 1],
        ret_100_0=result[length - 1] / result[0]
        )

fibRet = fibonacci(close, length)

// Long entry
if close > upper
    strategy.entry("Long", strategy.long, stop = fibRet.ret_61_8, limit = fibRet.ret_100_0)

/ Short entry
if close < lower
    strategy.entry("Short", strategy.short, stop = fibRet.ret_61_8, limit = fibRet.ret_0_0)

// Exit
strategy.exit("Exit", "Long", stop = fibRet.ret_38_2)
strategy.exit("Exit", "Short", stop = fibRet.ret_61_8)
</code>```

I am having a problem with object.new() in the fibonacci function.  I can't figure out for the life of me what's wrong. This is the error I'm getting: Mismatched input 'end of line without line continuation' expecting ')'

Body:
fibonacci(close, length) =>
    result = array.new<float>(1, 1)
    array.set(result, 0, close)  // Set the first element of the 'result' array to 'close'
    for i = 2 to length - 1
        next = sum(result[i-1]) + sum(result[i-2])
        array.set(result, i, next)
    ret = object.new(
        ret_0_0=result[0] / result[length - 1],
        ret_23_6=result[1] / result[length - 1],
        ret_38_2=result[2] / result[length - 1],
        ret_50_0=result[3] / result[length - 1],
        ret_61_8=result[4] / result[length - 1],
        ret_100_0=result[length - 1] / result[0]
        )

fibRet = fibonacci(close, length)

// Long entry
if close > upper
    strategy.entry("Long", strategy.long, stop = fibRet.ret_61_8, limit = fibRet.ret_100_0)

/ Short entry
if close < lower
    strategy.entry("Short", strategy.short, stop = fibRet.ret_61_8, limit = fibRet.ret_0_0)

// Exit
strategy.exit("Exit", "Long", stop = fibRet.ret_38_2)
strategy.exit("Exit", "Short", stop = fibRet.ret_61_8)

I am having a problem with object.new() in the fibonacci function.  I can't figure out for the life of me what's wrong. This is the error I'm getting: Mismatched input 'end of line without line continuation' expecting ')'


问:
Refetch data from API if status is complete in reactjs
A single API endpoint is returning the timestamp for a scheduled or live event. So the countdown could be the remaining time for an event or its ending time for the live event.

If it's a scheduled event, API is returning the remaining time, but if the event is already started then it's the end_time of the event.

What I am expecting is that if it's a scheduled event then as soon remaining time ends then the state should update with the event end_time countdown.

I am using jotai to maintain the state.

atoms.js

```<code>import { atom } from 'jotai';

export const startTimeAtom = atom('');
export const isEventActiveAtom = atom(false)
</code>```

EventBlock.js

```<code>import { startTimeAtom, isEventActiveAtom } from '../../atoms';

const EventBlock = () => {
    const [startTime, setStartTime] = useAtom(startTimeAtom);
    const [isEventActive] = useAtom(isEventActiveAtom);

    useEffect(() => {
        // api feting data and updating state
        // ...
        setStartTime(toLocalDateTime(dataStartTime, dataTimeZone))
        //...
    }, [isEventActive]);

    const handleStatus = ({completed}) => {}

    return (
        <div>
            <Counter
                id={id}
                counterEndTime={startTime}
                status={eventStatus}
                handleStatus={handleStatus}
            />
    );
}

export default EventBlock;
</code>```

and last part is

Counter.js

```<code>import React from 'react';
import Countdown from "react-countdown";
import { useAtom } from 'jotai';
import { startTimeAtom, isAuctionActiveAtom } from "../../atoms";

const Counter = ({ id, counterEndTime, status, handleStatus }) => {

    const [startTime]  = useAtom(startTimeAtom);
    const [isEventActive, setIsEventActive] = useAtom(isEventActiveAtom);

    const Completionist = ({ id, status }) => {
        return 'Event ended';
    };

    // Renderer callback with condition
    const handleRenderer = ({ completed, formatted }) => {
        if ( completed ) {
            if ( status !== 'expired' || status !== 'live' ) {
                setIsEventActive(true);
            } else {
                return <Completionist id={id} status={status} />;
            }
        } else {
            return Object.keys(formatted).map((key) => (
                <div key={`${key}`} className={`countDown bordered ${key}-box`}>
                    <span className={`num item ${key}`}>{formatted[key]}</span>
                    <span>{key}</span>
                </div>
            ))
        }
    };

    return (
        <div className="EventCounterContainer">
            <div className="EventCounterInner">
                <Countdown
                    id="Event"
                    date={counterEndTime}
                    renderer={handleRenderer}
                    intervalDelay={0}
                    precision={0}
                    onComplete={(e)=>handleStatus(e)}
                />
            </div>
        </div>
    );
};

export default Counter;
</code>```

Body:
A single API endpoint is returning the timestamp for a scheduled or live event. So the countdown could be the remaining time for an event or its ending time for the live event.

If it's a scheduled event, API is returning the remaining time, but if the event is already started then it's the end_time of the event.

What I am expecting is that if it's a scheduled event then as soon remaining time ends then the state should update with the event end_time countdown.

I am using jotai to maintain the state.

atoms.js

import { atom } from 'jotai';

export const startTimeAtom = atom('');
export const isEventActiveAtom = atom(false)

EventBlock.js

import { startTimeAtom, isEventActiveAtom } from '../../atoms';

const EventBlock = () => {
    const [startTime, setStartTime] = useAtom(startTimeAtom);
    const [isEventActive] = useAtom(isEventActiveAtom);

    useEffect(() => {
        // api feting data and updating state
        // ...
        setStartTime(toLocalDateTime(dataStartTime, dataTimeZone))
        //...
    }, [isEventActive]);

    const handleStatus = ({completed}) => {}

    return (

            <Counter
                id={id}
                counterEndTime={startTime}
                status={eventStatus}
                handleStatus={handleStatus}
            />
    );
}

export default EventBlock;

and last part is

Counter.js

import React from 'react';
import Countdown from "react-countdown";
import { useAtom } from 'jotai';
import { startTimeAtom, isAuctionActiveAtom } from "../../atoms";

const Counter = ({ id, counterEndTime, status, handleStatus }) => {

    const [startTime]  = useAtom(startTimeAtom);
    const [isEventActive, setIsEventActive] = useAtom(isEventActiveAtom);

    const Completionist = ({ id, status }) => {
        return 'Event ended';
    };

    // Renderer callback with condition
    const handleRenderer = ({ completed, formatted }) => {
        if ( completed ) {
            if ( status !== 'expired' || status !== 'live' ) {
                setIsEventActive(true);
            } else {
                return <Completionist id={id} status={status} />;
            }
        } else {
            return Object.keys(formatted).map((key) => (
                <div key={`${key}`} className={`countDown bordered ${key}-box`}>
                    <span className={`num item ${key}`}>{formatted[key]}
                    {key}

            ))
        }
    };

    return (

                <Countdown
                    id="Event"
                    date={counterEndTime}
                    renderer={handleRenderer}
                    intervalDelay={0}
                    precision={0}
                    onComplete={(e)=>handleStatus(e)}
                />

    );
};

export default Counter;