问:
Multiple APEX_PUBLIC_USER sessions

I have an ORACLE database and ORACLE APEX 5.1 is installed there.
It has worked well in previous days.
In recent days, the server has crashed due to many sessions generated by the user APEX_PUBLIC_USER.

Seeing the current statement, this:

```<code>/* Formatted on 30/12/2022 05:19:20 p. m. (QP5 v5.336) */
DECLARE
    rc__             NUMBER;
    simple_list__    OWA_UTIL.vc_arr;
    complex_list__   OWA_UTIL.vc_arr;
BEGIN
    OWA.init_cgi_env ( :n__, :nm__, :v__);
    HTP.HTBUF_LEN := 63;
    NULL;
    NULL;
    simple_list__ (1) := 'sys.%';
    simple_list__ (2) := 'dbms\_%';
    simple_list__ (3) := 'utl\_%';
    simple_list__ (4) := 'owa\_%';
    simple_list__ (5) := 'owa.%';
    simple_list__ (6) := 'htp.%';
    simple_list__ (7) := 'htf.%';
    simple_list__ (8) := 'wpg_docload.%';
    simple_list__ (9) := 'ctxsys.%';
    simple_list__ (10) := 'mdsys.%';

    IF (   (wwv_flow_epg_include_modules.authorize ('wwv_flow.ajax') = FALSE)
        OR (owa_match.match_pattern (p_string              => 'wwv_flow.ajax'/* */
                                                                             ,
                                     p_simple_pattern      => simple_list__,
                                     p_complex_pattern     => complex_list__,
                                     p_use_special_chars   => FALSE)))
    THEN
        rc__ := 2;
    ELSE
        NULL;
        NULL;
        wwv_flow.ajax (p_flow_id        => :p_flow_id,
                       p_flow_step_id   => :p_flow_step_id,
                       p_instance       => :p_instance,
                       p_debug          => :p_debug,
                       p_request        => :p_request,
                       p_json           => :p_json);

        IF (WPG_DOCLOAD.is_file_download)
        THEN
            rc__ := 1;
            WPG_DOCLOAD.get_download_file ( :doc_info);
            NULL;
            NULL;
            NULL;
            COMMIT;
        ELSE
            rc__ := 0;
            NULL;
            NULL;
            NULL;
            COMMIT;
            OWA.get_page ( :data__, :ndata__);
        END IF;
    END IF;

    :rc__ := rc__;
END;
</code>```

I delete the sessions and they are recreated.

What solution could it be?
Migrate from DB?
New version of APEX?

Title: Multiple APEX_PUBLIC_USER sessions

Body:
I have an ORACLE database and ORACLE APEX 5.1 is installed there.
It has worked well in previous days.
In recent days, the server has crashed due to many sessions generated by the user APEX_PUBLIC_USER.

Seeing the current statement, this:

/* Formatted on 30/12/2022 05:19:20 p. m. (QP5 v5.336) */
DECLARE
    rc__             NUMBER;
    simple_list__    OWA_UTIL.vc_arr;
    complex_list__   OWA_UTIL.vc_arr;
BEGIN
    OWA.init_cgi_env ( :n__, :nm__, :v__);
    HTP.HTBUF_LEN := 63;
    NULL;
    NULL;
    simple_list__ (1) := 'sys.%';
    simple_list__ (2) := 'dbms\_%';
    simple_list__ (3) := 'utl\_%';
    simple_list__ (4) := 'owa\_%';
    simple_list__ (5) := 'owa.%';
    simple_list__ (6) := 'htp.%';
    simple_list__ (7) := 'htf.%';
    simple_list__ (8) := 'wpg_docload.%';
    simple_list__ (9) := 'ctxsys.%';
    simple_list__ (10) := 'mdsys.%';

    IF (   (wwv_flow_epg_include_modules.authorize ('wwv_flow.ajax') = FALSE)
        OR (owa_match.match_pattern (p_string              => 'wwv_flow.ajax'/* */
                                                                             ,
                                     p_simple_pattern      => simple_list__,
                                     p_complex_pattern     => complex_list__,
                                     p_use_special_chars   => FALSE)))
    THEN
        rc__ := 2;
    ELSE
        NULL;
        NULL;
        wwv_flow.ajax (p_flow_id        => :p_flow_id,
                       p_flow_step_id   => :p_flow_step_id,
                       p_instance       => :p_instance,
                       p_debug          => :p_debug,
                       p_request        => :p_request,
                       p_json           => :p_json);

        IF (WPG_DOCLOAD.is_file_download)
        THEN
            rc__ := 1;
            WPG_DOCLOAD.get_download_file ( :doc_info);
            NULL;
            NULL;
            NULL;
            COMMIT;
        ELSE
            rc__ := 0;
            NULL;
            NULL;
            NULL;
            COMMIT;
            OWA.get_page ( :data__, :ndata__);
        END IF;
    END IF;

    :rc__ := rc__;
END;

I delete the sessions and they are recreated.

What solution could it be?
Migrate from DB?
New version of APEX?


来源: stackexchange

问:
Docker compose unsupported option 'target'
I am developing a nest js application and I need to deploy it to a remote server with ubuntu, i'm new with docker and everything is fine on windows 8 and ubuntu 22 i can use my app fine but on server i get this error

enter image description here error in the server

in using this docker files

enter image description here Dockerfile

enter image description here docker-compose

On my windows and ubuntu works docker-compose up dev and docker-compose up prod. It seems weird that it works on two different systems but not on the server, they all have the same version of docker and docker-compose

I try to change the version in the yml, but the error persists.

ContentLicense: CC BY-SA 4.0


问:
credentials webview2 in VB.Net
I try to insert a authentification in webview2, but I have a error in my code.

The error is at the AddHandler WebAccount.CoreWebView2.BasicAuthenticationRequested :

System.NullReferenceException : 'Object reference not set to an instance of an object.'

Here my code:

```<code>Class MainWindow
Private Site As String = "https://test.fr"
Private HTTPS_LoginOne As String = "admin"
Private HTTPS_PwdOne As String = "1234567"
Public Event BasicAuthenticationRequested As EventHandler(Of CoreWebView2BasicAuthenticationRequestedEventArgs)

Public Sub New()

    InitializeComponent()

    InitWeb()

    AddHandler WebAccount.CoreWebView2.BasicAuthenticationRequested, AddressOf Authentweb

End Sub

Private Sub Authentweb(sender As Object, e As CoreWebView2BasicAuthenticationRequestedEventArgs)
    e.Response.UserName = HTTPS_LoginOne
    e.Response.Password = HTTPS_PwdOne
End Sub

Async Sub InitWeb()
    Await WebAccount.EnsureCoreWebView2Async()
    WebAccount.CoreWebView2.Navigate(Site)
End Sub
</code>```

Someone have any idea ?

Title: credentials webview2 in VB.Net

Body:
I try to insert a authentification in webview2, but I have a error in my code.

The error is at the AddHandler WebAccount.CoreWebView2.BasicAuthenticationRequested :

System.NullReferenceException : 'Object reference not set to an instance of an object.'

Here my code:

Class MainWindow
Private Site As String = "https://test.fr"
Private HTTPS_LoginOne As String = "admin"
Private HTTPS_PwdOne As String = "1234567"
Public Event BasicAuthenticationRequested As EventHandler(Of CoreWebView2BasicAuthenticationRequestedEventArgs)

Public Sub New()

    InitializeComponent()

    InitWeb()

    AddHandler WebAccount.CoreWebView2.BasicAuthenticationRequested, AddressOf Authentweb

End Sub

Private Sub Authentweb(sender As Object, e As CoreWebView2BasicAuthenticationRequestedEventArgs)
    e.Response.UserName = HTTPS_LoginOne
    e.Response.Password = HTTPS_PwdOne
End Sub

Async Sub InitWeb()
    Await WebAccount.EnsureCoreWebView2Async()
    WebAccount.CoreWebView2.Navigate(Site)
End Sub

Someone have any idea ?


问:
Plotly interactive plot python: How to change text by changing the dropdown?
The line graph with the dropdown button can select the data by different district to show.

However, I would like to add the text on the left-bottom corner of the  plot to show the value (input_df5), and there is only one way that I tried that is work, which is fig.add_annotation.

Unfortunately, add_annotation() will show all texts on the screen instead of showing it by the selection on the button.

I would like to ask about how to show the text by the dropdown button that I selected?

The output of my code: (the black long line is the text that I would like to show)

This is the image of my output

My code:

```<code>def interactive_multi_plot_test(input_df, input_df2, input_df3, input_df4, input_df5, title, addAll = True):
    fig = go.Figure()
    for column in input_df.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df.index, y = input_df[column], line=dict(color='#0000ff')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df.columns.isin(input_df.columns),'title': 'All','showlegend':False}])

    for column in input_df2.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df2.index, y = input_df2[column], line=dict(color='red')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df2.columns.isin(input_df2.columns),'title': 'All','showlegend':False}])

    for column in input_df3.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df3.index, y = input_df3[column], line=dict(color='red')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df3.columns.isin(input_df3.columns),'title': 'All','showlegend':False}])

    for column in input_df4.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df4.index, y = input_df4[column], line=dict(color='green', dash='dash'), hoverinfo='none'))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df4.columns.isin(input_df4.columns),'title': 'All','showlegend':False}])

    for column in input_df5.columns.to_list():
        fig.add_annotation(text="Different between 2019 to 2022: " + str(input_df5[column][0]),
                  xref="paper", yref="paper",
                  x=1, y=0.2, showarrow=False)

  #  for column in input_df5.columns.to_list():
     #   fig.add_trace(go.Scatter(x = input_df3.index[2:5],y = input_df3[column],name=str(input_df5[column][0]),marker_color="#2457BD"))

#        fig.add_vline(x = input_df[input_df[column] == max(input_df[column])].index[0], line_width=3, line_dash="dash", line_color="green")

    fig.layout.plot_bgcolor = '#ffffff'
    fig.layout.yaxis.gridcolor = '#000000'
    fig.layout.xaxis.gridcolor = '#000000'
    # Update remaining layout properties
    fig.update_layout(
        title_text=title,
        height=600,
        font = dict(color='#000', size=12)
    )

    fig.update_layout(
        updatemenus=[go.layout.Updatemenu(
            active = 0,
            buttons =  ([button_all] * addAll) + list(input_df.columns.map(lambda column: dict(label = column,
                    method = 'update',
                    args = [{'visible': input_df.columns.isin([column]),
                             'title': column,
                             'showlegend': False}]))))])

    return(fig)
</code>```

I expect the text(annotation) will follow my selection on the dropdown button.

I tired to create a short line on the graph and always show that one hovertext, but it seems not a good format for visualize the data, and I didn't completely test it yet

Body:
The line graph with the dropdown button can select the data by different district to show.

However, I would like to add the text on the left-bottom corner of the  plot to show the value (input_df5), and there is only one way that I tried that is work, which is fig.add_annotation.

Unfortunately, add_annotation() will show all texts on the screen instead of showing it by the selection on the button.

I would like to ask about how to show the text by the dropdown button that I selected?

The output of my code: (the black long line is the text that I would like to show)

This is the image of my output

My code:

def interactive_multi_plot_test(input_df, input_df2, input_df3, input_df4, input_df5, title, addAll = True):
    fig = go.Figure()
    for column in input_df.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df.index, y = input_df[column], line=dict(color='#0000ff')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df.columns.isin(input_df.columns),'title': 'All','showlegend':False}])

    for column in input_df2.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df2.index, y = input_df2[column], line=dict(color='red')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df2.columns.isin(input_df2.columns),'title': 'All','showlegend':False}])

    for column in input_df3.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df3.index, y = input_df3[column], line=dict(color='red')))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df3.columns.isin(input_df3.columns),'title': 'All','showlegend':False}])

    for column in input_df4.columns.to_list():
        fig.add_trace(go.Scatter(x = input_df4.index, y = input_df4[column], line=dict(color='green', dash='dash'), hoverinfo='none'))
    button_all = dict(label = 'Select Data: ',method = 'update',args = [{'visible': ~input_df4.columns.isin(input_df4.columns),'title': 'All','showlegend':False}])

    for column in input_df5.columns.to_list():
        fig.add_annotation(text="Different between 2019 to 2022: " + str(input_df5[column][0]),
                  xref="paper", yref="paper",
                  x=1, y=0.2, showarrow=False)

  #  for column in input_df5.columns.to_list():
     #   fig.add_trace(go.Scatter(x = input_df3.index[2:5],y = input_df3[column],name=str(input_df5[column][0]),marker_color="#2457BD"))

#        fig.add_vline(x = input_df[input_df[column] == max(input_df[column])].index[0], line_width=3, line_dash="dash", line_color="green")

    fig.layout.plot_bgcolor = '#ffffff'
    fig.layout.yaxis.gridcolor = '#000000'
    fig.layout.xaxis.gridcolor = '#000000'
    # Update remaining layout properties
    fig.update_layout(
        title_text=title,
        height=600,
        font = dict(color='#000', size=12)
    )

    fig.update_layout(
        updatemenus=[go.layout.Updatemenu(
            active = 0,
            buttons =  ([button_all] * addAll) + list(input_df.columns.map(lambda column: dict(label = column,
                    method = 'update',
                    args = [{'visible': input_df.columns.isin([column]),
                             'title': column,
                             'showlegend': False}]))))])

    return(fig)

I expect the text(annotation) will follow my selection on the dropdown button.

I tired to create a short line on the graph and always show that one hovertext, but it seems not a good format for visualize the data, and I didn't completely test it yet


问:
MaminGL OpenGL err = 1280 (Invalid Enum) - Animated Plane with Texture
I'm getting invalid enum error using maningl.

I have created an animated wave with video as texture.

Code works well with a  short animation of around 5 seconds.
This is the result:
But with more than 10 seconds it throws invalid enum error

Animation length is controlled with method self.wait in PinkyWaving class.

Wave with video as texture

The error:

```<code>  self.construct()
  File "pinky_waving.py", line 119, in construct
    self.wait(10)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 417, in wrapper
    func(self, *args, **kwargs)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 508, in wait
    self.emit_frame()
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 179, in emit_frame
    self.file_writer.write_frame(self.camera)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene_file_writer.py", line 238, in write_frame
    raw_bytes = camera.get_raw_fbo_data()
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\camera\camera.py", line 294, in get_raw_fbo_data
    gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, self.fbo_msaa.glo)
  File "src/errorchecker.pyx", line 58, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError
OpenGL.error.GLError: GLError(
        err = 1280,
        description = b'numeraci\xf3n no v\xe1lida',
        baseOperation = glBindFramebuffer,
        cArguments = (GL_READ_FRAMEBUFFER, 2)
)
</code>```

I'm using Python 3.8, ManimGL v1.5.0 and moderngl version: 5.7.2.

Where animation is made pinky.py.

```<code>from manimlib import *

VIDEO_FRAMES  = 'pinky_60fps-opencv'
TEXTURES = os.listdir(VIDEO_FRAMES)
N = len(TEXTURES)
FRAME_INDEX = 0

class TexturedPlaneWavingVideo(TexturedSurface):
    CONFIG = {
        'waving_plane_config':
            {
            "u_range": (-5*2,5*2),
            "v_range": (-5*2,5*2),
            "resolution": (32,32),
            "color": BLUE_E,
            "opacity": 0.85,
            }
    }
    def __init__(self, phi=0, height_factor=1.0, d=1.0, alpha=0.1,scale_factor = 0.5, init_frame= None,**kwargs):
        """
        init_frame: str
            frame used as texture
        """
        digest_config(self,self.CONFIG)
        self.init_frame = init_frame

        # Parameters
        # heigth of wave
        self.height_factor = height_factor
        self.d = d
        self.alpha = alpha
        self.phi = phi
        #overall scale of plane
        self.scale_factor = scale_factor

        # Initialize as a plane
        surface = ParametricSurface(
            uv_func = self.wave_func,
            **self.waving_plane_config).scale(self.scale_factor)

        self.surface = surface

        super().__init__(uv_surface= surface,
            image_file = os.path.join(VIDEO_FRAMES,self.init_frame))

    def update_wave(self,dt):
        self.phi += 4*dt
        global FRAME_INDEX
        FRAME_INDEX= (FRAME_INDEX+1)%N

        texture = TEXTURES[FRAME_INDEX]
        texture_path =os.path.join(VIDEO_FRAMES, TEXTURES[FRAME_INDEX])

        # Create a new TexturedPlaneWavingVideo
        plane = TexturedPlaneWavingVideo(
            phi=self.phi, height_factor=self.height_factor, d=self.d ,alpha=self.alpha,scale_factor = self.scale_factor, init_frame=texture )

        self.init_frame = texture

        self.texture_paths = {
            "LightTexture": get_full_raster_image_path(texture_path),
            "DarkTexture": get_full_raster_image_path(texture_path),}

        self.become(plane)

        self.init_shader_data()

    def plane_func(self,u,v):
        return np.array([
            u,
            v,
            0])

    def wave_func(self, u, v):

        return (u,
                v,
                np.sin((np.sqrt(u**2/self.d + v ** 2 / self.d) + self.phi)) * self.height_factor + self.alpha)

    def wave_func_np(self,u,v):
        return  np.array(
            [u,
             v,
             np.sin( (np.sqrt(u**2/self.d + v ** 2 / self.d ) + self.phi) ) * self.height_factor + self.alpha])

    def waving(self,speed = 1):
        """
        speed: float
            speed of waving animation
        """
        self.add_updater(lambda m,dt:self.update_wave(dt*speed)  )

    def stop_waving(self):
        self.clear_updaters()

class PinkyWaving(ThreeDScene):
    def construct(self):
        p = TexturedPlaneWavingVideo(phi=0, height_factor=3.0, d=1.0, alpha=0.1,scale_factor = 0.5,init_frame="frame0-00-00.00.jpg")

        self.play(ShowCreation(p))

        p.waving()

        self.wait(10)
</code>```

Download an extract the images to reproduce the error:  https://drive.google.com/file/d/1_kUcDP5D4-7LXi7bbpnjdobl4ajHTOMr/view?usp=sharing

Run the command manimgl pinky.py PinkyWaving -w

Each texture_path is a path to a jpg image.

I expected to produce an animation with the full video, 2 minutes, but if the animation passes the 10 seconds it throws Invalid enum.

Body:
I'm getting invalid enum error using maningl.

I have created an animated wave with video as texture.

Code works well with a  short animation of around 5 seconds.
This is the result:
But with more than 10 seconds it throws invalid enum error

Animation length is controlled with method self.wait in PinkyWaving class.

Wave with video as texture

The error:

  self.construct()
  File "pinky_waving.py", line 119, in construct
    self.wait(10)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 417, in wrapper
    func(self, *args, **kwargs)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 508, in wait
    self.emit_frame()
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene.py", line 179, in emit_frame
    self.file_writer.write_frame(self.camera)
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\scene\scene_file_writer.py", line 238, in write_frame
    raw_bytes = camera.get_raw_fbo_data()
  File "f:\instalaciones\anaconda\envs\manim2\lib\site-packages\manimlib\camera\camera.py", line 294, in get_raw_fbo_data
    gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, self.fbo_msaa.glo)
  File "src/errorchecker.pyx", line 58, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError
OpenGL.error.GLError: GLError(
        err = 1280,
        description = b'numeraci\xf3n no v\xe1lida',
        baseOperation = glBindFramebuffer,
        cArguments = (GL_READ_FRAMEBUFFER, 2)
)

I'm using Python 3.8, ManimGL v1.5.0 and moderngl version: 5.7.2.

Where animation is made pinky.py.

from manimlib import *

VIDEO_FRAMES  = 'pinky_60fps-opencv'
TEXTURES = os.listdir(VIDEO_FRAMES)
N = len(TEXTURES)
FRAME_INDEX = 0

class TexturedPlaneWavingVideo(TexturedSurface):
    CONFIG = {
        'waving_plane_config':
            {
            "u_range": (-5*2,5*2),
            "v_range": (-5*2,5*2),
            "resolution": (32,32),
            "color": BLUE_E,
            "opacity": 0.85,
            }
    }
    def __init__(self, phi=0, height_factor=1.0, d=1.0, alpha=0.1,scale_factor = 0.5, init_frame= None,**kwargs):
        """
        init_frame: str
            frame used as texture
        """
        digest_config(self,self.CONFIG)
        self.init_frame = init_frame

        # Parameters
        # heigth of wave
        self.height_factor = height_factor
        self.d = d
        self.alpha = alpha
        self.phi = phi
        #overall scale of plane
        self.scale_factor = scale_factor

        # Initialize as a plane
        surface = ParametricSurface(
            uv_func = self.wave_func,
            **self.waving_plane_config).scale(self.scale_factor)

        self.surface = surface

        super().__init__(uv_surface= surface,
            image_file = os.path.join(VIDEO_FRAMES,self.init_frame))

    def update_wave(self,dt):
        self.phi += 4*dt
        global FRAME_INDEX
        FRAME_INDEX= (FRAME_INDEX+1)%N

        texture = TEXTURES[FRAME_INDEX]
        texture_path =os.path.join(VIDEO_FRAMES, TEXTURES[FRAME_INDEX])

        # Create a new TexturedPlaneWavingVideo
        plane = TexturedPlaneWavingVideo(
            phi=self.phi, height_factor=self.height_factor, d=self.d ,alpha=self.alpha,scale_factor = self.scale_factor, init_frame=texture )

        self.init_frame = texture

        self.texture_paths = {
            "LightTexture": get_full_raster_image_path(texture_path),
            "DarkTexture": get_full_raster_image_path(texture_path),}

        self.become(plane)

        self.init_shader_data()

    def plane_func(self,u,v):
        return np.array([
            u,
            v,
            0])

    def wave_func(self, u, v):

        return (u,
                v,
                np.sin((np.sqrt(u**2/self.d + v ** 2 / self.d) + self.phi)) * self.height_factor + self.alpha)

    def wave_func_np(self,u,v):
        return  np.array(
            [u,
             v,
             np.sin( (np.sqrt(u**2/self.d + v ** 2 / self.d ) + self.phi) ) * self.height_factor + self.alpha])

    def waving(self,speed = 1):
        """
        speed: float
            speed of waving animation
        """
        self.add_updater(lambda m,dt:self.update_wave(dt*speed)  )

    def stop_waving(self):
        self.clear_updaters()

class PinkyWaving(ThreeDScene):
    def construct(self):
        p = TexturedPlaneWavingVideo(phi=0, height_factor=3.0, d=1.0, alpha=0.1,scale_factor = 0.5,init_frame="frame0-00-00.00.jpg")

        self.play(ShowCreation(p))

        p.waving()

        self.wait(10)

Download an extract the images to reproduce the error:  https://drive.google.com/file/d/1_kUcDP5D4-7LXi7bbpnjdobl4ajHTOMr/view?usp=sharing

Run the command manimgl pinky.py PinkyWaving -w

Each texture_path is a path to a jpg image.

I expected to produce an animation with the full video, 2 minutes, but if the animation passes the 10 seconds it throws Invalid enum.


问:
Discord Bot not responding to ping command
I finished the code where the bot is supposed to reply back if I type in !ping but it is not replying back to me.</p>
```<code>const { messageLink } = require('discord.js');
const Discord = require('discord.js')

const client = new Discord.Client({intents:32767});

const prefix = '!';

client.on('message', message=>{
    if(!message.content.startsWith(config.prefix) || message.author.bot) return;

    const args = message.content.slice(config.prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('pong!');
    }
  })
client.once('ready', () => {
    console.log('TixyBot is online!');
});

client.login('Token')
</code>```

Body:
I finished the code where the bot is supposed to reply back if I type in !ping but it is not replying back to me.

const { messageLink } = require('discord.js');
const Discord = require('discord.js')

const client = new Discord.Client({intents:32767});

const prefix = '!';

client.on('message', message=>{
    if(!message.content.startsWith(config.prefix) || message.author.bot) return;

    const args = message.content.slice(config.prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        message.channel.send('pong!');
    }
  })
client.once('ready', () => {
    console.log('TixyBot is online!');
});

client.login('Token')


问:
Get a range but I need to get it until the last row no empty
I am trying to program some information in Excel with dynamic information and I am using the next line of code to get a range of information

```<code>var rangoValidacion = hojaResumen.getRange(9, 3, 3);
</code>```

but with that I only get up to 3 rows and that might change later I want to make it where it gets the range of all the rows but until it gets to a empty one, how can I do that?

```<code>var rangoValidacion = hojaResumen.getRange(9, 3, getlastrownoblank);
</code>```

Body:
I am trying to program some information in Excel with dynamic information and I am using the next line of code to get a range of information

var rangoValidacion = hojaResumen.getRange(9, 3, 3);

but with that I only get up to 3 rows and that might change later I want to make it where it gets the range of all the rows but until it gets to a empty one, how can I do that?

var rangoValidacion = hojaResumen.getRange(9, 3, getlastrownoblank);


问:
How to resolve the error: RuntimeError: running_mean should contain 16 elements not 32?
I am using a RE NET from https://github.com/iMED-Lab/RE-Net, and my input data is 448x448x128. When I run the Python program in Google Colab it gives the error RuntimeError: running_mean should contain 16 elements not 32.

The algorithm is here:

```<code>

nonlinearity = partial(F.relu, inplace=True)

def downsample():
    return nn.MaxPool3d(kernel_size=2, stride=2)

def deconv(in_channels, out_channels):
    return nn.ConvTranspose3d(in_channels, out_channels, kernel_size=2, stride=2)

def initialize_weights(*models):
    for model in models:
        for m in model.modules():
            if isinstance(m, nn.Conv3d) or isinstance(m, nn.Linear):
                nn.init.kaiming_normal(m.weight)
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

class ResEncoder(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(ResEncoder, self).__init__()
        self.conv1 = nn.Conv3d(in_channels, out_channels//2, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm3d(out_channels)
        self.conv2 = nn.Conv3d(out_channels//2, out_channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm3d(out_channels)
        self.relu = nn.ReLU(inplace=False)
        self.conv1x1 = nn.Conv3d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        residual = self.conv1x1(x)
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.relu(self.bn2(self.conv2(out)))
        out += residual
        out = self.relu(out)
        return out

class Decoder(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(Decoder, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv3d(in_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm3d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv3d(out_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm3d(out_channels),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        out = self.conv(x)
        return out

class RE_Net(nn.Module):
    # def __init__(self, classes, channels):
    def __init__(self):

        super(RE_Net, self).__init__()
        self.encoder1 = ResEncoder(1, 32)
        self.encoder2 = ResEncoder(32, 64)
        self.encoder3 = ResEncoder(64, 128)
        self.bridge = ResEncoder(128, 256)

        self.conv1_1 = nn.Conv3d(256, 1, kernel_size=1)
        self.conv2_2 = nn.Conv3d(128, 1, kernel_size=1)
        self.conv3_3 = nn.Conv3d(64, 1, kernel_size=1)

        self.convTrans1 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)
        self.convTrans2 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)
        self.convTrans3 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)

        self.decoder3 = Decoder(256, 128)
        self.decoder2 = Decoder(128, 64)
        self.decoder1 = Decoder(64, 32)
        self.down = downsample()
        self.up3 = deconv(256, 128)
        self.up2 = deconv(128, 64)
        self.up1 = deconv(64, 32)
        self.final = nn.Conv3d(32, 1, kernel_size=1, padding=0)
        initialize_weights(self)

    def forward(self, x):
        enc1 = self.encoder1(x)
        down1 = self.down(enc1)

        enc2 = self.encoder2(down1)
        down2 = self.down(enc2)

        con3_3 = self.conv3_3(enc2)
        convTrans3 = self.convTrans3(con3_3)
        x3 = -1 * (torch.sigmoid(convTrans3)) + 1
        x3 = x3.expand(-1, 32, -1, -1, -1).mul(enc1)
        x3 = x3 + enc1

        enc3 = self.encoder3(down2)
        down3 = self.down(enc3)

        con2_2 = self.conv2_2(enc3)
        convTrans2 = self.convTrans2(con2_2)
        x2 = -1 * (torch.sigmoid(convTrans2)) + 1
        x2 = x2.expand(-1, 64, -1, -1, -1).mul(enc2)
        x2 = x2 + enc2

        bridge = self.bridge(down3)

        conv1_1 = self.conv1_1(bridge)
        convTrans1 = self.convTrans1(conv1_1)

        x = -1 * (torch.sigmoid(convTrans1)) + 1
        x = x.expand(-1, 128, -1, -1, -1).mul(enc3)
        x = x + enc3

        up3 = self.up3(bridge)
        up3 = torch.cat((up3, x), dim=1)
        dec3 = self.decoder3(up3)

        up2 = self.up2(dec3)
        up2 = torch.cat((up2, x2), dim=1)
        dec2 = self.decoder2(up2)

        up1 = self.up1(dec2)
        up1 = torch.cat((up1, x3), dim=1)
        dec1 = self.decoder1(up1)

        final = self.final(dec1)
        final = F.sigmoid(final)
        return final

</code>```

I have researched and found out the issue has something to do with batch normalization, and I have tried to adjust the numbers, but I do not know which line is causing the problem. If anyone could help, that would be great. Thanks!

Body:
I am using a RE NET from https://github.com/iMED-Lab/RE-Net, and my input data is 448x448x128. When I run the Python program in Google Colab it gives the error RuntimeError: running_mean should contain 16 elements not 32.

The algorithm is here:

nonlinearity = partial(F.relu, inplace=True)

def downsample():
    return nn.MaxPool3d(kernel_size=2, stride=2)

def deconv(in_channels, out_channels):
    return nn.ConvTranspose3d(in_channels, out_channels, kernel_size=2, stride=2)

def initialize_weights(*models):
    for model in models:
        for m in model.modules():
            if isinstance(m, nn.Conv3d) or isinstance(m, nn.Linear):
                nn.init.kaiming_normal(m.weight)
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

class ResEncoder(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(ResEncoder, self).__init__()
        self.conv1 = nn.Conv3d(in_channels, out_channels//2, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm3d(out_channels)
        self.conv2 = nn.Conv3d(out_channels//2, out_channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm3d(out_channels)
        self.relu = nn.ReLU(inplace=False)
        self.conv1x1 = nn.Conv3d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        residual = self.conv1x1(x)
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.relu(self.bn2(self.conv2(out)))
        out += residual
        out = self.relu(out)
        return out

class Decoder(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(Decoder, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv3d(in_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm3d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv3d(out_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm3d(out_channels),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        out = self.conv(x)
        return out

class RE_Net(nn.Module):
    # def __init__(self, classes, channels):
    def __init__(self):

        super(RE_Net, self).__init__()
        self.encoder1 = ResEncoder(1, 32)
        self.encoder2 = ResEncoder(32, 64)
        self.encoder3 = ResEncoder(64, 128)
        self.bridge = ResEncoder(128, 256)

        self.conv1_1 = nn.Conv3d(256, 1, kernel_size=1)
        self.conv2_2 = nn.Conv3d(128, 1, kernel_size=1)
        self.conv3_3 = nn.Conv3d(64, 1, kernel_size=1)

        self.convTrans1 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)
        self.convTrans2 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)
        self.convTrans3 = nn.ConvTranspose3d(1, 1, kernel_size=2, stride=2)

        self.decoder3 = Decoder(256, 128)
        self.decoder2 = Decoder(128, 64)
        self.decoder1 = Decoder(64, 32)
        self.down = downsample()
        self.up3 = deconv(256, 128)
        self.up2 = deconv(128, 64)
        self.up1 = deconv(64, 32)
        self.final = nn.Conv3d(32, 1, kernel_size=1, padding=0)
        initialize_weights(self)

    def forward(self, x):
        enc1 = self.encoder1(x)
        down1 = self.down(enc1)

        enc2 = self.encoder2(down1)
        down2 = self.down(enc2)

        con3_3 = self.conv3_3(enc2)
        convTrans3 = self.convTrans3(con3_3)
        x3 = -1 * (torch.sigmoid(convTrans3)) + 1
        x3 = x3.expand(-1, 32, -1, -1, -1).mul(enc1)
        x3 = x3 + enc1

        enc3 = self.encoder3(down2)
        down3 = self.down(enc3)

        con2_2 = self.conv2_2(enc3)
        convTrans2 = self.convTrans2(con2_2)
        x2 = -1 * (torch.sigmoid(convTrans2)) + 1
        x2 = x2.expand(-1, 64, -1, -1, -1).mul(enc2)
        x2 = x2 + enc2

        bridge = self.bridge(down3)

        conv1_1 = self.conv1_1(bridge)
        convTrans1 = self.convTrans1(conv1_1)

        x = -1 * (torch.sigmoid(convTrans1)) + 1
        x = x.expand(-1, 128, -1, -1, -1).mul(enc3)
        x = x + enc3

        up3 = self.up3(bridge)
        up3 = torch.cat((up3, x), dim=1)
        dec3 = self.decoder3(up3)

        up2 = self.up2(dec3)
        up2 = torch.cat((up2, x2), dim=1)
        dec2 = self.decoder2(up2)

        up1 = self.up1(dec2)
        up1 = torch.cat((up1, x3), dim=1)
        dec1 = self.decoder1(up1)

        final = self.final(dec1)
        final = F.sigmoid(final)
        return final

I have researched and found out the issue has something to do with batch normalization, and I have tried to adjust the numbers, but I do not know which line is causing the problem. If anyone could help, that would be great. Thanks!


问:
Error: Mismatch of Closure Arguments expected fn(&static _) found fn(_)
I am getting this type error and I cannot figure out what is wrong code below:

use std::{collections::{HashMap, btree_map::Values}, any::TypeId};
#[macro_use]
use lazy_static::lazy_static;

pub fn constraint_eq(x: &f32, y: &f32) -> f32 {
    (x-y).abs()
}

pub fn constraint_neq(x: &f32, y: &f32) -> f32 {

    match x != y {
        true => 0.0,
        false => (x-y).abs()
    }
}

pub fn constraint_lt(x: &f32, y: &f32) -> f32 {
    match x < y {
        true => 0.0,
        false => (x-y).abs()
    }
}

pub fn constraint_gt(x: &f32, y: &f32) -> f32 {
   match x > y {
        true => 0.0,
        false => (x-y).abs()
    }
   }

type ConstraintFn = fn(&f32, &f32) -> f32;

lazy_static! {//
    pub static ref OPERATORS: HashMap<String, fn(&f32, &f32) -> f32> = {
        let mut m = HashMap::new();
        m.insert("==".to_string(), constraint_eq as ConstraintFn);
        m.insert("!=".to_string(), constraint_neq as ConstraintFn);
        m.insert("<".to_string(), constraint_lt as ConstraintFn);
        m.insert(">".to_string(), constraint_gt as ConstraintFn);
        m
    };
}

pub struct Constraint{
    // EQUALS: &'static str = "==0"
    //
    EQUALS_ZERO: &'static str,
    LESS_THAN_ZERO: &'static str ,
    GREATER_THAN_ZERO: &'static str,
    op: &'static str,
    // function: fn(&f32) -> f32,
    function: Box<dyn Fn(&'a f32) -> f32>
}

impl Constraint{
    pub fn new(op: &'static str, value: Option<f32>) -> Constraint {
        let EQUALS_ZERO: &'static str = "==0";
        let LESS_THAN_ZERO: &'static str = "<0";
        let GREATER_THAN_ZERO: &'static str = ">0";
        // let op: &'static str;
        if value.is_some() {

            let op = &format!("{}{}", &op, &value.unwrap().to_string());
            let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));

            return Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}

        } else {
            let op = &format!("{}{}", &op, &0.0.to_string());
            let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));
            return Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
        }

        }

        pub fn call(&self, value: &f32) -> f32 {
            (self.function)(value)
        }
        // Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
        }

```
<p>I am trying to get a partial function of it becoming a closure, but sure how to fix this error.
the error that I am getting is :</p>
```|             let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));
    |                                     ------------ found signature defined here
101 |
102 |             return Constraint {EQUALS_ZERO, LEQ_ZERO, GEQ_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
    |                                                                                ^^^^^^^^ expected due to this
    |
    = note: expected closure signature `fn(&'static f32) -> _`
               found closure signature `fn(f32) -> _`
    = note: required for the cast from `[closure@src/constraint.rs:100:37: 100:49]` to the object type `dyn Fn(&'static f32) -> f32`
```

What am I doing wrong, and how can this be fixed? I

I tried incorporating lifetimes but I have been running into an error. I switched from fn(&f32)-> f32 to Box<dyn Fn(&'a f32) -> f32>

Body:
I am getting this type error and I cannot figure out what is wrong code below:

use std::{collections::{HashMap, btree_map::Values}, any::TypeId};
#[macro_use]
use lazy_static::lazy_static;

pub fn constraint_eq(x: &f32, y: &f32) -> f32 {
    (x-y).abs()
}

pub fn constraint_neq(x: &f32, y: &f32) -> f32 {

    match x != y {
        true => 0.0,
        false => (x-y).abs()
    }
}

pub fn constraint_lt(x: &f32, y: &f32) -> f32 {
    match x < y {
        true => 0.0,
        false => (x-y).abs()
    }
}

pub fn constraint_gt(x: &f32, y: &f32) -> f32 {
   match x > y {
        true => 0.0,
        false => (x-y).abs()
    }
   }

type ConstraintFn = fn(&f32, &f32) -> f32;

lazy_static! {//
    pub static ref OPERATORS: HashMap<String, fn(&f32, &f32) -> f32> = {
        let mut m = HashMap::new();
        m.insert("==".to_string(), constraint_eq as ConstraintFn);
        m.insert("!=".to_string(), constraint_neq as ConstraintFn);
        m.insert("<".to_string(), constraint_lt as ConstraintFn);
        m.insert(">".to_string(), constraint_gt as ConstraintFn);
        m
    };
}

pub struct Constraint{
    // EQUALS: &'static str = "==0"
    //
    EQUALS_ZERO: &'static str,
    LESS_THAN_ZERO: &'static str ,
    GREATER_THAN_ZERO: &'static str,
    op: &'static str,
    // function: fn(&f32) -> f32,
    function: Box<dyn Fn(&'a f32) -> f32>
}

impl Constraint{
    pub fn new(op: &'static str, value: Option<f32>) -> Constraint {
        let EQUALS_ZERO: &'static str = "==0";
        let LESS_THAN_ZERO: &'static str = "<0";
        let GREATER_THAN_ZERO: &'static str = ">0";
        // let op: &'static str;
        if value.is_some() {

            let op = &format!("{}{}", &op, &value.unwrap().to_string());
            let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));

            return Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}

        } else {
            let op = &format!("{}{}", &op, &0.0.to_string());
            let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));
            return Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
        }

        }

        pub fn call(&self, value: &f32) -> f32 {
            (self.function)(value)
        }
        // Constraint {EQUALS_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
        }

I am trying to get a partial function of it becoming a closure, but sure how to fix this error.
the error that I am getting is :

|             let function = Box::new(move |x:f32| OPERATORS[op](&x, &value.unwrap()));
    |                                     ------------ found signature defined here
101 |
102 |             return Constraint {EQUALS_ZERO, LEQ_ZERO, GEQ_ZERO, LESS_THAN_ZERO, GREATER_THAN_ZERO, function, op}
    |                                                                                ^^^^^^^^ expected due to this
    |
    = note: expected closure signature `fn(&'static f32) -> _`
               found closure signature `fn(f32) -> _`
    = note: required for the cast from `[closure@src/constraint.rs:100:37: 100:49]` to the object type `dyn Fn(&'static f32) -> f32`

What am I doing wrong, and how can this be fixed? I

I tried incorporating lifetimes but I have been running into an error. I switched from fn(&f32)-> f32 to Box<dyn Fn(&'a f32) -> f32>


问:
:not selector isn't recognizing classes

.titlebar {
  justify-content: baseline;
  width: 100%;
  margin: 0 auto;
  top: -2px;
  height: 125px;
  position: fixed;
  background-color: rgb(0, 0, 0);
  z-index: 2;
}

.titlebar:not(.join) {
  display: flex;
}

.login,
.join {
  float: right;
  display: inline-flex;
  text-decoration: none;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  color: white;
  height: fit-content;
  width: fit-content;
  font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div
  onclick="window.location='join.php';"
  id="join"
  class="join"
  style=" color: black; border-radius: 5px;">
  Join
</div>
<div
  onclick="window.location='login.php';"
  id="login"
  class="login">
  Log In
</div></code>```

I'm trying to use :not to exclusively align .login and .join on the right. When I try it with element types like div, it works as all elements in my bar are divs, but it does not recognize .login, .join, or any other class I used to test. What am I doing wrong?

Title: :not selector isn't recognizing classes

Body:
.titlebar {
  justify-content: baseline;
  width: 100%;
  margin: 0 auto;
  top: -2px;
  height: 125px;
  position: fixed;
  background-color: rgb(0, 0, 0);
  z-index: 2;
}

.titlebar:not(.join) {
  display: flex;
}

.login,
.join {
  float: right;
  display: inline-flex;
  text-decoration: none;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  color: white;
  height: fit-content;
  width: fit-content;
  font-size: 20px;
}

  Join

  Log In

I'm trying to use :not to exclusively align .login and .join on the right. When I try it with element types like div, it works as all elements in my bar are divs, but it does not recognize .login, .join, or any other class I used to test. What am I doing wrong?


问:
App created with PyInstaller only works properly if launched with the executable script - macOS
Hello and thanks for your help.

I created an app with PyInstaller on macOS, it launches but all my buttons in it don't do anything. BUT, if go grab the executable script in it via Show Package Contents, it works perfectly...I don't understand why...I checked my security preferences to see if the app was being restricted but all seems alright...

Example > get the video title of a YouTube url

`

```<code>import tkinter as tk
from pytube import YouTube
import ssl
ssl._create_default_https_context = ssl._create_stdlib_context

def search_video(video_url):
  yt = YouTube(video_url)
  return yt.title

def on_click():
  video_url = input_field.get()
  result = search_video(video_url)
  result_label.config(text=result)

window = tk.Tk()
window.title("YouTube Search")

input_field = tk.Entry(window)
input_field.pack()

search_button = tk.Button(window, text="Search", command=on_click)
search_button.pack()

result_label = tk.Label(window)
result_label.pack()

window.mainloop()
</code>```

`

Body:
Hello and thanks for your help.

I created an app with PyInstaller on macOS, it launches but all my buttons in it don't do anything. BUT, if go grab the executable script in it via Show Package Contents, it works perfectly...I don't understand why...I checked my security preferences to see if the app was being restricted but all seems alright...

Example > get the video title of a YouTube url

`

import tkinter as tk
from pytube import YouTube
import ssl
ssl._create_default_https_context = ssl._create_stdlib_context

def search_video(video_url):
  yt = YouTube(video_url)
  return yt.title

def on_click():
  video_url = input_field.get()
  result = search_video(video_url)
  result_label.config(text=result)

window = tk.Tk()
window.title("YouTube Search")

input_field = tk.Entry(window)
input_field.pack()

search_button = tk.Button(window, text="Search", command=on_click)
search_button.pack()

result_label = tk.Label(window)
result_label.pack()

window.mainloop()

`


问:
Can't connect to Redis using ioredis lib when running tests with jest
I have a typescript system using postgres and redis as databases. I use ioredis (v4.28.5) to handle redis and prisma (v4.8.0) to handle with Postgres .
To test this system I'm using jest and supertest for integration tests, but to be able to change the postgres schemas for each test suit (so they don't mess with each other), I use jest custom environment to handle postgres database URL to change the schema before each test.

My problem is that redis is hanging in the connecting state, until a timeout error occurs. What is driving me crazy is that running locally (npm start) works fine.

Here are my configuration files.

Redis Client Connection

import { readFileSync } from "node:fs";
import Redis from "ioredis";
import { resolve } from "node:path";
import logger from "@utils/logger";

const {
  NODE_ENV,
  REDIS_HOST: host,
  REDIS_PORT: port,
  REDIS_USERNAME: username,
  REDIS_PASSWORD: password,
} = process.env;

if (typeof host !== "string" || typeof port !== "string") {
  logger.error("Database - Redis credentials not loaded.");
  throw new Error("Redis DB1 credentials not loaded.");
}

const parsedPort = Number.parseInt(port || "6379", 10);
const connectionData = {
  host,
  port: parsedPort,
  db: 1,
};

if (NODE_ENV !== "local" && NODE_ENV !== "test") {
  if (typeof username !== "string" || typeof password !== "string") {
    logger.error("Database - Redis SAFETY credentials not loaded.");
    throw new Error("Redis SAFETY credentials not loaded.");
  }
  try {
    // eslint-disable-next-line unicorn/prefer-module
    const redisCert = readFileSync(resolve(__dirname, "../../../certificates/redis.pem"));

    if (redisCert) {
      Object.assign(connectionData, {
        username,
        password,
        tls: {
          ca: redisCert,
        },
      });
    }
  } catch (error) {
    logger.warn("Error reading REDIS cert file");
    throw error;
  }
}

const redisDB = new Redis(connectionData);
// const redisDB = "foo";
logger.info("Connect to REDIS DB1");

export default redisDB;
```
<p><strong>jest.config.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>import { compilerOptions } from "./tsconfig.json";
import { pathsToModuleNameMapper } from "ts-jest";

export default {
  // Automatically clear mock calls, instances and results before every test
  clearMocks: true,
  // An array of regexp pattern strings used to skip coverage collection
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ],
  // Indicates which provider should be used to instrument code for coverage
  coverageProvider: "v8",
  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>" }),
  // A preset that is used as a base for Jest's configuration
  preset: "ts-jest",
  // The glob patterns Jest uses to detect test files
  testMatch: ["**/__tests__/modules/**/?(*.)+(spec|test).ts"],
};
</code>```

test file

/**
 * @jest-environment ./prisma/prismaEnvironmentJest
 */

import prisma from "@database/prisma";
import app from "@src/app";
import request from "supertest";

describe("Create User Controller", () => {
  afterAll(async () => {
    const databaseURL = process.env.DATABASE_URL;
    if (typeof databaseURL === "string") {
      const URLSplitted = databaseURL.split("schema=");
      const schema = URLSplitted[1];

      await prisma.$queryRawUnsafe(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
    }
  });

  it("Should be able to create a new user", async () => {
    const name = "John Doe";
    const email = "john.doe@email.com";

    const { status, body } = await request(app)
      .post("/users")
      .send({
        name,
        email,
      });

    expect(status).toBe(201);
    expect(body).toHaveProperty("id");
    expect(body).toHaveProperty("name", name);
    expect(body).toHaveProperty("email", email);
  });
});
```
<p><strong>custom jest environment</strong></p>
<pre class="lang-js prettyprint-override"><code>const NodeEnvironment = require("jest-environment-node");
const { randomUUID } = require("node:crypto");
const { execSync } = require("node:child_process");

require('dotenv').config()

class CustomEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
    this.schema = randomUUID();
    const DATABASE_URL_SPLITTER = "schema="
    const [baseDatabaseURL,] = process.env.DATABASE_URL?.split(DATABASE_URL_SPLITTER)
    this.connectionString = baseDatabaseURL + DATABASE_URL_SPLITTER + this.schema
  }

  setup() {
    process.env.DATABASE_URL = this.connectionString;
    this.global.process.env.DATABASE_URL = this.connectionString;

    // RUN MIGRATIONS
    execSync("npx prisma migrate dev");
  }

  getVmContext() {
    return super.getVmContext();
  }
}

module.exports = CustomEnvironment;
</code>```

jest console error

Jest has detected the following 3 open handles potentially keeping Jest from exiting:

  ●  Timeout

      48 | }
      49 |
    > 50 | const redisDB = new Redis(connectionData);
         |                 ^
      51 | // const redisDB = "foo";
      52 | logger.info("Connect to REDIS DB1");
      53 |

      at node_modules/ioredis/built/redis/index.js:278:48
      at Redis.Object.<anonymous>.Redis.connect (node_modules/ioredis/built/redis/index.js:265:21)
      at new Redis (node_modules/ioredis/built/redis/index.js:167:14)
```

Not sure if the custom environment is guilt for anything but I couldn't found nothing similar to this and pretty sure someone uses ioredis, jest, and supertest together

Body:
I have a typescript system using postgres and redis as databases. I use ioredis (v4.28.5) to handle redis and prisma (v4.8.0) to handle with Postgres .
To test this system I'm using jest and supertest for integration tests, but to be able to change the postgres schemas for each test suit (so they don't mess with each other), I use jest custom environment to handle postgres database URL to change the schema before each test.

My problem is that redis is hanging in the connecting state, until a timeout error occurs. What is driving me crazy is that running locally (npm start) works fine.

Here are my configuration files.

Redis Client Connection

import { readFileSync } from "node:fs";
import Redis from "ioredis";
import { resolve } from "node:path";
import logger from "@utils/logger";

const {
  NODE_ENV,
  REDIS_HOST: host,
  REDIS_PORT: port,
  REDIS_USERNAME: username,
  REDIS_PASSWORD: password,
} = process.env;

if (typeof host !== "string" || typeof port !== "string") {
  logger.error("Database - Redis credentials not loaded.");
  throw new Error("Redis DB1 credentials not loaded.");
}

const parsedPort = Number.parseInt(port || "6379", 10);
const connectionData = {
  host,
  port: parsedPort,
  db: 1,
};

if (NODE_ENV !== "local" && NODE_ENV !== "test") {
  if (typeof username !== "string" || typeof password !== "string") {
    logger.error("Database - Redis SAFETY credentials not loaded.");
    throw new Error("Redis SAFETY credentials not loaded.");
  }
  try {
    // eslint-disable-next-line unicorn/prefer-module
    const redisCert = readFileSync(resolve(__dirname, "../../../certificates/redis.pem"));

    if (redisCert) {
      Object.assign(connectionData, {
        username,
        password,
        tls: {
          ca: redisCert,
        },
      });
    }
  } catch (error) {
    logger.warn("Error reading REDIS cert file");
    throw error;
  }
}

const redisDB = new Redis(connectionData);
// const redisDB = "foo";
logger.info("Connect to REDIS DB1");

export default redisDB;

jest.config.ts

import { compilerOptions } from "./tsconfig.json";
import { pathsToModuleNameMapper } from "ts-jest";

export default {
  // Automatically clear mock calls, instances and results before every test
  clearMocks: true,
  // An array of regexp pattern strings used to skip coverage collection
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ],
  // Indicates which provider should be used to instrument code for coverage
  coverageProvider: "v8",
  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: "<rootDir>" }),
  // A preset that is used as a base for Jest's configuration
  preset: "ts-jest",
  // The glob patterns Jest uses to detect test files
  testMatch: ["**/__tests__/modules/**/?(*.)+(spec|test).ts"],
};

test file

/**
 * @jest-environment ./prisma/prismaEnvironmentJest
 */

import prisma from "@database/prisma";
import app from "@src/app";
import request from "supertest";

describe("Create User Controller", () => {
  afterAll(async () => {
    const databaseURL = process.env.DATABASE_URL;
    if (typeof databaseURL === "string") {
      const URLSplitted = databaseURL.split("schema=");
      const schema = URLSplitted[1];

      await prisma.$queryRawUnsafe(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
    }
  });

  it("Should be able to create a new user", async () => {
    const name = "John Doe";
    const email = "john.doe@email.com";

    const { status, body } = await request(app)
      .post("/users")
      .send({
        name,
        email,
      });

    expect(status).toBe(201);
    expect(body).toHaveProperty("id");
    expect(body).toHaveProperty("name", name);
    expect(body).toHaveProperty("email", email);
  });
});

custom jest environment

const NodeEnvironment = require("jest-environment-node");
const { randomUUID } = require("node:crypto");
const { execSync } = require("node:child_process");

require('dotenv').config()

class CustomEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
    this.schema = randomUUID();
    const DATABASE_URL_SPLITTER = "schema="
    const [baseDatabaseURL,] = process.env.DATABASE_URL?.split(DATABASE_URL_SPLITTER)
    this.connectionString = baseDatabaseURL + DATABASE_URL_SPLITTER + this.schema
  }

  setup() {
    process.env.DATABASE_URL = this.connectionString;
    this.global.process.env.DATABASE_URL = this.connectionString;

    // RUN MIGRATIONS
    execSync("npx prisma migrate dev");
  }

  getVmContext() {
    return super.getVmContext();
  }
}

module.exports = CustomEnvironment;

jest console error

Jest has detected the following 3 open handles potentially keeping Jest from exiting:

  ●  Timeout

      48 | }
      49 |
    > 50 | const redisDB = new Redis(connectionData);
         |                 ^
      51 | // const redisDB = "foo";
      52 | logger.info("Connect to REDIS DB1");
      53 |

      at node_modules/ioredis/built/redis/index.js:278:48
      at Redis.Object.<anonymous>.Redis.connect (node_modules/ioredis/built/redis/index.js:265:21)
      at new Redis (node_modules/ioredis/built/redis/index.js:167:14)

Not sure if the custom environment is guilt for anything but I couldn't found nothing similar to this and pretty sure someone uses ioredis, jest, and supertest together


问:
how do I set access_type to offline for oath for google api
I am creating a script that will handle files on my local computer and my google drive.
I have fixed so I could use the script.
but after a while I got this error:

```<code>  File "C:\Users\name\AppData\Roaming\Python\Python311\site-packages\pydrive2\auth.py", line 662, in Refresh
    raise RefreshError(
pydrive2.auth.RefreshError: No refresh_token found.Please set access_type of OAuth to offline.
</code>```

And I am new to this and have no idea where I should change the access type.

my main code is located in my documents-folder.

I am using google cloud and have a project there for this script.

I have tried to change the access_type in theauth.py.
it says aaccess_type:'online'. and I changed it to offline.
nothing happend.

I have also tried to add "&access_type=offline" after the url in client secret .json after auth_uri.
I also tried to add &prompt=consent.

But nothing seemes to work.

As a new coder I need someone to explain to me as I was 5 years old (even if there are 5-year-olds that are much better than me...).

Thank you and have a good day!

edit:
or am I tackeling this wrong?
should I refresh the token/key on google cloud api?
or should I delete some files that gets created when running the script?

Body:
I am creating a script that will handle files on my local computer and my google drive.
I have fixed so I could use the script.
but after a while I got this error:

  File "C:\Users\name\AppData\Roaming\Python\Python311\site-packages\pydrive2\auth.py", line 662, in Refresh
    raise RefreshError(
pydrive2.auth.RefreshError: No refresh_token found.Please set access_type of OAuth to offline.

And I am new to this and have no idea where I should change the access type.

my main code is located in my documents-folder.

I am using google cloud and have a project there for this script.

I have tried to change the access_type in theauth.py.
it says aaccess_type:'online'. and I changed it to offline.
nothing happend.

I have also tried to add "&access_type=offline" after the url in client secret .json after auth_uri.
I also tried to add &prompt=consent.

But nothing seemes to work.

As a new coder I need someone to explain to me as I was 5 years old (even if there are 5-year-olds that are much better than me...).

Thank you and have a good day!

edit:
or am I tackeling this wrong?
should I refresh the token/key on google cloud api?
or should I delete some files that gets created when running the script?


问:
Flutter how to hide focused menu child when menu appears and show it when it desappears
I'm using focused_menu as menu inside actions in the appBar to be able to customize items background color.
I've modifed the offset to hide the actions icon when the focued menu appears but the icon is still visible how can I fix it ?

What I have

What I would like to have

Here's the code

```<code>class TestMenu extends StatefulWidget {
  const TestMenu({Key? key}) : super(key: key);

  @override
  State<TestMenu> createState() => _TestMenuState();
}

class _TestMenuState extends State<TestMenu> {
  @override
  Widget build(BuildContext context) {
    return FocusedMenuHolder(
      menuWidth: MediaQuery.of(context).size.width * 0.5,
      blurBackgroundColor: Colors.transparent,
      blurSize: 0,
      menuOffset: -50,
      openWithTap: true,
      child: Icon(
        Icons.more_vert,
        color: Colors.black,
      ),
      onPressed: () {},
      menuItems: [
        FocusedMenuItem(
          title: Row(
              children: [
                Icon(
                  Icons.science,
                  color: Colors.white,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Lab",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ]
          ),
          backgroundColor: Colors.blue,
          onPressed: () {
            print("Lab clicked");
          },
        ),
        FocusedMenuItem(
            title: Row(
              children: [
                Icon(
                  Icons.settings,
                  color: Colors.black,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Settings",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ]
            ),
            onPressed: () {
              print("Settings clicked");
            },
        ),
        FocusedMenuItem(
          title: Row(
              children: [
                Icon(
                  Icons.share,
                  color: Colors.black,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Share",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ]
          ),
          onPressed: () {
            print("Share clicked");
          },
        ),
      ],
    );
  }
}
</code>```

I've tried to wrap FocusedMenuHolder inside Visbility but it doesn't works because click on the child Icon make appears the focused menu and it will change both visibility at the same time, it means menu disappears Icon too

Body:
I'm using focused_menu as menu inside actions in the appBar to be able to customize items background color.
I've modifed the offset to hide the actions icon when the focued menu appears but the icon is still visible how can I fix it ?

What I have

What I would like to have

Here's the code

class TestMenu extends StatefulWidget {
  const TestMenu({Key? key}) : super(key: key);

  @override
  State<TestMenu> createState() => _TestMenuState();
}

class _TestMenuState extends State<TestMenu> {
  @override
  Widget build(BuildContext context) {
    return FocusedMenuHolder(
      menuWidth: MediaQuery.of(context).size.width * 0.5,
      blurBackgroundColor: Colors.transparent,
      blurSize: 0,
      menuOffset: -50,
      openWithTap: true,
      child: Icon(
        Icons.more_vert,
        color: Colors.black,
      ),
      onPressed: () {},
      menuItems: [
        FocusedMenuItem(
          title: Row(
              children: [
                Icon(
                  Icons.science,
                  color: Colors.white,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Lab",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ]
          ),
          backgroundColor: Colors.blue,
          onPressed: () {
            print("Lab clicked");
          },
        ),
        FocusedMenuItem(
            title: Row(
              children: [
                Icon(
                  Icons.settings,
                  color: Colors.black,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Settings",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ]
            ),
            onPressed: () {
              print("Settings clicked");
            },
        ),
        FocusedMenuItem(
          title: Row(
              children: [
                Icon(
                  Icons.share,
                  color: Colors.black,
                ),
                const SizedBox(width: 12,),
                Text(
                  "Share",
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ]
          ),
          onPressed: () {
            print("Share clicked");
          },
        ),
      ],
    );
  }
}

I've tried to wrap FocusedMenuHolder inside Visbility but it doesn't works because click on the child Icon make appears the focused menu and it will change both visibility at the same time, it means menu disappears Icon too


问:
How do I use Chrome's -webkit-mask-image in the web animations api?
I'm trying to animate the discrete [-webkit-]mask-image property, as shown below.  The left image is animated with CSS3 properties which works in Chrome, Safari and Firefox.  The center image is animated via the Web Animations API which works in Safari and Firefox, but not Chrome despite trying many variations of the camel-cased vendor prefixed property.

Is this just a bug or is there some other naming convention I'm missing?

Possibly related to Do I include vendor prefixes when animating with WAAPI animate()?

```<code><html>
<h1>Web animations API with vendor prefixed properties</h1>
<style>
img {
  margin: 0 50px;
  width: 300px;
  height: 300px;
}

.mask {
   -webkit-mask-position: 50px 50px;
  mask-position: 50px 50px;
  -webkit-mask-size: 200px 200px;
  mask-size: 200px 200px;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

.mask-css {
  animation: mask_frames 1s infinite;
}

@keyframes mask_frames {
  0% {
    -webkit-mask-image: none;
    mask-image: none
  }
  100% {
  -webkit-mask-image: url(https://upload.wikimedia.org/wikipedia/commons/c/c8/Black_Star.svg);
  mask-image: url(https://upload.wikimedia.org/wikipedia/commons/c/c8/Black_Star.svg);
  }
}
</style>

<!-- CSS3 animation -->
<div class='container'>
  <img class="mask mask-css" src="https://services.google.com/fh/files/misc/color_grey.jpg">

  <!-- JS animation, doesn't work in Chrome -->
  <img class="mask mask-js" src="https://services.google.com/fh/files/misc/color_grey.jpg">

  <!-- No animation for refernce -->
  <img class="no-mask" src="https://services.google.com/fh/files/misc/color_grey.jpg">
</div>
<script>
let elt = document.getElementsByClassName('mask-js')[0],
    url = 'url(https://upload.wikimedia.org/wikipedia/commons/c/c8/Black_Star.svg)';

// works in Safari and Firefox but not Chrome
elt.animate([
  {
    '-webkit-mask-image': 'none',
    webkitMaskImage: 'none',
    webKitMaskImage: 'none',
    WebKitMaskImage: 'none',
    WebkitMaskImage: 'none',
    CSSPropertyWebkitMaskImage: 'none',
    maskImage: 'none',
  },
  {
    '-webkit-mask-image': url,
    webkitMaskImage: url,
    webKitMaskImage: url,
    WebKitMaskImage: url,
    WebkitMaskImage: url,
    CSSPropertyWebkitMaskImage: url,
    maskImage: url,
  },
],
  {duration: 1000, iterations: Infinity}
);
</script>
</html>
</code>```

Body:
I'm trying to animate the discrete [-webkit-]mask-image property, as shown below.  The left image is animated with CSS3 properties which works in Chrome, Safari and Firefox.  The center image is animated via the Web Animations API which works in Safari and Firefox, but not Chrome despite trying many variations of the camel-cased vendor prefixed property.

Is this just a bug or is there some other naming convention I'm missing?

Possibly related to Do I include vendor prefixes when animating with WAAPI animate()?

Web animations API with vendor prefixed properties


问:
ERROR: Could not find a version that satisfies the requirement sklearn.preprocessing
I've been using Python 3.11.1 and try to install sklearn.preprocessing from cmd window. Help me with this ERROR: Could not find a version that satisfies the requirement sklearn.preprocessing. Thank you!</p>


问:
Is there a way for VS Code Intellisense to show the summary for all items in the suggestions list?
I have a global css variables file hooked up to intellisense. Is there a way for VS Code to show the mapped values for all of them in that suggestions list?

I noticed that the pixel value is the same as the second screenshot for a description of an method.


问:
Setup phpmyadmin with PHP 8.2?
After following the tutorial:
https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-20-04

I've been getting a seemingly endless amount of errors with phpmyadmin. I fix one then move onto the next but I'm wondering if it just isn't compatible yet or if I set it up incorrectly. The tutorial mentions a list of packages to be installed and to refer to your version of php for the correct pages. I cannot find that list for PHP 8.2.

The current list of packages is:
phpmyadmin php-mbstring php-zip php-gd php-json php-curl

In which I changed php-mbstring to php8.2-mbstring and left the others. After this did not work I tried changing the others to php8.2 versions to no avail:
phpmyadmin php8.2-mbstring php8.2-zip php8.2-gd php-json php8.2-curl
Note: It appears that it updates the libraries to 8.2 automatically when applicable if installing with the regular names.

I've added parenthesis to certain functions in phpmyadmin, overrode/updated mbstring due to the new deprecation notices with PHP 8.2, commented out lines that are being called more than once (when they aren't supposed to be), etc.

It is now giving the errors such as "Cannot redeclare PMA_sprites()" and "Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array"

I'm done solving errors even though there are more and I'm going to assume that either a. It's not compatible or b. I'm installing the wrong libraries. Any help is greatly appreciated.

P.S. These errors occur when I visit mysite/phpmyadmin and come from the error.log.

Title: Setup phpmyadmin with PHP 8.2?


问:
Does chaining prefetch_related fetch all sub-queries?
Take this for example:

user = User.objects.prefetch_related("foo__bar__baz").get(id=id)

In this scenario, do I not need to do:

user = User.objects.prefetch_related("foo__bar").get(id=id) if I want to access values on bar, or if they are mixed between select_related and prefetch_related due to some being OneToOne and others being FK like this below?

user = User.objects.prefetch_related("foo__bar__baz").select_related("foo_bar_baz_qux").get(id=id)

Or would skipping the prefetch and only using select be sufficient?

user = User.objects.select_related("foo_bar_baz_qux").get(id=id)


问:
Output from noisy optimization in skopt.gp_minimize
When using skopt.gp_minimize on a noisy dataset with unknown variance - is the returned minimum the x-values found for one specific sample of data or the minimum of the surrogate function? And either way - is it possible to specify which one is desired?

I have looked through the documentation but have been unable to find anything describing this.


问:
How to check if object is inside terrain area?
I have a  plane and when i click on the plane it's spawning objects on the plane area and on the terrain ground.

but i want to do that if the plane or part of it is out of the terrain area that it will disable the spawning part.

This screenshot show the plane above the terrain.

and this screenshot where the plane is out of the terrain area but i can still click on the plane and spawn objects.

This is the spawn objects script :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class SpawnObjects : MonoBehaviour
{
    public GameObject prefabToSpawn;
    public Terrain terrain;
    public CustomPlane plane;
    public GameObject spawnedTerrainObjectsParent;
    public GameObject spawnedPlaneObjectsParent;
    public bool go = false;
    public int numberOfObjects;
    public float duration;
    public float yOffset = 0.5f;
    public bool isParent = true;

    private float terrainWidth;
    private float terrainLength;
    private float xTerrainPos;
    private float zTerrainPos;

    private float planeWidth;
    private float planeLength;
    private float xPlanePos;
    private float zPlanePos;

    private float yValTerrain;
    private float yValPlane;

    private float randXTerrain;
    private float randZTerrain;

    private float randXPlane;
    private float randZPlane;

    private GameObject cube;

    private Collider terrainCollider;
    void Awake()
    {
        if (terrain != null)
        {
            //Get terrain size
            terrainWidth = terrain.terrainData.size.x;
            terrainLength = terrain.terrainData.size.z;

            //Get terrain position
            xTerrainPos = terrain.transform.position.x;
            zTerrainPos = terrain.transform.position.z;

            terrainCollider = terrain.GetComponent<Collider>();
        }

        if (plane != null)
        {
            planeWidth = plane.width;
            planeLength = plane.length;
            xPlanePos = plane.transform.position.x;
            zPlanePos = plane.transform.position.z;
        }

        if (isParent)
        {
            if(spawnedTerrainObjectsParent == null)
            {
                spawnedTerrainObjectsParent = GameObject.Find("Spawned Terrain Parent");
            }

            if(spawnedPlaneObjectsParent == null)
            {
                spawnedPlaneObjectsParent = GameObject.Find("Spawned Plane Parent");
            }
        }

        Camera.main.transform.position =
            new Vector3(plane.GetComponent<Renderer>().bounds.center.x, 635,
            plane.GetComponent<Renderer>().bounds.center.z);

        if (go)
        {
            StartCoroutine(Generate());
        }
    }

    IEnumerator Generate()
    {
        //Generate the Prefab on the generated position
        for (int i = 0; i < numberOfObjects; i++)
        {
            if (terrain != null)
            {
                //Generate random x,z,y position on the terrain
                randXTerrain = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
                randZTerrain = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
                yValTerrain = Terrain.activeTerrain.SampleHeight(new Vector3(randXTerrain, 0, randZTerrain));
                yValTerrain = yValTerrain + yOffset;

                GameObject objInstanceTerrain = (GameObject)Instantiate(prefabToSpawn,
                new Vector3(randXTerrain, yValTerrain, randZTerrain), Quaternion.identity);

                objInstanceTerrain.name = "Terrain Spawned";

                if (isParent)
                {
                    objInstanceTerrain.transform.parent = spawnedTerrainObjectsParent.transform;
                }
            }

            if (plane != null)
            {
                randXPlane = UnityEngine.Random.Range(xPlanePos, xPlanePos + planeWidth);
                randZPlane = UnityEngine.Random.Range(zPlanePos, zPlanePos + planeLength);
                yValPlane = 0;
                yValPlane = yValPlane + yOffset;

                GameObject objInstancePlane = (GameObject)Instantiate(prefabToSpawn,
                new Vector3(randXPlane, yValPlane, randZPlane), Quaternion.identity);

                objInstancePlane.name = "Plane Spawned";

                if (isParent)
                {
                    objInstancePlane.transform.parent = spawnedPlaneObjectsParent.transform;
                }
            }

            if (duration > 0)
            {
                yield return new WaitForSeconds(duration);
            }
        }
    }

    private void Update()
    {
        SpawnThroughPlane();
    }
    public void SpawnThroughPlane()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
            {
                cube = Instantiate(prefabToSpawn);
                cube.transform.position = hit.point;

                float heightFromTerrain = Terrain.activeTerrain.SampleHeight(hit.point);
                var posy = hit.point.y;
                posy -= heightFromTerrain;
                var newpos = new Vector3(hit.point.x, hit.point.y - posy, hit.point.z);
                Instantiate(prefabToSpawn, newpos, Quaternion.identity);
            }
        }
    }
}
</code>```

Body:
I have a  plane and when i click on the plane it's spawning objects on the plane area and on the terrain ground.

but i want to do that if the plane or part of it is out of the terrain area that it will disable the spawning part.

This screenshot show the plane above the terrain.

and this screenshot where the plane is out of the terrain area but i can still click on the plane and spawn objects.

This is the spawn objects script :

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class SpawnObjects : MonoBehaviour
{
    public GameObject prefabToSpawn;
    public Terrain terrain;
    public CustomPlane plane;
    public GameObject spawnedTerrainObjectsParent;
    public GameObject spawnedPlaneObjectsParent;
    public bool go = false;
    public int numberOfObjects;
    public float duration;
    public float yOffset = 0.5f;
    public bool isParent = true;

    private float terrainWidth;
    private float terrainLength;
    private float xTerrainPos;
    private float zTerrainPos;

    private float planeWidth;
    private float planeLength;
    private float xPlanePos;
    private float zPlanePos;

    private float yValTerrain;
    private float yValPlane;

    private float randXTerrain;
    private float randZTerrain;

    private float randXPlane;
    private float randZPlane;

    private GameObject cube;

    private Collider terrainCollider;
    void Awake()
    {
        if (terrain != null)
        {
            //Get terrain size
            terrainWidth = terrain.terrainData.size.x;
            terrainLength = terrain.terrainData.size.z;

            //Get terrain position
            xTerrainPos = terrain.transform.position.x;
            zTerrainPos = terrain.transform.position.z;

            terrainCollider = terrain.GetComponent<Collider>();
        }

        if (plane != null)
        {
            planeWidth = plane.width;
            planeLength = plane.length;
            xPlanePos = plane.transform.position.x;
            zPlanePos = plane.transform.position.z;
        }

        if (isParent)
        {
            if(spawnedTerrainObjectsParent == null)
            {
                spawnedTerrainObjectsParent = GameObject.Find("Spawned Terrain Parent");
            }

            if(spawnedPlaneObjectsParent == null)
            {
                spawnedPlaneObjectsParent = GameObject.Find("Spawned Plane Parent");
            }
        }

        Camera.main.transform.position =
            new Vector3(plane.GetComponent<Renderer>().bounds.center.x, 635,
            plane.GetComponent<Renderer>().bounds.center.z);

        if (go)
        {
            StartCoroutine(Generate());
        }
    }

    IEnumerator Generate()
    {
        //Generate the Prefab on the generated position
        for (int i = 0; i < numberOfObjects; i++)
        {
            if (terrain != null)
            {
                //Generate random x,z,y position on the terrain
                randXTerrain = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
                randZTerrain = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
                yValTerrain = Terrain.activeTerrain.SampleHeight(new Vector3(randXTerrain, 0, randZTerrain));
                yValTerrain = yValTerrain + yOffset;

                GameObject objInstanceTerrain = (GameObject)Instantiate(prefabToSpawn,
                new Vector3(randXTerrain, yValTerrain, randZTerrain), Quaternion.identity);

                objInstanceTerrain.name = "Terrain Spawned";

                if (isParent)
                {
                    objInstanceTerrain.transform.parent = spawnedTerrainObjectsParent.transform;
                }
            }

            if (plane != null)
            {
                randXPlane = UnityEngine.Random.Range(xPlanePos, xPlanePos + planeWidth);
                randZPlane = UnityEngine.Random.Range(zPlanePos, zPlanePos + planeLength);
                yValPlane = 0;
                yValPlane = yValPlane + yOffset;

                GameObject objInstancePlane = (GameObject)Instantiate(prefabToSpawn,
                new Vector3(randXPlane, yValPlane, randZPlane), Quaternion.identity);

                objInstancePlane.name = "Plane Spawned";

                if (isParent)
                {
                    objInstancePlane.transform.parent = spawnedPlaneObjectsParent.transform;
                }
            }

            if (duration > 0)
            {
                yield return new WaitForSeconds(duration);
            }
        }
    }

    private void Update()
    {
        SpawnThroughPlane();
    }
    public void SpawnThroughPlane()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
            {
                cube = Instantiate(prefabToSpawn);
                cube.transform.position = hit.point;

                float heightFromTerrain = Terrain.activeTerrain.SampleHeight(hit.point);
                var posy = hit.point.y;
                posy -= heightFromTerrain;
                var newpos = new Vector3(hit.point.x, hit.point.y - posy, hit.point.z);
                Instantiate(prefabToSpawn, newpos, Quaternion.identity);
            }
        }
    }
}


问:
when ASP.NET core web API app connecting call WCF service API, how to authenticate
I am developing a C# backend app using ASP.NET core web API application. Inside this API, I need to call some API(WCF SOAP service) from database. For this WCF service, we were provided pre-built .dll, so will not use adding service reference. When calling these WCF service, have to pass my windows credential to let WCF service know I am a qualified user before use the service. Now I am stuck on how I can pass my credential to this WCF. What is the right architecture to use.(Screen shot is showing some endpoint of the WCF service)
Adding some background info, In our react frontend, will call these ASP.NET core web API to get data back from WCF, and show it on frontend.
I am new to C# and .Net core. Please share some insight. Thanks a lot. Happy New Year!!!

I did the ASP.NET core web API part. but could not figure out the right way to authenticate when connecting to WCF API.


问:
Do you know how to convert from bases in python?

How do you convert base 12 to base 10 in Python 3 and the other way around too? (from 10 to 12)

I wrote this code to make a list of numbers in base 4, but the code never executes and eventually has a timeout error. Any ideas on how to fix it? It also identifies the mode and counts the frequency of the mode. The program should start at 1 and print the next 21 numbers in base 4 and then do the mode stuff.

```<code>while num > 0:
        if start in yes:
          list4.append(start)
          start += 1
          num -= 1
        if start not in yes:
          num += 1
    new_4 = ''.join([str(n) for n in list4])
    print(statistics.mode(new_4))
    count_m = new_4.count(statistics.mode(new_4))
    print(count_m)

</code>```

Comment any other questions you may have!

Body:
How do you convert base 12 to base 10 in Python 3 and the other way around too? (from 10 to 12)

I wrote this code to make a list of numbers in base 4, but the code never executes and eventually has a timeout error. Any ideas on how to fix it? It also identifies the mode and counts the frequency of the mode. The program should start at 1 and print the next 21 numbers in base 4 and then do the mode stuff.

while num > 0:
        if start in yes:
          list4.append(start)
          start += 1
          num -= 1
        if start not in yes:
          num += 1
    new_4 = ''.join([str(n) for n in list4])
    print(statistics.mode(new_4))
    count_m = new_4.count(statistics.mode(new_4))
    print(count_m)

Comment any other questions you may have!


问:
Detect how close the iPhone is to the Mac using BLE?
I'm trying to detect if the iPhone is placed close enough to the Mac using BLE signal strength. I am using the following code to detect if the iPhone is in range(and it works), but I don't know how to detect if the iPhone is 'close enough'. Like -30db for instance. Does anyone know how I can achieve that? Any comments/discussions are welcome :)</p>
```<code>import SwiftUI
import AVFoundation
import IOBluetooth
import CoreBluetooth
 import Foundation

  class BluetoothSearchDelegate : NSObject, IOBluetoothDeviceInquiryDelegate {
func deviceInquiryDeviceFound(_ sender: IOBluetoothDeviceInquiry, device: IOBluetoothDevice) {
    print("Found Device \(device.name ?? "nil")")
   }

func deviceInquiryStarted(_ sender: IOBluetoothDeviceInquiry) {
    print("started")
}

func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
    print("completed")
}
   }

 struct ContentView: View {
let delegate = BluetoothSearchDelegate()
let inquiry: IOBluetoothDeviceInquiry

init() {
    self.inquiry = IOBluetoothDeviceInquiry(delegate: delegate)
}

var body: some View {
    Button("Bluetooth") {
        inquiry.start()
    }
}
 }
</code>```

Body:
I'm trying to detect if the iPhone is placed close enough to the Mac using BLE signal strength. I am using the following code to detect if the iPhone is in range(and it works), but I don't know how to detect if the iPhone is 'close enough'. Like -30db for instance. Does anyone know how I can achieve that? Any comments/discussions are welcome :)

import SwiftUI
import AVFoundation
import IOBluetooth
import CoreBluetooth
 import Foundation

  class BluetoothSearchDelegate : NSObject, IOBluetoothDeviceInquiryDelegate {
func deviceInquiryDeviceFound(_ sender: IOBluetoothDeviceInquiry, device: IOBluetoothDevice) {
    print("Found Device \(device.name ?? "nil")")
   }

func deviceInquiryStarted(_ sender: IOBluetoothDeviceInquiry) {
    print("started")
}

func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) {
    print("completed")
}
   }

 struct ContentView: View {
let delegate = BluetoothSearchDelegate()
let inquiry: IOBluetoothDeviceInquiry

init() {
    self.inquiry = IOBluetoothDeviceInquiry(delegate: delegate)
}

var body: some View {
    Button("Bluetooth") {
        inquiry.start()
    }
}
 }


Title: I have a dataset and when I try to find the correlation of this dataset like df.corr() it the output is (_) in jupyter, NaN in spyder

Body:
My dataset looks like this, and my code is:

import pandas as pd

df = pd.read_csv("Admission_data.csv")
correlations = df.corr()
correlations

admit   gre gpa rank
0.0 380.0   3.609999895095825   3.0
1.0 660.0   3.6700000762939453  3.0
1.0 800.0   4.0 1.0
1.0 640.0   3.190000057220459   4.0
0.0 520.0   2.930000066757202   4.0
1.0 760.0   3.0 2.0
1.0 560.0   2.9800000190734863  1.0
0.0 400.0   3.0799999237060547  2.0
1.0 540.0   3.390000104904175   3.0
0.0 700.0   3.9200000762939453  2.0
0.0 800.0   4.0 4.0
0.0 440.0   3.2200000286102295  1.0
1.0 760.0   4.0 1.0
0.0 700.0   3.0799999237060547  2.0
1.0 700.0   4.0 1.0
0.0 480.0   3.440000057220459   3.0
0.0 780.0   3.869999885559082   4.0
0.0 360.0   2.559999942779541   3.0
0.0 800.0   3.75    2.0
1.0 540.0   3.809999942779541   1.0
0.0 500.0   3.1700000762939453  3.0
1.0 660.0   3.630000114440918   2.0
0.0 600.0   2.819999933242798   4.0
0.0 680.0   3.190000057220459   4.0
1.0 760.0   3.3499999046325684  2.0
1.0 800.0   3.6600000858306885  1.0
1.0 620.0   3.609999895095825   1.0
1.0 520.0   3.740000009536743   4.0
1.0 780.0   3.2200000286102295  2.0
0.0 520.0   3.2899999618530273  1.0
0.0 540.0   3.7799999713897705  4.0
0.0 760.0   3.3499999046325684  3.0
0.0 600.0   3.4000000953674316  3.0
1.0 800.0   4.0 3.0
0.0 360.0   3.140000104904175   1.0
0.0 400.0   3.049999952316284   2.0
0.0 580.0   3.25    1.0
0.0 520.0   2.9000000953674316  3.0
1.0 500.0   3.130000114440918   2.0
1.0 520.0   2.680000066757202   3.0
0.0 560.0   2.4200000762939453  2.0
1.0 580.0   3.319999933242798   2.0
1.0 600.0   3.1500000953674316  2.0
0.0 500.0   3.309999942779541   3.0
0.0 700.0   2.940000057220459   2.0
1.0 460.0   3.450000047683716   3.0
1.0 580.0   3.4600000381469727  2.0
0.0 500.0   2.9700000286102295  4.0
0.0 440.0   2.4800000190734863  4.0
0.0 400.0   3.3499999046325684  3.0
0.0 640.0   3.859999895095825   3.0
0.0 440.0   3.130000114440918   4.0
0.0 740.0   3.369999885559082   4.0
1.0 680.0   3.2699999809265137  2.0
0.0 660.0   3.3399999141693115  3.0
1.0 740.0   4.0 3.0
0.0 560.0   3.190000057220459   3.0
0.0 380.0   2.940000057220459   3.0
0.0 400.0   3.6500000953674316  2.0
0.0 600.0   2.819999933242798   4.0
1.0 620.0   3.180000066757202   2.0
0.0 560.0   3.319999933242798   4.0
0.0 640.0   3.6700000762939453  3.0
1.0 680.0   3.8499999046325684  3.0
0.0 580.0   4.0 3.0
0.0 600.0   3.5899999141693115  2.0
0.0 740.0   3.619999885559082   4.0
0.0 620.0   3.299999952316284   1.0
0.0 580.0   3.690000057220459   1.0
0.0 800.0   3.7300000190734863  1.0
0.0 640.0   4.0 3.0
0.0 300.0   2.9200000762939453  4.0
0.0 480.0   3.390000104904175   4.0
0.0 580.0   4.0 2.0
0.0 720.0   3.450000047683716   4.0
0.0 720.0   4.0 3.0
0.0 560.0   3.359999895095825   3.0
1.0 800.0   4.0 3.0
0.0 540.0   3.119999885559082   1.0
1.0 620.0   4.0 1.0
0.0 700.0   2.9000000953674316  4.0
0.0 620.0   3.069999933242798   2.0
0.0 500.0   2.7100000381469727  2.0
0.0 380.0   2.9100000858306885  4.0
1.0 500.0   3.5999999046325684  3.0
0.0 520.0   2.9800000190734863  2.0
0.0 600.0   3.319999933242798   2.0
0.0 600.0   3.4800000190734863  2.0
0.0 700.0   3.2799999713897705  1.0
1.0 660.0   4.0 2.0
0.0 700.0   3.8299999237060547  2.0
1.0 720.0   3.640000104904175   1.0
0.0 800.0   3.9000000953674316  2.0
0.0 580.0   2.930000066757202   2.0
1.0 660.0   3.440000057220459   2.0
0.0 660.0   3.3299999237060547  2.0
0.0 640.0   3.5199999809265137  4.0
0.0 480.0   3.569999933242798   2.0
0.0 700.0   2.880000114440918   2.0
0.0 400.0   3.309999942779541   3.0

I tried correlations methods, method='pearson' or numeric_value=True etc.. but nothing works


问:
Missing Environment Variables in VS Code Terminal Process
I have an environment variable called DEBUG, whose value is the string "true". I'm reading this variable from within a Node process (itself a child process of cmd.exe) via process.env.DEBUG:

Note: I am using nvm for Windows, and have tested versions 14.18.1 and 18.12.1 of Node. Both versions yielded the same results and experience.

As you can see, this works as expected. Likewise, PowerShell also works as expected.

When testing the same scenario from within a terminal in VS Code, undefined is returned:

To simplify things, I have checked that no scripts are loaded which would remove the environment variable, no plugins are installed which would alter the variable, and no difference is made when using a different terminal within VS Code.

After running into a dead-end, I turned my attention to the process Environment, to see where the DEBUG variable may be getting dropped. To proceed, I used both Process Monitor, and Process Explorer. When I launch Visual Studio Code (from explorer.exe), I can confirm that it has the variable in its Environment.

The process tree of Code.exe instances and the inclusion of the DEBUG variable in their respective Environments is as follows:

Process
Type
DEBUG Inclusion

Code.exe
none/parent
true

› Code.exe
crashpad-handler
true

› Code.exe
gpu-process
true

› Code.exe
utility
true

› Code.exe
renderer
true

› Code.exe
renderer
true

› Code.exe
ptyHost
false

As you can see, the variable is present in the environments of all child processes, with the exception of the --type=ptyHost child process. That process has a couple other runtime args (paths truncated):

"C:\…\Code.exe"
  --ms-enable-electron-run-as-node
  "c:\…\resources\app\out\bootstrap-fork"
  --type=ptyHost
  --logsPath C:\…\AppData\Roaming\Code\logs\20221230T172335
```

It is unclear to me why some environment variables are not present for the ptyHost process. In my frustration, I even created a second environment variable named DEEBUG, and it too was not present under the same circumstances.

I'm aware that alternative approaches would arguably be more ideal, such as using a tool like dotenv, but I also feel as though there is a valuable lesson just around the corner here for me.

Body:
I have an environment variable called DEBUG, whose value is the string "true". I'm reading this variable from within a Node process (itself a child process of cmd.exe) via process.env.DEBUG:

Note: I am using nvm for Windows, and have tested versions 14.18.1 and 18.12.1 of Node. Both versions yielded the same results and experience.

As you can see, this works as expected. Likewise, PowerShell also works as expected.

When testing the same scenario from within a terminal in VS Code, undefined is returned:

To simplify things, I have checked that no scripts are loaded which would remove the environment variable, no plugins are installed which would alter the variable, and no difference is made when using a different terminal within VS Code.

After running into a dead-end, I turned my attention to the process Environment, to see where the DEBUG variable may be getting dropped. To proceed, I used both Process Monitor, and Process Explorer. When I launch Visual Studio Code (from explorer.exe), I can confirm that it has the variable in its Environment.

The process tree of Code.exe instances and the inclusion of the DEBUG variable in their respective Environments is as follows:

Process
Type
DEBUG Inclusion

Code.exe
none/parent
true

› Code.exe
crashpad-handler
true

› Code.exe
gpu-process
true

› Code.exe
utility
true

› Code.exe
renderer
true

› Code.exe
renderer
true

› Code.exe
ptyHost
false

As you can see, the variable is present in the environments of all child processes, with the exception of the --type=ptyHost child process. That process has a couple other runtime args (paths truncated):

"C:\…\Code.exe"
  --ms-enable-electron-run-as-node
  "c:\…\resources\app\out\bootstrap-fork"
  --type=ptyHost
  --logsPath C:\…\AppData\Roaming\Code\logs\20221230T172335

It is unclear to me why some environment variables are not present for the ptyHost process. In my frustration, I even created a second environment variable named DEEBUG, and it too was not present under the same circumstances.

I'm aware that alternative approaches would arguably be more ideal, such as using a tool like dotenv, but I also feel as though there is a valuable lesson just around the corner here for me.