问:
i have no errors but i'm getting a black screen when i try to render with three.js
i am getting a black screen without any errors when i try to load my three.js project in React but it is working in normal html and css when i tested it.
i have checked everything within my power and i can't find the problem, I'm new to three.js and this code was from codepen that i was practicing with, i don't fully understand everything in it. please help me
see my code below`

```<code>import React, { Suspense } from "react";
import { useEffect, useRef } from "react";
import * as THREE from "three";
import { Helmet } from "react-helmet";
import Stats from "three/addons/libs/stats.module.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";

const Parallax = () => {

  useEffect(() => {
    const pic_url =
      "https://images.unsplash.com/photo-1541585452861-0375331f10bf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=" +
      window.innerHeight / 5 +
      "&q=0";
    const easeOutSine = (t, b, c, d) => {
      return c * Math.sin((t / d) * (Math.PI / 2)) + b;
    };

    class PositionMouseInCanvas {
      constructor(scene, group, camera) {
        this.scene = scene;
        this.group = group;
        this.camera = camera;
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2(0, 0);

        this.initPlane();
        this.initTouch();
      }

      initPlane() {
        const planeGeo = new THREE.PlaneGeometry(1, 1, 32);
        const planeMat = new THREE.MeshBasicMaterial({
          color: "#000",
          side: THREE.DoubleSide,
        });

        this.plane = new THREE.Mesh(planeGeo, planeMat);
        this.group.add(this.plane);

        this.canvas = document.querySelector("#interactive-particles");
        this.cursor = document.querySelector(".cursor");

        this.boundCanvas = this.getBound(this.canvas);
        this.boundCursor = this.getBound(this.cursor);

        this.canvas.addEventListener("mousemove", (e) => this.onMouseMove(e));
        window.addEventListener("resize", () => this.onResize());
      }

      getBound(el) {
        const bound = el.getBoundingClientRect();
        return {
          w: bound.width,
          h: bound.height,
          left: bound.left,
          top: bound.top,
        };
      }

      onResize() {
        this.boundCanvas = this.getBound(this.canvas);
        this.boundCursor = this.getBound(this.cursor);
      }

      initTouch() {
        if (!this.touch) this.touch = new TouchTexture();

        const uniforms = this.group.children[0].material.uniforms;
        uniforms.uTouch.value = this.touch.texture;
      }

      onMouseMove(e) {
        const t = e.touches ? e.touches[0] : e;
        const touch = { x: t.clientX, y: t.clientY };

        this.mouse.x = (touch.x / this.boundCanvas.w) * 2 - 1;
        this.mouse.y = -(touch.y / this.boundCanvas.h) * 2 + 1;
        this.raycaster.setFromCamera(this.mouse, this.camera);

        const intersects = this.raycaster.intersectObjects([this.plane]);

        if (intersects.length > 0) {
          this.touch.addTouch(intersects[0].uv);
        }

        TweenMax.to(this.cursor, 0.5, {
          x: touch.x - this.boundCursor.w / 2,
          y: touch.y - this.boundCursor.h / 2,
        });
      }

      update() {
        if (this.touch) this.touch.update();
      }
    }

    // Carga modelos 3D externos o texturas dependiendo de la opcion
    const textureLoader = (opt) =>
      opt === "obj" ? new OBJLoader() : new THREE.TextureLoader();

    class WebGL {
      constructor() {
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.camera = new THREE.PerspectiveCamera(
          45,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
        );
        this.scene = new THREE.Scene();
        this.group = new THREE.Group();
        this.clock = new THREE.Clock();

        //this.helper = new Helper(this.scene);
        this.loader = textureLoader();

        this.update = this.update.bind(this);
      }

      // Coloca el objeto renderer dentro del DOM
      // Instaciamos la clase OrbitControls para mover la camara
      // Agrega la camara y el objeto group dentro de la escena
      init() {
        const _contentCanvas = document.querySelector("#content-canvas");

        this.renderer.domElement.id = "interactive-particles";

        this.renderer.setPixelRatio(devicePixelRatio);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;

        this.scene.add(this.camera);
        this.scene.add(this.group);

        this.camera.position.set(0, 0, 1);
        this.camera.lookAt(this.scene.position);

        _contentCanvas.appendChild(this.renderer.domElement);

        this.initFn();
      }

      // Inicia todos los metodos que serviran para crear nuestro espacio y objetos
      initFn() {
        this.loader.load(pic_url, (texture) => {
          this.createMesh(texture);
          this.show();

          this.positionMouse = new PositionMouseInCanvas(
            this.scene,
            this.group,
            this.camera
          );

          this.update();

          window.addEventListener("resize", this.onResize);
        });
      }

      // Crea el objeto (geometria, material y malla) para luego agregarlo al escenario
      createMesh(texture) {
        this.width = texture.image.width;
        this.height = texture.image.height;

        this.uniforms = {
          uTime: { value: 0 },
          uRandom: { value: 1.0 },
          uDepth: { value: 2.0 },
          uSize: { value: 0.0 },
          uTextureSize: { value: new THREE.Vector2(this.width, this.height) },
          uTexture: { value: texture },
          uMouse: { value: new THREE.Vector3() },
          uTouch: { value: null },
        };

        texture.minFilter = THREE.LinearFilter;
        texture.magFilter = THREE.LinearFilter;
        texture.format = THREE.RGBAFormat;

        this.numPoints = this.width * this.height;
        const threshold = 34;
        const [numVisible, originalColors] = this.discard(texture, threshold);

        const _particlesMat = new THREE.RawShaderMaterial({
          uniforms: this.uniforms,
          vertexShader: document.getElementById("vertexShader").textContent,
          fragmentShader: document.getElementById("fragmentShader").textContent,
          depthTest: false,
          transparent: true,
          side: THREE.DoubleSide,
        });

        const bufferGeometry = new THREE.InstancedBufferGeometry();
        const planeGeo = new THREE.PlaneGeometry();

        bufferGeometry.copy(planeGeo);

        const indices = new Uint16Array(numVisible);
        const offsets = new Float32Array(numVisible * 3);
        const angles = new Float32Array(numVisible);

        for (let i = 0, j = 0; i < this.numPoints; i++) {
          if (originalColors[i * 4] <= threshold) continue;

          offsets[j * 3 + 0] = i % this.width;
          offsets[j * 3 + 1] = Math.floor(i / this.width);

          indices[j] = i;

          angles[j] = Math.random() * Math.PI;

          j++;
        }

        bufferGeometry.setAttribute(
          "pindex",
          new THREE.InstancedBufferAttribute(indices, 1, false)
        );
        bufferGeometry.setAttribute(
          "offset",
          new THREE.InstancedBufferAttribute(offsets, 3, false)
        );
        bufferGeometry.setAttribute(
          "angle",
          new THREE.InstancedBufferAttribute(angles, 1, false)
        );

        this.particlesMesh = new THREE.Mesh(bufferGeometry, _particlesMat);

        this.particlesMesh.position.z -= 270;

        this.group.add(this.particlesMesh);
      }

      discard(texture, threshold) {
        let numVisible = 0;
        let originalColors = null;

        const img = texture.image;
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        canvas.width = this.width;
        canvas.height = this.height;
        ctx.scale(1, -1); // flip y
        ctx.drawImage(img, 0, 0, this.width, this.height * -1);

        const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        originalColors = Float32Array.from(imgData.data);

        for (var i = 0; i < this.numPoints; i++) {
          if (originalColors[i * 4] > threshold) numVisible++;
        }

        return [numVisible, originalColors];
      }

      // Actualiza cualquier cambio, para luego representarlo en el canvas
      update() {
        this.renderer.setAnimationLoop(() => {
          const time = this.clock.getElapsedTime() * 0.5;

          //this.particlesMesh.material.uniforms.uTime.value = time;

          if (this.resizeRendererToDisplaySize(this.renderer)) {
            const canvas = this.renderer.domElement;
            this.camera.aspect = canvas.clientWidth / canvas.clientHeight;
            this.camera.updateProjectionMatrix();
          }

          this.positionMouse.update();

          this.render();
        });

        requestAnimationFrame(this.update);
      }

      show(time = 1.0) {
        TweenLite.fromTo(
          this.particlesMesh.material.uniforms.uSize,
          time,
          { value: 0.5 },
          { value: 1.5 }
        );
        TweenLite.to(this.particlesMesh.material.uniforms.uRandom, time, {
          value: 2.0,
        });
        TweenLite.fromTo(
          this.particlesMesh.material.uniforms.uDepth,
          time * 1.5,
          { value: 40.0 },
          { value: 4.0 }
        );
      }

      // Rescala el canvas y escenario
      resizeRendererToDisplaySize(renderer) {
        const canvas = renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        const needResize = canvas.width !== width || canvas.height !== height;
        if (needResize) {
          renderer.setSize(width, height, false);
        }
        return needResize;
      }

      // Renderiza nuestro escenario
      render() {
        this.renderer.render(this.scene, this.camera);
      }
    }

    class TouchTexture {
      constructor(parent) {
        this.parent = parent;
        this.size = 64;
        this.maxAge = 120;
        this.radius = 0.15;
        this.trail = [];
        this.initTexture();
      }

      initTexture() {
        this.canvas = document.createElement("canvas");
        this.canvas.width = this.size;
        this.canvas.height = this.size;

        this.ctx = this.canvas.getContext("2d");
        this.ctx.fillStyle = "white";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.texture = new THREE.Texture(this.canvas);

        this.canvas.id = "touchTexture";
      }

      update(delta) {
        this.clear();
        // age points
        this.trail.forEach((point, i) => {
          point.age++;
          // remove old
          if (point.age > this.maxAge) {
            this.trail.splice(i, 1);
          }
        });

        this.trail.forEach((point, i) => {
          this.drawTouch(point);
        });

        this.texture.needsUpdate = true;
      }

      clear() {
        this.ctx.fillStyle = "black";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      }

      addTouch(point) {
        let force = 0;
        const last = this.trail[this.trail.length - 1];

        if (last) {
          const dx = last.x - point.x;
          const dy = last.y - point.y;
          const dd = dx * dx + dy * dy;
          force = Math.min(dd * 10000, 1);
        }
        this.trail.push({ x: point.x, y: point.y, age: 0, force });
      }

      drawTouch(point) {
        const pos = {
          x: point.x * this.size,
          y: (1 - point.y) * this.size,
        };

        let intensity = 1;
        if (point.age < this.maxAge * 0.3) {
          intensity = easeOutSine(point.age / (this.maxAge * 0.3), 0, 1, 1);
        } else {
          intensity = easeOutSine(
            1 - (point.age - this.maxAge * 0.3) / (this.maxAge * 0.7),
            0,
            1,
            1
          );
        }

        intensity *= point.force;

        const radius = this.size * this.radius * intensity;

        const grd = this.ctx.createRadialGradient(
          pos.x,
          pos.y,
          radius * 0.25,
          pos.x,
          pos.y,
          radius
        );
        grd.addColorStop(0, `rgba(255, 255, 255, 0.2)`);
        grd.addColorStop(1, "rgba(0, 0, 0, 0.0)");

        this.ctx.beginPath();
        this.ctx.fillStyle = grd;
        this.ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
        this.ctx.fill();
      }
    }

    const webgl = new WebGL();
    webgl.init();
  }, []);

  return (
    <>
      <div className="content">
        <div id="content-canvas" ref={contentCanvas}></div>
        <div className="cursor">
          <div className="pointer"></div>
        </div>
      </div>

      <script id="vertexShader" type="f">{`
  #define TAU 6.28318530718

      precision highp float;

      attribute float pindex;
      attribute vec3 position;
      attribute vec3 offset;
      attribute vec2 uv;
      attribute float angle;

      uniform mat4 modelViewMatrix;
      uniform mat4 projectionMatrix;

      uniform float uTime;
      uniform float uRandom;
      uniform float uDepth;
      uniform float uSize;
      uniform vec3 uMouse;
      uniform vec2 uTextureSize;
      uniform sampler2D uTexture;
      uniform sampler2D uTouch;

      varying vec2 vPUv;
      varying vec2 vUv;

      // Description : Array and textureless GLSL 2D simplex noise function.
      //      Author : Ian McEwan, Ashima Arts.
      //  Maintainer : ijm
      //     Lastmod : 20110822 (ijm)
      //     License : Copyright (C) 2011 Ashima Arts. All rights reserved.
      //               Distributed under the MIT License. See LICENSE file.
      //               https://github.com/ashima/webgl-noise
      //

      vec3 mod289_1_0(vec3 x) {
        return x - floor(x * (1.0 / 289.0)) * 289.0;
      }

      vec2 mod289_1_0(vec2 x) {
        return x - floor(x * (1.0 / 289.0)) * 289.0;
      }

      vec3 permute_1_1(vec3 x) {
        return mod289_1_0(((x*34.0)+1.0)*x);
      }

      float snoise_1_2(vec2 v){
        const vec4 C = vec4(0.211324865405187,  // (3.0-sqrt(3.0))/6.0
                            0.366025403784439,  // 0.5*(sqrt(3.0)-1.0)
                           -0.577350269189626,  // -1.0 + 2.0 * C.x
                            0.024390243902439); // 1.0 / 41.0
      // First corner
        vec2 i  = floor(v + dot(v, C.yy) );
        vec2 x0 = v -   i + dot(i, C.xx);

      // Other corners
        vec2 i1;
        //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
        //i1.y = 1.0 - i1.x;
        i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
        // x0 = x0 - 0.0 + 0.0 * C.xx ;
        // x1 = x0 - i1 + 1.0 * C.xx ;
        // x2 = x0 - 1.0 + 2.0 * C.xx ;
        vec4 x12 = x0.xyxy + C.xxzz;
        x12.xy -= i1;

      // Permutations
        i = mod289_1_0(i); // Avoid truncation effects in permutation
        vec3 p = permute_1_1( permute_1_1( i.y + vec3(0.0, i1.y, 1.0 ))
          + i.x + vec3(0.0, i1.x, 1.0 ));

        vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
        m = m*m ;
        m = m*m ;

      // Gradients: 41 points uniformly over a line, mapped onto a diamond.
      // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)

        vec3 x = 2.0 * fract(p * C.www) - 1.0;
        vec3 h = abs(x) - 0.5;
        vec3 ox = floor(x + 0.5);
        vec3 a0 = x - ox;

      // Normalise gradients implicitly by scaling m
      // Approximation of: m *= inversesqrt( a0*a0 + h*h );
        m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );

      // Compute final noise value at P
        vec3 g;
        g.x  = a0.x  * x0.x  + h.x  * x0.y;
        g.yz = a0.yz * x12.xz + h.yz * x12.yw;
        return 130.0 * dot(m, g);
      }

      float random(float n){
          return fract(sin(n) * 43758.5453123);
      }

      void main() {
            vUv = uv;

          // particle uv
          vec2 puv = offset.xy / uTextureSize;
          vPUv = puv;

          // pixel color
          vec4 colA = texture2D(uTexture, puv);
          float grey = dot(colA.rgb, vec3(0.299, 0.587, 0.114));

          // displacement
          vec3 displaced = offset;
          // randomise
          displaced.xy += vec2(random(pindex) - 0.5, random(offset.x + pindex) - 0.5) * uRandom;
          float rndz = (random(pindex) + snoise_1_2(vec2(pindex * 0.5, uTime * 0.5)));
          displaced.z += rndz * (random(pindex) * 2.0 * uDepth);
          // center
          displaced.xy -= uTextureSize * 0.5;

          // touch
          float t = texture2D(uTouch, puv).r;
          displaced.z += t * 20.0 * rndz;
          displaced.x += cos(angle) * t * 20.0 * rndz;
          displaced.y += sin(angle) * t * 20.0 * rndz;

          // particle size
          float psize = (snoise_1_2(vec2(uTime, pindex) * 0.5) + 2.0);
          psize *= max(grey, 0.2);
          psize *= uSize;

          vec3 dir = position - uMouse * .5;
          float dist = length(dir);
          float range = .5;

          if(dist < range){
            float ratio = clamp(1. - dist / range, 0., 1.);
            displaced -= dir * ratio * 10.;
          }

          displaced += position * psize;

          // final position
          vec4 mvPosition = modelViewMatrix * vec4(displaced, 1.0);
          vec4 finalPosition = projectionMatrix * mvPosition;

          gl_Position = finalPosition;
      }
`}</script>
      <script id="fragmentShader" type="f">
        {" "}
        {`
  precision highp float;

      uniform sampler2D uTexture;

      varying vec2 vPUv;
      varying vec2 vUv;

      void main() {
        vec4 color = vec4(0.0);
        vec2 uv = vUv;
        vec2 puv = vPUv;

        // pixel color
        vec4 colA = texture2D(uTexture, puv);

        // greyscale
        float grey = dot(colA.rgb, vec3(0.299, 0.587, 0.114));
        vec4 colB = vec4(vec3(grey), 1.0);

        // circle
        float border = 0.5;
        float radius = 0.5;
        float dist =  1. - distance(uv, vec2(0.5)) / radius;
        float t = smoothstep(0.0, border, dist);

        // final color
        color = colB;
        color.a = t;

        gl_FragColor = color;
      } `}
      </script>
    </>
  );
};

export default Parallax;

</code>```

`

i was expecting a rendered image with interactive particles

Body:
i am getting a black screen without any errors when i try to load my three.js project in React but it is working in normal html and css when i tested it.
i have checked everything within my power and i can't find the problem, I'm new to three.js and this code was from codepen that i was practicing with, i don't fully understand everything in it. please help me
see my code below`

import React, { Suspense } from "react";
import { useEffect, useRef } from "react";
import * as THREE from "three";
import { Helmet } from "react-helmet";
import Stats from "three/addons/libs/stats.module.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";

const Parallax = () => {

  useEffect(() => {
    const pic_url =
      "https://images.unsplash.com/photo-1541585452861-0375331f10bf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=" +
      window.innerHeight / 5 +
      "&q=0";
    const easeOutSine = (t, b, c, d) => {
      return c * Math.sin((t / d) * (Math.PI / 2)) + b;
    };

    class PositionMouseInCanvas {
      constructor(scene, group, camera) {
        this.scene = scene;
        this.group = group;
        this.camera = camera;
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2(0, 0);

        this.initPlane();
        this.initTouch();
      }

      initPlane() {
        const planeGeo = new THREE.PlaneGeometry(1, 1, 32);
        const planeMat = new THREE.MeshBasicMaterial({
          color: "#000",
          side: THREE.DoubleSide,
        });

        this.plane = new THREE.Mesh(planeGeo, planeMat);
        this.group.add(this.plane);

        this.canvas = document.querySelector("#interactive-particles");
        this.cursor = document.querySelector(".cursor");

        this.boundCanvas = this.getBound(this.canvas);
        this.boundCursor = this.getBound(this.cursor);

        this.canvas.addEventListener("mousemove", (e) => this.onMouseMove(e));
        window.addEventListener("resize", () => this.onResize());
      }

      getBound(el) {
        const bound = el.getBoundingClientRect();
        return {
          w: bound.width,
          h: bound.height,
          left: bound.left,
          top: bound.top,
        };
      }

      onResize() {
        this.boundCanvas = this.getBound(this.canvas);
        this.boundCursor = this.getBound(this.cursor);
      }

      initTouch() {
        if (!this.touch) this.touch = new TouchTexture();

        const uniforms = this.group.children[0].material.uniforms;
        uniforms.uTouch.value = this.touch.texture;
      }

      onMouseMove(e) {
        const t = e.touches ? e.touches[0] : e;
        const touch = { x: t.clientX, y: t.clientY };

        this.mouse.x = (touch.x / this.boundCanvas.w) * 2 - 1;
        this.mouse.y = -(touch.y / this.boundCanvas.h) * 2 + 1;
        this.raycaster.setFromCamera(this.mouse, this.camera);

        const intersects = this.raycaster.intersectObjects([this.plane]);

        if (intersects.length > 0) {
          this.touch.addTouch(intersects[0].uv);
        }

        TweenMax.to(this.cursor, 0.5, {
          x: touch.x - this.boundCursor.w / 2,
          y: touch.y - this.boundCursor.h / 2,
        });
      }

      update() {
        if (this.touch) this.touch.update();
      }
    }

    // Carga modelos 3D externos o texturas dependiendo de la opcion
    const textureLoader = (opt) =>
      opt === "obj" ? new OBJLoader() : new THREE.TextureLoader();

    class WebGL {
      constructor() {
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.camera = new THREE.PerspectiveCamera(
          45,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
        );
        this.scene = new THREE.Scene();
        this.group = new THREE.Group();
        this.clock = new THREE.Clock();

        //this.helper = new Helper(this.scene);
        this.loader = textureLoader();

        this.update = this.update.bind(this);
      }

      // Coloca el objeto renderer dentro del DOM
      // Instaciamos la clase OrbitControls para mover la camara
      // Agrega la camara y el objeto group dentro de la escena
      init() {
        const _contentCanvas = document.querySelector("#content-canvas");

        this.renderer.domElement.id = "interactive-particles";

        this.renderer.setPixelRatio(devicePixelRatio);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;

        this.scene.add(this.camera);
        this.scene.add(this.group);

        this.camera.position.set(0, 0, 1);
        this.camera.lookAt(this.scene.position);

        _contentCanvas.appendChild(this.renderer.domElement);

        this.initFn();
      }

      // Inicia todos los metodos que serviran para crear nuestro espacio y objetos
      initFn() {
        this.loader.load(pic_url, (texture) => {
          this.createMesh(texture);
          this.show();

          this.positionMouse = new PositionMouseInCanvas(
            this.scene,
            this.group,
            this.camera
          );

          this.update();

          window.addEventListener("resize", this.onResize);
        });
      }

      // Crea el objeto (geometria, material y malla) para luego agregarlo al escenario
      createMesh(texture) {
        this.width = texture.image.width;
        this.height = texture.image.height;

        this.uniforms = {
          uTime: { value: 0 },
          uRandom: { value: 1.0 },
          uDepth: { value: 2.0 },
          uSize: { value: 0.0 },
          uTextureSize: { value: new THREE.Vector2(this.width, this.height) },
          uTexture: { value: texture },
          uMouse: { value: new THREE.Vector3() },
          uTouch: { value: null },
        };

        texture.minFilter = THREE.LinearFilter;
        texture.magFilter = THREE.LinearFilter;
        texture.format = THREE.RGBAFormat;

        this.numPoints = this.width * this.height;
        const threshold = 34;
        const [numVisible, originalColors] = this.discard(texture, threshold);

        const _particlesMat = new THREE.RawShaderMaterial({
          uniforms: this.uniforms,
          vertexShader: document.getElementById("vertexShader").textContent,
          fragmentShader: document.getElementById("fragmentShader").textContent,
          depthTest: false,
          transparent: true,
          side: THREE.DoubleSide,
        });

        const bufferGeometry = new THREE.InstancedBufferGeometry();
        const planeGeo = new THREE.PlaneGeometry();

        bufferGeometry.copy(planeGeo);

        const indices = new Uint16Array(numVisible);
        const offsets = new Float32Array(numVisible * 3);
        const angles = new Float32Array(numVisible);

        for (let i = 0, j = 0; i < this.numPoints; i++) {
          if (originalColors[i * 4] <= threshold) continue;

          offsets[j * 3 + 0] = i % this.width;
          offsets[j * 3 + 1] = Math.floor(i / this.width);

          indices[j] = i;

          angles[j] = Math.random() * Math.PI;

          j++;
        }

        bufferGeometry.setAttribute(
          "pindex",
          new THREE.InstancedBufferAttribute(indices, 1, false)
        );
        bufferGeometry.setAttribute(
          "offset",
          new THREE.InstancedBufferAttribute(offsets, 3, false)
        );
        bufferGeometry.setAttribute(
          "angle",
          new THREE.InstancedBufferAttribute(angles, 1, false)
        );

        this.particlesMesh = new THREE.Mesh(bufferGeometry, _particlesMat);

        this.particlesMesh.position.z -= 270;

        this.group.add(this.particlesMesh);
      }

      discard(texture, threshold) {
        let numVisible = 0;
        let originalColors = null;

        const img = texture.image;
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        canvas.width = this.width;
        canvas.height = this.height;
        ctx.scale(1, -1); // flip y
        ctx.drawImage(img, 0, 0, this.width, this.height * -1);

        const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        originalColors = Float32Array.from(imgData.data);

        for (var i = 0; i < this.numPoints; i++) {
          if (originalColors[i * 4] > threshold) numVisible++;
        }

        return [numVisible, originalColors];
      }

      // Actualiza cualquier cambio, para luego representarlo en el canvas
      update() {
        this.renderer.setAnimationLoop(() => {
          const time = this.clock.getElapsedTime() * 0.5;

          //this.particlesMesh.material.uniforms.uTime.value = time;

          if (this.resizeRendererToDisplaySize(this.renderer)) {
            const canvas = this.renderer.domElement;
            this.camera.aspect = canvas.clientWidth / canvas.clientHeight;
            this.camera.updateProjectionMatrix();
          }

          this.positionMouse.update();

          this.render();
        });

        requestAnimationFrame(this.update);
      }

      show(time = 1.0) {
        TweenLite.fromTo(
          this.particlesMesh.material.uniforms.uSize,
          time,
          { value: 0.5 },
          { value: 1.5 }
        );
        TweenLite.to(this.particlesMesh.material.uniforms.uRandom, time, {
          value: 2.0,
        });
        TweenLite.fromTo(
          this.particlesMesh.material.uniforms.uDepth,
          time * 1.5,
          { value: 40.0 },
          { value: 4.0 }
        );
      }

      // Rescala el canvas y escenario
      resizeRendererToDisplaySize(renderer) {
        const canvas = renderer.domElement;
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;
        const needResize = canvas.width !== width || canvas.height !== height;
        if (needResize) {
          renderer.setSize(width, height, false);
        }
        return needResize;
      }

      // Renderiza nuestro escenario
      render() {
        this.renderer.render(this.scene, this.camera);
      }
    }

    class TouchTexture {
      constructor(parent) {
        this.parent = parent;
        this.size = 64;
        this.maxAge = 120;
        this.radius = 0.15;
        this.trail = [];
        this.initTexture();
      }

      initTexture() {
        this.canvas = document.createElement("canvas");
        this.canvas.width = this.size;
        this.canvas.height = this.size;

        this.ctx = this.canvas.getContext("2d");
        this.ctx.fillStyle = "white";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.texture = new THREE.Texture(this.canvas);

        this.canvas.id = "touchTexture";
      }

      update(delta) {
        this.clear();
        // age points
        this.trail.forEach((point, i) => {
          point.age++;
          // remove old
          if (point.age > this.maxAge) {
            this.trail.splice(i, 1);
          }
        });

        this.trail.forEach((point, i) => {
          this.drawTouch(point);
        });

        this.texture.needsUpdate = true;
      }

      clear() {
        this.ctx.fillStyle = "black";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      }

      addTouch(point) {
        let force = 0;
        const last = this.trail[this.trail.length - 1];

        if (last) {
          const dx = last.x - point.x;
          const dy = last.y - point.y;
          const dd = dx * dx + dy * dy;
          force = Math.min(dd * 10000, 1);
        }
        this.trail.push({ x: point.x, y: point.y, age: 0, force });
      }

      drawTouch(point) {
        const pos = {
          x: point.x * this.size,
          y: (1 - point.y) * this.size,
        };

        let intensity = 1;
        if (point.age < this.maxAge * 0.3) {
          intensity = easeOutSine(point.age / (this.maxAge * 0.3), 0, 1, 1);
        } else {
          intensity = easeOutSine(
            1 - (point.age - this.maxAge * 0.3) / (this.maxAge * 0.7),
            0,
            1,
            1
          );
        }

        intensity *= point.force;

        const radius = this.size * this.radius * intensity;

        const grd = this.ctx.createRadialGradient(
          pos.x,
          pos.y,
          radius * 0.25,
          pos.x,
          pos.y,
          radius
        );
        grd.addColorStop(0, `rgba(255, 255, 255, 0.2)`);
        grd.addColorStop(1, "rgba(0, 0, 0, 0.0)");

        this.ctx.beginPath();
        this.ctx.fillStyle = grd;
        this.ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
        this.ctx.fill();
      }
    }

    const webgl = new WebGL();
    webgl.init();
  }, []);

  return (
    <>

    </>
  );
};

export default Parallax;

`

i was expecting a rendered image with interactive particles


来源: stackexchange

问:
PyQt5: changing windowsflag from WindowStaysOnBottomHint to WindowStaysOnTopHint
WindowStaysOnBottomHint is a default option when running the program.

```<code>class WindowClass(QWidget, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        flags = Qt.WindowFlags(Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnBottomHint)
        self.setWindowFlags(flags)
</code>```

And I want it to change to WindowStaysOnTopHint with a button, however it is not working properly
This is what I have tried with clicking a menu option

```<code>        onTop.triggered.connect(lambda: self.setWindowFlags(Qt.WindowFlags(Qt.Tool | Qt.FramelessWindowHint  |Qt.WindowStaysOnBottomHint)))
        onTop.triggered.connect(lambda: self.show())
</code>```

The code is just toggling the WindowStaysOnBottomHint instead of changing it to WindowStaysOnTopHint
There is no error displaying while running onTop.triggered.connect()

ContentLicense: CC BY-SA 4.0

Body:
WindowStaysOnBottomHint is a default option when running the program.

class WindowClass(QWidget, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        flags = Qt.WindowFlags(Qt.Tool | Qt.FramelessWindowHint | Qt.WindowStaysOnBottomHint)
        self.setWindowFlags(flags)

And I want it to change to WindowStaysOnTopHint with a button, however it is not working properly
This is what I have tried with clicking a menu option

        onTop.triggered.connect(lambda: self.setWindowFlags(Qt.WindowFlags(Qt.Tool | Qt.FramelessWindowHint  |Qt.WindowStaysOnBottomHint)))
        onTop.triggered.connect(lambda: self.show())

The code is just toggling the WindowStaysOnBottomHint instead of changing it to WindowStaysOnTopHint
There is no error displaying while running onTop.triggered.connect()


Title: In R: run a function through a list of matrices

Body:
Is it possible to run a function through a list of matrices?
The function multkw from the package ULT requires a matrix of the same length as the x variable (data$S_M). I have a list of matrices (my_list) that I want to run through the function. I have provided the data and my list below and also an example for how to run the function with a matrix. Also what I have tried so far and the error.

data

data <- structure(list(ID = c("BLA80", "BLA80", "BLA31", "BLA31", "BLA79",
                      "BLA79", "BLA42", "BLA42", "BLA283", "BLA283"), S_M = c("BEFORE",
                                                                              "AFTER", "BEFORE", "AFTER", "BEFORE", "AFTER", "BEFORE", "AFTER",
                                                                              "BEFORE", "AFTER"), average_Ca = c(1596974.03, 1473014.143, 2586409.745,
                                                                                3682684.657, 2520483.128, 1821912.382, 2721958.618, 2748744.864,
                                                                                1328664.242, 1185459.179), average_Ba = c(16.15156258, 20.09711394,
                                                                                28.90255736, 46.20374139, 19.4043364, 28.08272881, 17.27731536,
                                                                                35.38934084, 12.43289018, 23.52246807), average_Cu = c(1.541614794,
                                                                                1.272199498, 0.605696247, 0.835403944, 1.101976967, 0.968764031,
                                                                                1.627720498, 1.388735396, 0.91716115, 0.936442436), average_K = c(1109.095542,
                                                                                1657.282202, 718.370902, 823.254076, 575.3425151, 1023.087054,
                                                                                580.705691, 1230.217192, 1031.424583, 1511.920228), average_Mg = c(4396.94302,
                                                                                4870.3585, 4947.200358, 5068.28785, 5203.984999, 5071.13643,
                                                                                4479.919729, 5030.887032, 5452.903721, 5553.852132), average_Mn = c(20.83182396,
                                                                                36.80478114, 22.8397099, 40.16526756, 18.38159317, 29.69941914,
                                                                                20.58043487, 43.34693371, 22.41434749, 43.38435577), average_Pb = c(2.55094084,
                                                                                4.660350302, 0.979823896, 4.549917977, 2.601128278, 5.440631199,
                                                                                1.011520964, 5.865883295, 2.943337175, 6.182218068), average_Sr = c(113.8450974,
                                                                                112.6037395, 126.1247052, 112.5135425, 114.8274129, 115.0819017,
                                                                                120.4794982, 126.0247999, 117.5843842, 128.1751451), average_Zn = c(192.731261,
                                                                                199.9528515, 151.0361607, 148.9285955, 174.2455377, 188.3346348,
                                                                                170.5113979, 237.6179019, 173.9556326, 218.6832589), zone_width = c(39.94736842,
                                                                                18.7, 38.42424242, 31.31034483, 53.15789474, 21.35294118, 40.84210526,
                                                                                29.1875, 42.52631579, 15.6)), row.names = c(NA, -10L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))

Code to create list of matrices (my_list) to run through multkw function (y = ...)

x <- c(3,   4,  5,  6,  7,  8,  9,  10, 11, 12)

df1 <- unlist(lapply(seq_along(x), function(k) combn(x, k, paste0, collapse = " , ")))
df1<- as.data.frame(df1)

df1
colnames(df1) <- c("col1")

#filter for 3 or more and always include zone_width
df1 <- df1 %>% filter(str_count(col1, fixed(",")) == 2)
df1

columns_data<- df1

my_list <- apply(
  columns_data,
  1,
  function(i) {
    idx <- strsplit(i, " , ") |>
      unlist() |>
      as.integer()

    data[, idx] |>
      as.matrix() |>
      list()
  }
)

library(tidyverse)
#if you need to install ULT
remotes::install_github("jacobmaugoust/ULT")
library(ULT)
#how to run function on matrix of all variables 3:12 (y = matrix)
multkw(y=data[3:12], data$S_M)

I had originally tried to run through the function with lapply. I created a function with the code below but got this error

Error in FUN(newX[, i], ...) : unimplemented type 'list' in 'greater'

funn <- function(y) {
  result <- multkw(y=y, data$S_M)
}

lapply(my_list, funn)


问:
Yolov5 Error handling if there's no object detected
I load my yolov5 model using this code model = torch.hub.load('ultralytics/yolov5', 'custom', 'C:\Object Detection\yolov5_object_detection\last.pt') and how to do error handling for if there's no object detection for this model?


问:
python asyncio not spawning new thread
I am working on a script to introduce a non blocking async fire and forget call. Thought of using the asyncio for that. I am running a below POC code before get into a full fledge implementation.It appears that the async function is still running on the main thread. Why is the below async function not creating a new thread name/id? I am expecting a new thread id like the threading module generates.

```<code>import asyncio
import threading
from threading import Thread
#Asyncio function
async def async_func():
    print(f'async_func thread name: %s', threading.current_thread().name)
    print(f'async_func thread id: %s', threading.current_thread().ident)
    await asyncio.sleep(1)

# Threading
def non_async_func():
    print(f'non_async_func thread name: %s', threading.current_thread().name)
    print(f'non_async_func thread id: %s', threading.current_thread().ident)

def main():
    print(f'main name: %s', threading.current_thread().name)
    print(f'main id: %s', threading.current_thread().ident)
    asyncio.run(async_func())
    t = Thread(target=non_async_func)
    print(f'main thread name: %s', threading.current_thread().name)
    print(f'main thread id: %s', threading.current_thread().ident)
    t.start()
if __name__ == '__main__':
    main()

</code>```

I am getting the below output:

```<code>main name: %s **MainThread**
main id: %s **4691527168**
**async_func thread name: %s MainThread**
**async_func thread id: %s 4691527168**
main thread name: %s **MainThread**
main thread id: %s **4691527168**
non_async_func thread name: %s **Thread-1 (non_async_func)**
non_async_func thread id: %s **123145474224128**
</code>```

Title: python asyncio not spawning new thread

Body:
I am working on a script to introduce a non blocking async fire and forget call. Thought of using the asyncio for that. I am running a below POC code before get into a full fledge implementation.It appears that the async function is still running on the main thread. Why is the below async function not creating a new thread name/id? I am expecting a new thread id like the threading module generates.

import asyncio
import threading
from threading import Thread
#Asyncio function
async def async_func():
    print(f'async_func thread name: %s', threading.current_thread().name)
    print(f'async_func thread id: %s', threading.current_thread().ident)
    await asyncio.sleep(1)

# Threading
def non_async_func():
    print(f'non_async_func thread name: %s', threading.current_thread().name)
    print(f'non_async_func thread id: %s', threading.current_thread().ident)

def main():
    print(f'main name: %s', threading.current_thread().name)
    print(f'main id: %s', threading.current_thread().ident)
    asyncio.run(async_func())
    t = Thread(target=non_async_func)
    print(f'main thread name: %s', threading.current_thread().name)
    print(f'main thread id: %s', threading.current_thread().ident)
    t.start()
if __name__ == '__main__':
    main()

I am getting the below output:

main name: %s **MainThread**
main id: %s **4691527168**
**async_func thread name: %s MainThread**
**async_func thread id: %s 4691527168**
main thread name: %s **MainThread**
main thread id: %s **4691527168**
non_async_func thread name: %s **Thread-1 (non_async_func)**
non_async_func thread id: %s **123145474224128**


问:
Conditionally defining a PHP function using function_exists () and getting an error
I'm using PHP's function_exists() in name spaces to conditionally define a function.
(PHP 7.4)

In FileA.php I declare and instantiate a function "foo"

```<code>namespace NSA;
function foo () {};
</code>```

In FileB.php I want to check if the function foo() is available, and if not create function foo() to use.

```<code>namespace NSB;
use function NSA\foo;
...
# if function foo() does exist create it
if (!function_exists ('NSA\foo')) {
    # create function foo()
    function foo () {}
}
</code>```

Both files are incorporated in the main program using include_once () in the order shown above.

In this scenario function_exists ('NSA\foo') returns true as the function does exist.

But I still get the error Cannot declare function NSB\foo because the name is already in use in FileB.php

Body:
I'm using PHP's function_exists() in name spaces to conditionally define a function.
(PHP 7.4)

In FileA.php I declare and instantiate a function "foo"

namespace NSA;
function foo () {};

In FileB.php I want to check if the function foo() is available, and if not create function foo() to use.

namespace NSB;
use function NSA\foo;
...
# if function foo() does exist create it
if (!function_exists ('NSA\foo')) {
    # create function foo()
    function foo () {}
}

Both files are incorporated in the main program using include_once () in the order shown above.

In this scenario function_exists ('NSA\foo') returns true as the function does exist.

But I still get the error Cannot declare function NSB\foo because the name is already in use in FileB.php


问:
Pyqt5 qthread signal and pyqtslot
How to send data to thread is running by pyqt as the code below?

I think it would be using pyqtslot, but I don't know how to use.

I'm trying to use the pyqt qthread for multithreading program.

In the code, there are two different workers instance. I try to use signal and slot for data share. but it seemed that the signal is blocked until one of the qthread is finished.

this is the code.

gui.py

```<code>from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(641, 204)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Button_start_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_start_1.setGeometry(QtCore.QRect(30, 20, 81, 41))
        self.Button_start_1.setObjectName("Button_start_1")
        self.Button_start_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_start_2.setGeometry(QtCore.QRect(30, 70, 81, 41))
        self.Button_start_2.setObjectName("Button_start_2")
        self.Button_stop_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_stop_1.setGeometry(QtCore.QRect(150, 20, 75, 41))
        self.Button_stop_1.setObjectName("Button_stop_1")
        self.Button_stop_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_stop_2.setGeometry(QtCore.QRect(150, 70, 75, 41))
        self.Button_stop_2.setObjectName("Button_stop_2")
        self.lcdNumber_1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber_1.setGeometry(QtCore.QRect(250, 20, 151, 41))
        self.lcdNumber_1.setObjectName("lcdNumber_1")
        self.lcdNumber_2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber_2.setGeometry(QtCore.QRect(250, 70, 151, 41))
        self.lcdNumber_2.setObjectName("lcdNumber_2")
        self.Button_pause_thread_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_pause_thread_1.setGeometry(QtCore.QRect(420, 20, 121, 41))
        self.Button_pause_thread_1.setObjectName("Button_pause_thread_1")
        self.Button_pause_thread_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_pause_thread_2.setGeometry(QtCore.QRect(420, 70, 121, 41))
        self.Button_pause_thread_2.setObjectName("Button_pause_thread_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 641, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.Button_start_1.setText(_translate("MainWindow", "Start thread1"))
        self.Button_start_2.setText(_translate("MainWindow", "Start thread2"))
        self.Button_stop_1.setText(_translate("MainWindow", "Stop thread 1"))
        self.Button_stop_2.setText(_translate("MainWindow", "Stop thread 1"))
        self.Button_pause_thread_1.setText(_translate("MainWindow", "Pause thread 1"))
        self.Button_pause_thread_2.setText(_translate("MainWindow", "Pause thread 2"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

</code>```

Main.py

```<code>import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal
from PyQt5 import QtCore
import time

from gui import Ui_MainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.uic = Ui_MainWindow()
        self.uic.setupUi(self)
        self.thread = {}
        self.uic.Button_start_1.clicked.connect(self.start_worker_1)
        self.uic.Button_start_2.clicked.connect(self.start_worker_2)
        self.uic.Button_stop_1.clicked.connect(self.stop_worker_1)
        self.uic.Button_stop_2.clicked.connect(self.stop_worker_2)

    def start_worker_1(self):
        self.thread[1] = ThreadClass(index=1)
        self.thread[1].start()
        self.thread[1].signal.connect(self.my_function)
        self.uic.Button_start_1.setEnabled(False)
        self.uic.Button_stop_1.setEnabled(True)

    def start_worker_2(self):
        self.thread[2] = ThreadClass(index=2)
        self.thread[2].start()
        self.thread[2].signal.connect(self.my_function)
        self.uic.Button_start_2.setEnabled(False)
        self.uic.Button_stop_2.setEnabled(True)

    def stop_worker_1(self):
        self.thread[1].stop()
        self.uic.Button_stop_1.setEnabled(False)
        self.uic.Button_start_1.setEnabled(True)

    def stop_worker_2(self):
        self.thread[2].stop()
        self.uic.Button_stop_2.setEnabled(False)
        self.uic.Button_start_2.setEnabled(True)

    def my_function(self, counter):
        m = counter
        i = self.sender().index

        if i == 1:
            self.uic.lcdNumber_1.display(m)
        if i == 2:
            self.uic.lcdNumber_2.display(m)

class ThreadClass(QtCore.QThread):
    signal = pyqtSignal(int)

    def __init__(self, index=0):
        super().__init__()
        self.index = index

    def run(self):
        print('Starting thread...', self.index)
        counter = 0
        while True:
            counter += 1
            print(counter)
            time.sleep(1)
            self.signal.emit(counter)

    def stop(self):
        print('Stopping thread...', self.index)
        self.terminate()

    def get_value_from_button(self):
        print("value of thread ")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_win = MainWindow()
    main_win.show()
    sys.exit(app.exec())
</code>```

I need to get data at get_value_from_button(self) function, when I press the button.

Title: Pyqt5 qthread signal and pyqtslot

Body:
How to send data to thread is running by pyqt as the code below?

I think it would be using pyqtslot, but I don't know how to use.

I'm trying to use the pyqt qthread for multithreading program.

In the code, there are two different workers instance. I try to use signal and slot for data share. but it seemed that the signal is blocked until one of the qthread is finished.

this is the code.

gui.py

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(641, 204)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Button_start_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_start_1.setGeometry(QtCore.QRect(30, 20, 81, 41))
        self.Button_start_1.setObjectName("Button_start_1")
        self.Button_start_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_start_2.setGeometry(QtCore.QRect(30, 70, 81, 41))
        self.Button_start_2.setObjectName("Button_start_2")
        self.Button_stop_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_stop_1.setGeometry(QtCore.QRect(150, 20, 75, 41))
        self.Button_stop_1.setObjectName("Button_stop_1")
        self.Button_stop_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_stop_2.setGeometry(QtCore.QRect(150, 70, 75, 41))
        self.Button_stop_2.setObjectName("Button_stop_2")
        self.lcdNumber_1 = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber_1.setGeometry(QtCore.QRect(250, 20, 151, 41))
        self.lcdNumber_1.setObjectName("lcdNumber_1")
        self.lcdNumber_2 = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber_2.setGeometry(QtCore.QRect(250, 70, 151, 41))
        self.lcdNumber_2.setObjectName("lcdNumber_2")
        self.Button_pause_thread_1 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_pause_thread_1.setGeometry(QtCore.QRect(420, 20, 121, 41))
        self.Button_pause_thread_1.setObjectName("Button_pause_thread_1")
        self.Button_pause_thread_2 = QtWidgets.QPushButton(self.centralwidget)
        self.Button_pause_thread_2.setGeometry(QtCore.QRect(420, 70, 121, 41))
        self.Button_pause_thread_2.setObjectName("Button_pause_thread_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 641, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.Button_start_1.setText(_translate("MainWindow", "Start thread1"))
        self.Button_start_2.setText(_translate("MainWindow", "Start thread2"))
        self.Button_stop_1.setText(_translate("MainWindow", "Stop thread 1"))
        self.Button_stop_2.setText(_translate("MainWindow", "Stop thread 1"))
        self.Button_pause_thread_1.setText(_translate("MainWindow", "Pause thread 1"))
        self.Button_pause_thread_2.setText(_translate("MainWindow", "Pause thread 2"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Main.py

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal
from PyQt5 import QtCore
import time

from gui import Ui_MainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.uic = Ui_MainWindow()
        self.uic.setupUi(self)
        self.thread = {}
        self.uic.Button_start_1.clicked.connect(self.start_worker_1)
        self.uic.Button_start_2.clicked.connect(self.start_worker_2)
        self.uic.Button_stop_1.clicked.connect(self.stop_worker_1)
        self.uic.Button_stop_2.clicked.connect(self.stop_worker_2)

    def start_worker_1(self):
        self.thread[1] = ThreadClass(index=1)
        self.thread[1].start()
        self.thread[1].signal.connect(self.my_function)
        self.uic.Button_start_1.setEnabled(False)
        self.uic.Button_stop_1.setEnabled(True)

    def start_worker_2(self):
        self.thread[2] = ThreadClass(index=2)
        self.thread[2].start()
        self.thread[2].signal.connect(self.my_function)
        self.uic.Button_start_2.setEnabled(False)
        self.uic.Button_stop_2.setEnabled(True)

    def stop_worker_1(self):
        self.thread[1].stop()
        self.uic.Button_stop_1.setEnabled(False)
        self.uic.Button_start_1.setEnabled(True)

    def stop_worker_2(self):
        self.thread[2].stop()
        self.uic.Button_stop_2.setEnabled(False)
        self.uic.Button_start_2.setEnabled(True)

    def my_function(self, counter):
        m = counter
        i = self.sender().index

        if i == 1:
            self.uic.lcdNumber_1.display(m)
        if i == 2:
            self.uic.lcdNumber_2.display(m)

class ThreadClass(QtCore.QThread):
    signal = pyqtSignal(int)

    def __init__(self, index=0):
        super().__init__()
        self.index = index

    def run(self):
        print('Starting thread...', self.index)
        counter = 0
        while True:
            counter += 1
            print(counter)
            time.sleep(1)
            self.signal.emit(counter)

    def stop(self):
        print('Stopping thread...', self.index)
        self.terminate()

    def get_value_from_button(self):
        print("value of thread ")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_win = MainWindow()
    main_win.show()
    sys.exit(app.exec())

I need to get data at get_value_from_button(self) function, when I press the button.


问:
Showing output from two different classes in pyqt5 gui python

Program

```<code>import sys
import os

from PyQt5 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import *
from PySide2 import *
from ui_test import *

class MainThread(QThread):
    def __init__(self):
        super(MainThread,self).__init__()

    def run(self):
        self.task()

    def task(self):
        while True:
          com="runnning"
          print(com)

startexecution = MainThread()
class main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ti = Ui_MainWindow()
        self.ti.setupUi(self)
        self.ti.run_btn.clicked.connect(self.starttask)
        self.ti.close.clicked.connect(self.close)

        self.show()

    def starttask(self):
        startexecution.start()

if __name__=="__main__":

    app =QApplication(sys.argv)
    window = main()
    sys.exit(app.exec_())
</code>```

It is an example of the problem I am facing in my original program

MainThread class run is the main program that runs in the backend and the main class runs GUI in frontend. I want to show the output generated by the backend program in textbrowser of my UI as an output

Body:
Program

import sys
import os

from PyQt5 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import *
from PySide2 import *
from ui_test import *

class MainThread(QThread):
    def __init__(self):
        super(MainThread,self).__init__()

    def run(self):
        self.task()

    def task(self):
        while True:
          com="runnning"
          print(com)

startexecution = MainThread()
class main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ti = Ui_MainWindow()
        self.ti.setupUi(self)
        self.ti.run_btn.clicked.connect(self.starttask)
        self.ti.close.clicked.connect(self.close)

        self.show()

    def starttask(self):
        startexecution.start()

if __name__=="__main__":

    app =QApplication(sys.argv)
    window = main()
    sys.exit(app.exec_())

It is an example of the problem I am facing in my original program

MainThread class run is the main program that runs in the backend and the main class runs GUI in frontend. I want to show the output generated by the backend program in textbrowser of my UI as an output


问:
r customize color with swimplot package
```<code>SwimArm <- swimmer_plot(df=Swim.Plot,
                        id='SUBJID',
                        end='swim_month',
                        name_fill='ARM',
                        id_order='ARM',
                        col="black",
                        increasing = FALSE,
                        alpha=0.75,width=.8) +
  scale_y_continuous(name = "Time since Treatment (months)",breaks = seq(0,18,by=3))
</code>```

I'm currently using swimplot package in r, and would like to customize plot of color below.
It seems that the package automatically chooses color of the line, and I would like to do this part manually.
Can you please tell me what I should do?
Thank you very much!

Title: r customize color with swimplot package

Body:
SwimArm <- swimmer_plot(df=Swim.Plot,
                        id='SUBJID',
                        end='swim_month',
                        name_fill='ARM',
                        id_order='ARM',
                        col="black",
                        increasing = FALSE,
                        alpha=0.75,width=.8) +
  scale_y_continuous(name = "Time since Treatment (months)",breaks = seq(0,18,by=3))

I'm currently using swimplot package in r, and would like to customize plot of color below.
It seems that the package automatically chooses color of the line, and I would like to do this part manually.
Can you please tell me what I should do?
Thank you very much!


问:
Laravel Livewire show Black Popup Without any message
I just create a laravel apps, with livewire installed.
when I try it on desktop, it works fine, but when mobile devices use it, the black popup show and no error log available
enter image description here

when I use chrome remote debug, here's what I gotenter image description here

no response or anything in network tab


问:
Run multiple Google MLKit TextRecognition processes in parallel
I try to make multiple MLKit TextRecognition processes run in multiple threads with the code below:

private TextRecognizer client;
private Executor mExecutor = Executors.newFixedThreadPool(4);

private void init() {
    TextRecognizerOptions build = new TextRecognizerOptions.Builder()
                .setExecutor(mExecutor)
                .build();
    client = TextRecognition.getClient(build);
//  client = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
}

private void testTextRec() {
    new Thread(new RecRunnable("task 1")).start();
    new Thread(new RecRunnable("task 2")).start();
    new Thread(new RecRunnable("task 3")).start();
    new Thread(new RecRunnable("task 4")).start();
}

private class RecRunnable implements Runnable {
    private final String name;
    private RecRunnable(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        Bitmap bitmap = readFromAsset("huchuan_passport.jpg");
        InputImage inputImage = InputImage.fromBitmap(bitmap, 0);
        final long start = System.currentTimeMillis();
        Log.e(TAG, "start " + name + " at :" + start);
        client.process(inputImage)
              .addOnSuccessListener(new OnSuccessListener<Text>() {
                  @Override
                  public void onSuccess(Text text) {
                      long elapse = System.currentTimeMillis() - start;
                      Log.e(TAG, name + " elapses: " + elapse + "ms");
                  }
              }).addOnFailureListener(new OnFailureListener() {
                  @Override
                  public void onFailure(@NonNull Exception e) {
                  }
              });
    }

    private Bitmap readFromAsset(String fileName) {
        try {
            InputStream open = getAssets().open(fileName);
            return BitmapFactory.decodeStream(open);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
```
<p>I also try the default Options<code> client = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);</code> and running the demo on device with 8 processors.</p>
<p>According to the log, four tasks cannot work in parallel.</p>
```2022-12-27 10:11:31.843 30756-30756/com.pax.tstmlkit E/MainActivity: available processors : 4
2022-12-27 10:11:32.181 30756-30810/com.pax.tstmlkit E/MainActivity: start task 1 at :1672107092181
2022-12-27 10:11:32.212 30756-30812/com.pax.tstmlkit E/MainActivity: start task 3 at :1672107092212
2022-12-27 10:11:32.270 30756-30811/com.pax.tstmlkit E/MainActivity: start task 2 at :1672107092270
2022-12-27 10:11:32.281 30756-30813/com.pax.tstmlkit E/MainActivity: start task 4 at :1672107092281
2022-12-27 10:11:33.490 30756-30756/com.pax.tstmlkit E/MainActivity: task 1 elapses: 1309ms
2022-12-27 10:11:34.378 30756-30756/com.pax.tstmlkit E/MainActivity: task 3 elapses: 2166ms
2022-12-27 10:11:35.215 30756-30756/com.pax.tstmlkit E/MainActivity: task 2 elapses: 2945ms
2022-12-27 10:11:36.022 30756-30756/com.pax.tstmlkit E/MainActivity: task 4 elapses: 3741ms
```

Does anybody know how to make multiple MLKit TextRecognition processes run in parallel?

Body:
I try to make multiple MLKit TextRecognition processes run in multiple threads with the code below:

private TextRecognizer client;
private Executor mExecutor = Executors.newFixedThreadPool(4);

private void init() {
    TextRecognizerOptions build = new TextRecognizerOptions.Builder()
                .setExecutor(mExecutor)
                .build();
    client = TextRecognition.getClient(build);
//  client = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
}

private void testTextRec() {
    new Thread(new RecRunnable("task 1")).start();
    new Thread(new RecRunnable("task 2")).start();
    new Thread(new RecRunnable("task 3")).start();
    new Thread(new RecRunnable("task 4")).start();
}

private class RecRunnable implements Runnable {
    private final String name;
    private RecRunnable(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        Bitmap bitmap = readFromAsset("huchuan_passport.jpg");
        InputImage inputImage = InputImage.fromBitmap(bitmap, 0);
        final long start = System.currentTimeMillis();
        Log.e(TAG, "start " + name + " at :" + start);
        client.process(inputImage)
              .addOnSuccessListener(new OnSuccessListener<Text>() {
                  @Override
                  public void onSuccess(Text text) {
                      long elapse = System.currentTimeMillis() - start;
                      Log.e(TAG, name + " elapses: " + elapse + "ms");
                  }
              }).addOnFailureListener(new OnFailureListener() {
                  @Override
                  public void onFailure(@NonNull Exception e) {
                  }
              });
    }

    private Bitmap readFromAsset(String fileName) {
        try {
            InputStream open = getAssets().open(fileName);
            return BitmapFactory.decodeStream(open);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

I also try the default Options client = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS); and running the demo on device with 8 processors.

According to the log, four tasks cannot work in parallel.

2022-12-27 10:11:31.843 30756-30756/com.pax.tstmlkit E/MainActivity: available processors : 4
2022-12-27 10:11:32.181 30756-30810/com.pax.tstmlkit E/MainActivity: start task 1 at :1672107092181
2022-12-27 10:11:32.212 30756-30812/com.pax.tstmlkit E/MainActivity: start task 3 at :1672107092212
2022-12-27 10:11:32.270 30756-30811/com.pax.tstmlkit E/MainActivity: start task 2 at :1672107092270
2022-12-27 10:11:32.281 30756-30813/com.pax.tstmlkit E/MainActivity: start task 4 at :1672107092281
2022-12-27 10:11:33.490 30756-30756/com.pax.tstmlkit E/MainActivity: task 1 elapses: 1309ms
2022-12-27 10:11:34.378 30756-30756/com.pax.tstmlkit E/MainActivity: task 3 elapses: 2166ms
2022-12-27 10:11:35.215 30756-30756/com.pax.tstmlkit E/MainActivity: task 2 elapses: 2945ms
2022-12-27 10:11:36.022 30756-30756/com.pax.tstmlkit E/MainActivity: task 4 elapses: 3741ms

Does anybody know how to make multiple MLKit TextRecognition processes run in parallel?


问:
How to work with Github Actions without .env file
I'm trying to perform deploy Laravel app to AWS Elastic Beanstalk with Github Actions but I had questions on running Github actions because currently I'm try to avoid upload .env file to my repository.

Below provided the default workflows which generated by Github

```<code>name: Laravel

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  laravel-tests:

    runs-on: ubuntu-latest

    steps:
    - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
      with:
        php-version: '8.0'
    - uses: actions/checkout@v3
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
    - name: Generate key
      run: php artisan key:generate
    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mkdir -p database
        touch database/database.sqlite
    - name: Execute tests (Unit and Feature tests) via PHPUnit
      env:
        DB_CONNECTION: sqlite
        DB_DATABASE: database/database.sqlite
      run: vendor/bin/phpunit
</code>```

The generated file showing error

```<code>There was 1 failure:

1) Tests\Feature\ExampleTest::test_the_application_returns_a_successful_response
Expected response status code [200] but received 500.
Failed asserting that 200 is identical to 500.

The following exception occurred during the last request:

PDOException: SQLSTATE[HY000]: General error: 1 no such table: users in /home/runner/work/sampleSearch/sampleSearch/vendor/laravel/framework/src/Illuminate/Database/Connection.php:414
</code>```

So may I know how can I solve this connection issues without upload .env file?

Body:
I'm trying to perform deploy Laravel app to AWS Elastic Beanstalk with Github Actions but I had questions on running Github actions because currently I'm try to avoid upload .env file to my repository.

Below provided the default workflows which generated by Github

name: Laravel

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  laravel-tests:

    runs-on: ubuntu-latest

    steps:
    - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
      with:
        php-version: '8.0'
    - uses: actions/checkout@v3
    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"
    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
    - name: Generate key
      run: php artisan key:generate
    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache
    - name: Create Database
      run: |
        mkdir -p database
        touch database/database.sqlite
    - name: Execute tests (Unit and Feature tests) via PHPUnit
      env:
        DB_CONNECTION: sqlite
        DB_DATABASE: database/database.sqlite
      run: vendor/bin/phpunit

The generated file showing error

There was 1 failure:

1) Tests\Feature\ExampleTest::test_the_application_returns_a_successful_response
Expected response status code [200] but received 500.
Failed asserting that 200 is identical to 500.

The following exception occurred during the last request:

PDOException: SQLSTATE[HY000]: General error: 1 no such table: users in /home/runner/work/sampleSearch/sampleSearch/vendor/laravel/framework/src/Illuminate/Database/Connection.php:414

So may I know how can I solve this connection issues without upload .env file?


问:
pyttsx3/__init__.py", line 20, in init

I wrote it on VS Code editor in Pop! OS. I get that problem now.

> That is codes:

```<code>import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexia' in command:
                command = command.replace('alexia', '')
                print(command)
    except:
        pass
    return command

def run_alexia():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who the heck is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')

while True:
    run_alexia()
</code>```

**

That is Error:
**

```<code>Traceback (most recent call last):
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "/usr/lib/python3.10/weakref.py", line 137, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mdshagor369/ao/main.py", line 9, in <module>
    engine = pyttsx3.init()
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/drivers/espeak.py", line 5, in <module>
    from . import _espeak, toUtf8, fromUtf8
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/drivers/_espeak.py", line 18, in <module>
    dll = cdll.LoadLibrary('libespeak.so.1')
  File "/usr/lib/python3.10/ctypes/__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.10/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libespeak.so.1: cannot open shared object file: No such file or directory
</code>```

**
it one Python3.10 on enviornment

There are some kind of issue like pyttsx3 init (20, 22, 452 and 374), engine(30), drive(50), so much error.

I need someone who can help me.
The prolem i don't understand. it like alexa project. I like to help me on there. i dont understad the problem.**

Title: pyttsx3/__init__.py", line 20, in init

Body:
I wrote it on VS Code editor in Pop! OS. I get that problem now.

> That is codes:

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexia' in command:
                command = command.replace('alexia', '')
                print(command)
    except:
        pass
    return command

def run_alexia():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who the heck is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')

while True:
    run_alexia()

**

That is Error:
**

Traceback (most recent call last):
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/__init__.py", line 20, in init
    eng = _activeEngines[driverName]
  File "/usr/lib/python3.10/weakref.py", line 137, in __getitem__
    o = self.data[key]()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mdshagor369/ao/main.py", line 9, in <module>
    engine = pyttsx3.init()
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/__init__.py", line 22, in init
    eng = Engine(driverName, debug)
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/drivers/espeak.py", line 5, in <module>
    from . import _espeak, toUtf8, fromUtf8
  File "/home/mdshagor369/ao/env/lib/python3.10/site-packages/pyttsx3/drivers/_espeak.py", line 18, in <module>
    dll = cdll.LoadLibrary('libespeak.so.1')
  File "/usr/lib/python3.10/ctypes/__init__.py", line 452, in LoadLibrary
    return self._dlltype(name)
  File "/usr/lib/python3.10/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libespeak.so.1: cannot open shared object file: No such file or directory

**
it one Python3.10 on enviornment

There are some kind of issue like pyttsx3 init (20, 22, 452 and 374), engine(30), drive(50), so much error.

I need someone who can help me.
The prolem i don't understand. it like alexa project. I like to help me on there. i dont understad the problem.**


问:
How to understand JavaScript “functions returning functions”?
I was following the MDN documentation about functions as first-class objects and wasn’t able to understand this line of code.

How to execute the function add? When I try this, I get these outputs.

// Function returning function.
const add = (x) => (y) => x + y;

console.log(add(1, 2)()) // undefined
console.log(add(1, 2))   // ƒ ()
console.log(add(1)(2))   // undefined```
</div>
</div>
</p>
<p>What is actually assigned to <code>add</code>? According to my understanding, <code>add</code> is defined as an anonymous function with input <code>x</code> and output as another anonymous function <code>(y) => x + y</code>. Then it should be equivalent to the following:</p>
<p>However, when I try a <code>function</code>, I get these outputs:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const add1 = function(x) {
  return (y) => x + y
};

console.log(add1(1, 2)()); // NaN
console.log(add1(1, 2));   // ƒ ()
console.log(add1(1)(2));   // 3</code>```

Body:
I was following the MDN documentation about functions as first-class objects and wasn’t able to understand this line of code.

How to execute the function add? When I try this, I get these outputs.

// Function returning function.
const add = (x) => (y) => x + y;

console.log(add(1, 2)()) // undefined
console.log(add(1, 2))   // ƒ ()
console.log(add(1)(2))   // undefined

What is actually assigned to add? According to my understanding, add is defined as an anonymous function with input x and output as another anonymous function (y) => x + y. Then it should be equivalent to the following:

However, when I try a function, I get these outputs:

const add1 = function(x) {
  return (y) => x + y
};

console.log(add1(1, 2)()); // NaN
console.log(add1(1, 2));   // ƒ ()
console.log(add1(1)(2));   // 3


问:
I have a committee table with a "leads" row relating to the members table. How do I select all leads of a committee by a committee id using TypeORM?
I am trying to use TypeORM to build highly relational data and make highly relational data queries. My current goal is to select all "leads" from the members table where the committee they are a lead of corresponds to a given committee id.

I have tried and failed to use repository.find() to do this. You can see in my code below.

```<code>   public async getLeadsFromCommittee(committeeId: number): Promise<Member[]> {
        const results = await this.memberRepository
            .createQueryBuilder()
            .select("member")
            .from(Member, "member")
            .innerJoinAndSelect("member.leadOf", "member")
            .getMany();
        return results;
        // return await this.memberRepository.find({ // my failure!
        //     where: { // but IMO this ... should work
        //         leadOf: {
        //             committeeId,
        //         },
        //     },
        // });
    }
</code>```

find({}) failed me. Perhaps I was using it wrong. But TypeORM's docs suggest that the createQueryBuilder is more powerful, so I'm trying that. But I'm new to using it, hence all I have to go on is one example in the docs which I've failed to utilize.

This post says that what I want is to INNER JOIN: "returns rows when there is a match in both tables."

Here is my (super duper interrelated) Members entity definition:

```<code>@Entity()
export class Member {
    @PrimaryGeneratedColumn()
    memberId: number;

    @ManyToMany(() => Committee, committee => committee.leads, { nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "lead_of" })
    leadOf?: Committee[];
}
</code>```

And here is the Committees entity definition:

```<code>@Entity()
export class Committee {
    @PrimaryGeneratedColumn({ name: "committee_id" })
    committeeId: number;

    @ManyToMany(() => Member, member => member.memberId, { eager: true, nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "leads_for_committee" })
    leads?: Member[];
}
</code>```

Lots of entries in the two entity definitions are deleted for brevity, but probably irrelevant.

Body:
I am trying to use TypeORM to build highly relational data and make highly relational data queries. My current goal is to select all "leads" from the members table where the committee they are a lead of corresponds to a given committee id.

I have tried and failed to use repository.find() to do this. You can see in my code below.

   public async getLeadsFromCommittee(committeeId: number): Promise<Member[]> {
        const results = await this.memberRepository
            .createQueryBuilder()
            .select("member")
            .from(Member, "member")
            .innerJoinAndSelect("member.leadOf", "member")
            .getMany();
        return results;
        // return await this.memberRepository.find({ // my failure!
        //     where: { // but IMO this ... should work
        //         leadOf: {
        //             committeeId,
        //         },
        //     },
        // });
    }

find({}) failed me. Perhaps I was using it wrong. But TypeORM's docs suggest that the createQueryBuilder is more powerful, so I'm trying that. But I'm new to using it, hence all I have to go on is one example in the docs which I've failed to utilize.

This post says that what I want is to INNER JOIN: "returns rows when there is a match in both tables."

Here is my (super duper interrelated) Members entity definition:

@Entity()
export class Member {
    @PrimaryGeneratedColumn()
    memberId: number;

    @ManyToMany(() => Committee, committee => committee.leads, { nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "lead_of" })
    leadOf?: Committee[];
}

And here is the Committees entity definition:

@Entity()
export class Committee {
    @PrimaryGeneratedColumn({ name: "committee_id" })
    committeeId: number;

    @ManyToMany(() => Member, member => member.memberId, { eager: true, nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "leads_for_committee" })
    leads?: Member[];
}

Lots of entries in the two entity definitions are deleted for brevity, but probably irrelevant.


问:
NavigationUI.setupActionBarWithNavController and setupActionBarWithNavController
I'm learning android development, Im looking up information about navigation components and fragments but I havent understood what is the diferent between

NavigationUI.setupActionBarWithNavController(this,navHostFragment.navController) and setupActionBarWithNavController(navController,appBarConfig).

bellow you can find two codes, In one Im using NavigationUI but In the other I dont.

First one:

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        NavigationUI.setupActionBarWithNavController(this,navHostFragment.navController)
        binding.bnNavBar.setupWithNavController(navHostFragment.navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.nav_host_fragment)
        return navController.navigateUp()
    }

}
</code>```

Second one:

```<code>class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    private lateinit var mainBinding: ActivityMainBinding
    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)

        val toolBar = mainBinding.activityMainContent.mainToolbar

        //Setting up the tool bar as the app bar for the activity
        setSupportActionBar(toolBar)

        val host: NavHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment

        val navController = host.navController

        //appBarConfiguration = AppBarConfiguration(navController.graph)

        appBarConfiguration = AppBarConfiguration(
            setOf(R.id.continentFragment),
            mainBinding.drawerLayout
        )

        //First
        setUpActionBar(navController,appBarConfiguration)

        //Second
        setUpNavigationView(navController)

    }

    private fun setUpActionBar(navController: NavController, appBarConfig : AppBarConfiguration) {
        setupActionBarWithNavController(navController,appBarConfig)
    }

    private fun setUpNavigationView(controller: NavController) {
        mainBinding.navView.setupWithNavController(controller)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        mainBinding.drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_container)
        return navController.navigateUp(appBarConfiguration)|| super.onSupportNavigateUp()
    }

    override fun onBackPressed() {
        if (mainBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mainBinding.drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }
}
</code>```

Please, I'd be very thankful if someone can explain me the diference.

Ive read a lot about navigation but I havent found anything useful

Body:
I'm learning android development, Im looking up information about navigation components and fragments but I havent understood what is the diferent between

NavigationUI.setupActionBarWithNavController(this,navHostFragment.navController) and setupActionBarWithNavController(navController,appBarConfig).

bellow you can find two codes, In one Im using NavigationUI but In the other I dont.

First one:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding= ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        NavigationUI.setupActionBarWithNavController(this,navHostFragment.navController)
        binding.bnNavBar.setupWithNavController(navHostFragment.navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.nav_host_fragment)
        return navController.navigateUp()
    }

}

Second one:

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    private lateinit var mainBinding: ActivityMainBinding
    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)

        val toolBar = mainBinding.activityMainContent.mainToolbar

        //Setting up the tool bar as the app bar for the activity
        setSupportActionBar(toolBar)

        val host: NavHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment

        val navController = host.navController

        //appBarConfiguration = AppBarConfiguration(navController.graph)

        appBarConfiguration = AppBarConfiguration(
            setOf(R.id.continentFragment),
            mainBinding.drawerLayout
        )

        //First
        setUpActionBar(navController,appBarConfiguration)

        //Second
        setUpNavigationView(navController)

    }

    private fun setUpActionBar(navController: NavController, appBarConfig : AppBarConfiguration) {
        setupActionBarWithNavController(navController,appBarConfig)
    }

    private fun setUpNavigationView(controller: NavController) {
        mainBinding.navView.setupWithNavController(controller)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        mainBinding.drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_container)
        return navController.navigateUp(appBarConfiguration)|| super.onSupportNavigateUp()
    }

    override fun onBackPressed() {
        if (mainBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            mainBinding.drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }
}

Please, I'd be very thankful if someone can explain me the diference.

Ive read a lot about navigation but I havent found anything useful


问:
Player movement only smooth when there's mouse movement
I began learning how to program on pygame recently. I followed a tutorial and learned how to import assets and have player movement with key presses. However, every time I try moving by holding down keys (without mouse movement), it moves at a slow velocity and looks choppy. When I constantly move my mouse and begin to move with the keys the movement becomes smoother and faster. I am very new to pygame so if this is a rookie mistake I apologize.

```<code>import pygame
from sys import exit

player_gravity = 0
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption("2d platformer")
clock = pygame.time.Clock()
test_font = pygame.font.Font(None, 50)

sky_surface = pygame.image.load("graphics/sky.png").convert()
ground_surface = pygame.image.load("graphics/ground.png").convert()

creeper_surface = pygame.image.load("graphics/enemy.png").convert_alpha()
creeper_rectangle = creeper_surface.get_rect(bottomright = (600,300))

player_surface = pygame.image.load("graphics/player.png").convert_alpha()
player_rectangle = player_surface.get_rect(midbottom = (80,300))

Steps = 5
Sprints = 10

x_change = 0
accel_x = 0
accel_y = 0
max_speed = 6

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and not keys[pygame.K_RIGHT]:
            x_change = max(x_change-0.2, -max_speed)
        elif keys[pygame.K_d] and not keys[pygame.K_LEFT]:
            x_change = min(x_change+0.2, max_speed)
        else:
            x_change *= 0.50
        if keys[pygame.K_w] and player_rectangle.bottom >= 300:
            player_gravity = -20

        player_rectangle.x += x_change

    screen.blit(sky_surface,(0,0))
    screen.blit(ground_surface,(0,300))

    creeper_rectangle.x -=4

    if creeper_rectangle.right <= 0:
        creeper_rectangle.left = 800

    screen.blit(creeper_surface,creeper_rectangle)

    player_gravity += 1
    player_rectangle.y += player_gravity
    if player_rectangle.bottom >= 300:
        player_rectangle.bottom = 300

    screen.blit(player_surface,player_rectangle)

    pygame.display.update()
    clock.tick(60)

</code>```

I tried using while loops, but that crashed the window everytime.

Body:
I began learning how to program on pygame recently. I followed a tutorial and learned how to import assets and have player movement with key presses. However, every time I try moving by holding down keys (without mouse movement), it moves at a slow velocity and looks choppy. When I constantly move my mouse and begin to move with the keys the movement becomes smoother and faster. I am very new to pygame so if this is a rookie mistake I apologize.

import pygame
from sys import exit

player_gravity = 0
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption("2d platformer")
clock = pygame.time.Clock()
test_font = pygame.font.Font(None, 50)

sky_surface = pygame.image.load("graphics/sky.png").convert()
ground_surface = pygame.image.load("graphics/ground.png").convert()

creeper_surface = pygame.image.load("graphics/enemy.png").convert_alpha()
creeper_rectangle = creeper_surface.get_rect(bottomright = (600,300))

player_surface = pygame.image.load("graphics/player.png").convert_alpha()
player_rectangle = player_surface.get_rect(midbottom = (80,300))

Steps = 5
Sprints = 10

x_change = 0
accel_x = 0
accel_y = 0
max_speed = 6

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and not keys[pygame.K_RIGHT]:
            x_change = max(x_change-0.2, -max_speed)
        elif keys[pygame.K_d] and not keys[pygame.K_LEFT]:
            x_change = min(x_change+0.2, max_speed)
        else:
            x_change *= 0.50
        if keys[pygame.K_w] and player_rectangle.bottom >= 300:
            player_gravity = -20

        player_rectangle.x += x_change

    screen.blit(sky_surface,(0,0))
    screen.blit(ground_surface,(0,300))

    creeper_rectangle.x -=4

    if creeper_rectangle.right <= 0:
        creeper_rectangle.left = 800

    screen.blit(creeper_surface,creeper_rectangle)

    player_gravity += 1
    player_rectangle.y += player_gravity
    if player_rectangle.bottom >= 300:
        player_rectangle.bottom = 300

    screen.blit(player_surface,player_rectangle)

    pygame.display.update()
    clock.tick(60)

I tried using while loops, but that crashed the window everytime.


问:
call external function in getStaticProps that interfaces with filesystem
I have a list of files in a filesystem, a page that lists these files, and another dynamic route that uses the same list for its static paths. My initial thought was to create another function that handled the filesystem and all the processing related to it and then exporting the results for the other pages to import, but it doesn't seem like it's possible to access the filesystem outside of the getStaticProps and getStaticPaths methods. Is it possible to share this data between the two pages without having to rewrite almost the same code in both functions?


问:
Fire Events as User Swipes Over Elements in React
In React, I want to allow the user to swipe over an area of the screen that contains several elements and fire an event handler as their finger enters the given element.

example

So, for example, in the image I'd want the user to be able to start touching in the element marked 1 and, as the user swipes across the elements, an event is fired as the user's finger enters the elements (2, 3, 4, and so on).

I've tried using onTouchMove but that event only fires the event handler of the first element that is initially touched. I expected it to fire only while the user was moving their touch over a particular element.