问:
Spring Boot is not running on external tomcat
I have seen a lot of similar questions but none of them were helpful.
I have made a Spring Boot application and I am trying to run it on tomcat v8.5. The application is running when I chose embedded tomcat. When I run external tomcat, I get following lines on console in red color:

```<code>Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Nov 16 2022 13:34:24 UTC
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 8.5.84.0
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_301\jre
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_301-b09
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         E:\apache-tomcat-8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=E:\apache-tomcat-8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=E:\apache-tomcat-8.5.84\endorsed
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_301\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:/Softwares/sts-4.13.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.1.v20211116-1657/jre/bin/server;D:/Softwares/sts-4.13.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.1.v20211116-1657/jre/bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\apache-maven-3.8.2\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\Geo Information\AppData\Local\Microsoft\WindowsApps;C:\Users\Geo Information\AppData\Roaming\npm;C:\Users\Geo Information\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Java\jdk1.8.0_301\bin;C:\Program Files\MySQL\MySQL Server 5.7\bin;;D:\Softwares\sts-4.13.0.RELEASE;;.]
Dec 26, 2022 6:03:36 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-9090"]
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1121 ms
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/8.5.84]
Dec 26, 2022 6:03:38 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
WARNING: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,011] milliseconds.
Dec 26, 2022 6:03:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-9090"]
Dec 26, 2022 6:03:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1689 ms

</code>```

My Controller is:

```<code>package com.devhub.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @GetMapping({"/home", "/"})
    public ModelAndView home() {
        System.out.println("Hello");
        return new ModelAndView("components/home");
    }
}

</code>```

But it gives me 404 page not found on the frontend.
Following is my pom.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.devhub</groupId>
    <artifactId>devhub</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>devhub</name>
    <description>DevHub Project in Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <scope>provided</scope>
            <version>2.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

I have tried solution https://stackoverflow.com/a/25151930/16437679 . By following this, on localhost:8080 I am getting the tomcat configuration screen. But on entering my url which is http://localhost:8080/devhub/home, I get 404. I also tried changing URL to http://localhost:8080/home but still getting 404.

Body:
I have seen a lot of similar questions but none of them were helpful.
I have made a Spring Boot application and I am trying to run it on tomcat v8.5. The application is running when I chose embedded tomcat. When I run external tomcat, I get following lines on console in red color:

Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Nov 16 2022 13:34:24 UTC
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 8.5.84.0
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_301\jre
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_301-b09
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         E:\apache-tomcat-8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=E:\apache-tomcat-8.5.84
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=E:\DevHub\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=E:\apache-tomcat-8.5.84\endorsed
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The Apache Tomcat Native library which allows using OpenSSL was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_301\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:/Softwares/sts-4.13.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.1.v20211116-1657/jre/bin/server;D:/Softwares/sts-4.13.0.RELEASE//plugins/org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.1.v20211116-1657/jre/bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\apache-maven-3.8.2\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\Geo Information\AppData\Local\Microsoft\WindowsApps;C:\Users\Geo Information\AppData\Roaming\npm;C:\Users\Geo Information\AppData\Local\Programs\Microsoft VS Code\bin;C:\Program Files\Java\jdk1.8.0_301\bin;C:\Program Files\MySQL\MySQL Server 5.7\bin;;D:\Softwares\sts-4.13.0.RELEASE;;.]
Dec 26, 2022 6:03:36 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-9090"]
Dec 26, 2022 6:03:36 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1121 ms
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Dec 26, 2022 6:03:36 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/8.5.84]
Dec 26, 2022 6:03:38 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
WARNING: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,011] milliseconds.
Dec 26, 2022 6:03:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-9090"]
Dec 26, 2022 6:03:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1689 ms

My Controller is:

package com.devhub.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @GetMapping({"/home", "/"})
    public ModelAndView home() {
        System.out.println("Hello");
        return new ModelAndView("components/home");
    }
}

But it gives me 404 page not found on the frontend.
Following is my pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath />
    </parent>
    <groupId>com.devhub</groupId>
    <artifactId>devhub</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>devhub</name>
    <description>DevHub Project in Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <scope>provided</scope>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I have tried solution https://stackoverflow.com/a/25151930/16437679 . By following this, on localhost:8080 I am getting the tomcat configuration screen. But on entering my url which is http://localhost:8080/devhub/home, I get 404. I also tried changing URL to http://localhost:8080/home but still getting 404.


来源: stackexchange

问:
Why does pipenv graph display some packages bold?
e.g. $ pipenv graph returns:

jsonschema==3.0.1

attrs [required: >=17.4.0, installed: 19.1.0]

Why is jsonschema typed in bold?

For the sake of readability here's the same source block formatted as shell output (can't display bold here):

jsonschema==3.0.1
  - attrs [required: >=17.4.0, installed: 19.1.0]
```

ContentLicense: CC BY-SA 4.0


问:
Get Qr scanner information
I have 2 er80 QR scanners (datasheet) (connected to my pc via usb), and I have my application written in node js.
Assuming that I have 2 doors and each scanner is mounted to a door (one for entering and one for exiting), how could I know which scanner scanned a QR code so I could know which door to open

1- I tried to use serial communication with the er80 but couldn't, (er80 is acting like a virtual keyboard)
2- tried to use scanner-to-buffer (which for linux uses scanimage), and my device did not find any device

Title: Get Qr scanner information


问:
How to make a client component Next.js 13
I'm trying to turn a 3rd party component into a client component. Here is how nextjs does it

Official Next.js Example

app/carousel.js

```<code>'use client';

import { AcmeCarousel } from 'acme-carousel';

export default AcmeCarousel;

</code>```

app/page.js

```<code>import Carousel from './carousel';

export default function Page() {
  return (
    <div>
      <p>View pictures</p>

      {/*  Works, since Carousel is a Client Component */}
      <Carousel />
    </div>
  );
}

</code>```

My code

ClientPopover.jsx

```<code>'use client';

import { Popover } from '@headlessui/react'

export const PopoverGroup = Popover.group;
</code>```

header.jsx

```<code>import PopoverGroup  from '../../../app/ClientPopover'

<PopoverGroup>
   ...
</PopoverGroup>
</code>```

This is the error I'm getting:

```<code>Error: Element type is invalid. Received a promise that resolves to: undefined. Lazy element type must resolve to a class or function.
</code>```

Body:
I'm trying to turn a 3rd party component into a client component. Here is how nextjs does it

Official Next.js Example

app/carousel.js

'use client';

import { AcmeCarousel } from 'acme-carousel';

export default AcmeCarousel;

app/page.js

import Carousel from './carousel';

export default function Page() {
  return (

View pictures

      {/*  Works, since Carousel is a Client Component */}
      <Carousel />

  );
}

My code

ClientPopover.jsx

'use client';

import { Popover } from '@headlessui/react'

export const PopoverGroup = Popover.group;

header.jsx

import PopoverGroup  from '../../../app/ClientPopover'

<PopoverGroup>
   ...
</PopoverGroup>

This is the error I'm getting:

Error: Element type is invalid. Received a promise that resolves to: undefined. Lazy element type must resolve to a class or function.


问:
jQuery selectors finds elements only after I open the dropdown (bootstrap-select)
Using the bootstrap-select package, I have 4 dropdowns. Each dropdown is a descendant of the previous in order to filter by hierarchy of company units.

So first dropdown shows list of company's groups, second shows list of company's subgroups and so on until the final dropdown shows the smallest unit.

The goal is that a selection in the ancestor dropdown will filter out and hide anything in the descendants that was not selected.

when I open the dropdowns, everything shows up well.

However the JavaScript code does not work because jQuery can't find the elements unless I open the dropdowns at least once.

I tried outputting the data both via PHP and via JS+Ajax. Same in both cases.

Example outputting via PHP (Laravel Blade):

```<code><select title="choose subunit" class="selectpicker" multiple>
    @foreach ($units as $group_name => $group)
        @foreach ($group as $subgroup_name => $subgroup)
            @foreach ($subgroup as $unit_name => $unit)
                @foreach ($unit $subunit_name=> $subunit)
                    <option class="$subunit['id'] $unit['id']
                                   $subgroup['id'] $group['id']">
                           $subunit['value']
                   </option>
                @endforeach
            @endforeach
        @endforeach
    @endforeach
</select>
</code>```

this example is to show that each option has its ancestors as classes. So the classes for subunit 11 can be unit7, subgroup4, group2 for example.

I have a jQuery selector to find any descendant (subgroup, unit, subunit) of the currently selected dropdown

If a group is selected, it would search for every matching descendant with the class of the groups ID:

So if group2 was selected in the first dropdown, the selector would be:

```<code>$("selectDiv").on("changed.bs.select", function (e, clicked, curr, prev) {
    // some more actions
    $("a.dropdown-item:not(.group2)").each(function() {
        $(this).closest("li").hide();
    });
}
</code>```

Now when I enter this selector in the browser's console:

$("a.dropdown-item:not(.group2)");

It will show me correct results that are needed to be hidden, only if I first open the sub-menus. Otherwise, it shows 0 results!

I've been trying to figure out what causes this for a few days now. But I could not get a clue as to what causes that

Body:
Using the bootstrap-select package, I have 4 dropdowns. Each dropdown is a descendant of the previous in order to filter by hierarchy of company units.

So first dropdown shows list of company's groups, second shows list of company's subgroups and so on until the final dropdown shows the smallest unit.

The goal is that a selection in the ancestor dropdown will filter out and hide anything in the descendants that was not selected.

when I open the dropdowns, everything shows up well.

However the JavaScript code does not work because jQuery can't find the elements unless I open the dropdowns at least once.

I tried outputting the data both via PHP and via JS+Ajax. Same in both cases.

Example outputting via PHP (Laravel Blade):

<select title="choose subunit" class="selectpicker" multiple>
    @foreach ($units as $group_name => $group)
        @foreach ($group as $subgroup_name => $subgroup)
            @foreach ($subgroup as $unit_name => $unit)
                @foreach ($unit $subunit_name=> $subunit)
                    <option class="$subunit['id'] $unit['id']
                                   $subgroup['id'] $group['id']">
                           $subunit['value']
                   </option>
                @endforeach
            @endforeach
        @endforeach
    @endforeach
</select>

this example is to show that each option has its ancestors as classes. So the classes for subunit 11 can be unit7, subgroup4, group2 for example.

I have a jQuery selector to find any descendant (subgroup, unit, subunit) of the currently selected dropdown

If a group is selected, it would search for every matching descendant with the class of the groups ID:

So if group2 was selected in the first dropdown, the selector would be:

$("selectDiv").on("changed.bs.select", function (e, clicked, curr, prev) {
    // some more actions
    $("a.dropdown-item:not(.group2)").each(function() {
        $(this).closest("li").hide();
    });
}

Now when I enter this selector in the browser's console:

$("a.dropdown-item:not(.group2)");

It will show me correct results that are needed to be hidden, only if I first open the sub-menus. Otherwise, it shows 0 results!

I've been trying to figure out what causes this for a few days now. But I could not get a clue as to what causes that


问:
CORS to server from linux cli and from browser
I am running a cross origin request from an index.html script tag. I receive a CORS error because

Reason: CORS header 'Access-Control-Allow-Origin' missing

I've read about CORS quite a bit. I am aware that a server needs to set the Access Control Header to * for my request to really succeed.

Yet if I run GET <URL> from the Linux Cli I get the expected JSON response.

But how are these two requests different? Is there any way to get it working from the browser?

API: https://www.fishwatch.gov/api/ (no code or anything)

I am trying to understand what is the reason for this?


问:
Plotly parallel coordinate plots (adjusting colorbar and label fonts) inside a for loop
I am working on generating plotly parallel coordinate plots and I am having problems on how to make the colorbar discrete as well as increasing the font size of my labels. My code also does not seem to work to generate the slice images inside the for loop and it only generates the first slice which does not seem to be correct either, as it incorrectly generates the plot in the first slice for only the store_index 1! In summary, here are the issues:
I'd greatly appreciate any feedback on this.

Is there a way to convert the colorbar to 3 discrete colors (or even more colors in other data cases) each one unique for each store_index?

Is there any way to increase the label font sizes (feb_sales, jan_sales, etc...)?

In the plot, is there any way to eliminate the store_index and slice_number from the plots and only keep the colorbar?

What am I doing wrong that the generated plot for each slice_number is either wrong or empty?

Here is the snapshots of my df, my code and attempt:

```<code>import pandas as pd
import numpy as np
import plotly.express as px
import os

path = r"C:\Users\test"

my_df = pd.DataFrame()
np.random.seed(0)
jan_sales = np.random.randint(low=0, high=100, size = 75)
feb_sales = np.random.randint(low=0, high=100, size =75)

store_index = np.arange(1, 4)
store_index = np.repeat(store_index, 25)

slice_number = np.arange(1, 6)
slice_number = np.tile(slice_number, 3)
slice_number = np.repeat(slice_number, 5)

my_df['jan_sales'] = jan_sales
my_df['feb_sales'] = feb_sales
my_df['store_index'] = store_index
my_df['slice_number'] = slice_number

#my_df

#n_colors = 3
#colors = px.colors.sample_colorscale("turbo", [n/(n_colors -1) for n in range(n_colors)])

for slice in np.arange(1, 6):
    my_df = my_df.loc[my_df['slice_number'] == slice]
    fig = px.parallel_coordinates(my_df, color="store_index", labels={"jan_sales": "feb_sales"},   #colors = colors
                                 color_continuous_scale=px.colors.diverging.Tealrose,  # color_discrete_scale=px.colors.diverging.Tealrose
                                 color_continuous_midpoint=2)
    fig.update_layout(title=dict(
        text='<b>Store Sales by Month and Slice: Slice: {}<b>'.format(slice),

        x=0.5,
        y=0.99,
        font=dict(
            family="Arial",
            size=12,
color='#000000'  )))
    fig.write_image(os.path.join(path,'Slice_{}.png'.format(slice)))
    fig.show()
</code>```

Body:
I am working on generating plotly parallel coordinate plots and I am having problems on how to make the colorbar discrete as well as increasing the font size of my labels. My code also does not seem to work to generate the slice images inside the for loop and it only generates the first slice which does not seem to be correct either, as it incorrectly generates the plot in the first slice for only the store_index 1! In summary, here are the issues:
I'd greatly appreciate any feedback on this.

Is there a way to convert the colorbar to 3 discrete colors (or even more colors in other data cases) each one unique for each store_index?

Is there any way to increase the label font sizes (feb_sales, jan_sales, etc...)?

In the plot, is there any way to eliminate the store_index and slice_number from the plots and only keep the colorbar?

What am I doing wrong that the generated plot for each slice_number is either wrong or empty?

Here is the snapshots of my df, my code and attempt:

import pandas as pd
import numpy as np
import plotly.express as px
import os

path = r"C:\Users\test"

my_df = pd.DataFrame()
np.random.seed(0)
jan_sales = np.random.randint(low=0, high=100, size = 75)
feb_sales = np.random.randint(low=0, high=100, size =75)

store_index = np.arange(1, 4)
store_index = np.repeat(store_index, 25)

slice_number = np.arange(1, 6)
slice_number = np.tile(slice_number, 3)
slice_number = np.repeat(slice_number, 5)

my_df['jan_sales'] = jan_sales
my_df['feb_sales'] = feb_sales
my_df['store_index'] = store_index
my_df['slice_number'] = slice_number

#my_df

#n_colors = 3
#colors = px.colors.sample_colorscale("turbo", [n/(n_colors -1) for n in range(n_colors)])

for slice in np.arange(1, 6):
    my_df = my_df.loc[my_df['slice_number'] == slice]
    fig = px.parallel_coordinates(my_df, color="store_index", labels={"jan_sales": "feb_sales"},   #colors = colors
                                 color_continuous_scale=px.colors.diverging.Tealrose,  # color_discrete_scale=px.colors.diverging.Tealrose
                                 color_continuous_midpoint=2)
    fig.update_layout(title=dict(
        text='Store Sales by Month and Slice: Slice: {}'.format(slice),

        x=0.5,
        y=0.99,
        font=dict(
            family="Arial",
            size=12,
color='#000000'  )))
    fig.write_image(os.path.join(path,'Slice_{}.png'.format(slice)))
    fig.show()


问:
How to know which line in a python library raised an exception?
I have a program which runs fine but when I use uvicorn, my program raises an asyncio.exceptions.CancelledError when I call asyncio.gather(*tasks). The problem is I don't know which line in the library (uvicorn or some other library) is rasing that exception.

How can I know which line in which library is rasing the exception?


问:
[Cmake][QtCreator] Including file from subdirectory causes it to not find its includes anymore
I have a project with following structure:

```<code>MyProject/
├─ CMakeLists.txt (A)
├─ foo.h
├─ ThirdParty/
│  ├─ CMakeLists.txt (B)
│  ├─ bar.h
│  ├─ ThirdPartySourceOne/
│  │  ├─ CMakeLists.txt (C)
│  │  ├─ boo.h
│  ├─ ThirdPartySourceTwo/
│  │  ├─ CMakeLists.txt (D)
│  │  ├─ far.h
</code>```

CMakeLists A "includes" CMakeLists B by

```<code>add_subdirectory(ThirdParty)
</code>```

CMakeLists B "includes" CMakeLists C and D

```<code>add_subdirectory(ThirdPartySourceOne)
add_subdirectory(ThirdPartySourceTwo)
</code>```

far.h includes boo.h

When I build it like this, the whole project builds fine (including the third party source).

But when I add #include ThirdParty/ThirdPartySourceTwo/far.h to foo.h I get an error from the far.h along the lines of:

```<code> fatal error: ThirdPartySourceOne/boo.h: No such file or directory
   25 | #include <ThirdPartySourceOne/boo.h>
      |          ^~~~~~~~~~~~~~~~
</code>```

So how do I include the Third Party code correctly?
Thank you in advance.

I tried to search for a similar problem on Google

I tried include(ThirdParty/CMakeLists.txt) which caused the (untouched) thirdparty Library's CMakeLists(B) not to find the subdirectories anymore:

```<code>CMakeLists.txt:19: error: add_subdirectory given source "ThirdPartySourceOne" which is not an existing directory. CMakeLists.txt:17 (include)
</code>```

Trial and error with Paths in CMakeLists(B) that just broke more further down the road

Body:
I have a project with following structure:

MyProject/
├─ CMakeLists.txt (A)
├─ foo.h
├─ ThirdParty/
│  ├─ CMakeLists.txt (B)
│  ├─ bar.h
│  ├─ ThirdPartySourceOne/
│  │  ├─ CMakeLists.txt (C)
│  │  ├─ boo.h
│  ├─ ThirdPartySourceTwo/
│  │  ├─ CMakeLists.txt (D)
│  │  ├─ far.h

CMakeLists A "includes" CMakeLists B by

add_subdirectory(ThirdParty)

CMakeLists B "includes" CMakeLists C and D

add_subdirectory(ThirdPartySourceOne)
add_subdirectory(ThirdPartySourceTwo)

far.h includes boo.h

When I build it like this, the whole project builds fine (including the third party source).

But when I add #include ThirdParty/ThirdPartySourceTwo/far.h to foo.h I get an error from the far.h along the lines of:

 fatal error: ThirdPartySourceOne/boo.h: No such file or directory
   25 | #include <ThirdPartySourceOne/boo.h>
      |          ^~~~~~~~~~~~~~~~

So how do I include the Third Party code correctly?
Thank you in advance.

I tried to search for a similar problem on Google

I tried include(ThirdParty/CMakeLists.txt) which caused the (untouched) thirdparty Library's CMakeLists(B) not to find the subdirectories anymore:

CMakeLists.txt:19: error: add_subdirectory given source "ThirdPartySourceOne" which is not an existing directory. CMakeLists.txt:17 (include)

Trial and error with Paths in CMakeLists(B) that just broke more further down the road


问:
Set Athena Query result location different for different workgroup
I created different workgroups and databases for different customers into Athena. I want to set different Query result location with different workgroup now. But whenever I am changing the Query result location for one workgroup other workgroup locations are changing as well.

Is there any way to save different Query result location for different workgroups?

Expecting the procedure to set different Query result location for different workgroups and database into Athena


问:
How to make multiple line chart with morris.js
I want to make multiple line chart with morris.js with channel title, watchers, published_at to created_at data.
Each channel data should be in different line chart with different color. I have tried to make defferent array for each channel but it is not working.
I have tried this but it is not working

   //  I have data like this

    var line = [
        {
            "stream": 55,
            "channel_title": "Geo News",
            "watchers": 0,
            "created_at": "11-07-2022 10:31:18",
            "published_at": "11-07-2022 10:31:17"
        },
        {
            "stream": 65,
            "channel_title": "BOL News",
            "watchers": 1316,
            "created_at": "08-19-2022 22:36:58",
            "published_at": "08-16-2022 19:53:01"
        },
        {
            "stream": 66,
            "channel_title": "Dunya News",
            "watchers": 411,
            "created_at": "08-19-2022 22:36:58",
            "published_at": "08-19-2022 05:44:01"
        },
        {
            "stream": 64,
            "channel_title": "Express News",
            "watchers": 28,
            "created_at": "08-19-2022 22:36:57",
            "published_at": "08-19-2022 08:52:54"
        },
        {
            "stream": 48,
            "channel_title": "ARY News",
            "watchers": 3948,
            "created_at": "08-19-2022 22:36:56",
            "published_at": "04-06-2021 13:15:04"
        },
        {
            "stream": 49,
            "channel_title": "Geo News",
            "watchers": 1912,
            "created_at": "08-19-2022 22:36:55",
            "published_at": "05-27-2022 14:13:32"
        },
        {
            "stream": 55,
            "channel_title": "Geo News",
            "watchers": 141,
            "created_at": "08-19-2022 22:36:55",
            "published_at": "05-27-2022 14:19:12"
        },
        {
            "stream": 53,
            "channel_title": "SAMAA TV",
            "watchers": 340,
            "created_at": "08-19-2022 22:36:54",
            "published_at": "08-06-2022 10:34:37"
        },
        {
            "stream": 63,
            "channel_title": "92 News HD",
            "watchers": 305,
            "created_at": "08-19-2022 22:36:53",
            "published_at": "08-19-2022 04:31:14"
        },
        {
            "stream": 65,
            "channel_title": "BOL News",
            "watchers": 1608,
            "created_at": "08-19-2022 20:45:26",
            "published_at": "08-16-2022 19:53:01"
        }
    ]

    // get same channel data
    var data = line.reduce(function (r, a) {
        r[a.channel_title] = r[a.channel_title] || [];
        r[a.channel_title].push(a);
        return r;
    }, Object.create(null));

    // get channel name
    var channel_name = Object.keys(data);
```


问:
How to improve performance on evaluating multiple mathematical expressions?
I'm developing an application that works like an excel sheet: the user types a few values, and a lot of consequent calculation is done, in Blazor.

Right now I'm following this sequence (simplified code can be found at the end of question):

Retrieve all expressions from DB into a List.

The expressions can be written by the user, in another section. For example, the user can insert that BMI formula is "= @Weight / @Height ^2"

Each property call "RetrieveValue(propertyName)"

Substitute refferences in expression for it's value

That means, if the expression is "= @Weight / @Height ^ 2", I'll replace '@Weight' and '@Height' for either user-typed values, or for values from other expressions

Evaluate using FLEE (fast lightweight expression evalutor)

I'd then send the expression "100 / 170 ^2" to be compiled and return it's value to the property

But it's taking too much time (around 300 evaluations taking 40 seconds), so I'm not sure this is the best method. I'm already storing an expression final form and it's result, so I don't have to evaluate again if it has already been evaluated.

What changes can I do to improve performance?

    Expressions = expressionsLibrary.ToList();
```
</li>
<li>
<pre class="lang-cs prettyprint-override"><code>    public string? BMI
    {
        get
        {
            return RetrieveValue("BMI");
        }
        set
        {
            return;
        }
    }
</code>```

    public string RetrieveValue(string propertyName)
    {
        // Retrieve property expression from list
        var result = Expressions.FirstOrDefault(e => d.Name == propertyName) ?? null;
        object value = result.Value;

        // Check for null
        if (result is null)
        {
            return null;
        }
        else if (!(result.Value is null) && result.ValueTrim().StartsWith('='))
        {
            // Replace refferences for numeric valuess
            var replaced = ReplaceRefferences(result.Value)GetAwaiter().GetResult();

            // If I didn't evaluate this expression yet, or it has changed
            if (string.IsNullOrEmpty(result.ReplacedValue) || resultado.ReplacedValue != replaced)
            {
                var index = Expressions.IndexOf(result);

                // Updates expression in list
                Expressions[index].ReplacedValue = replaced;

                // Evaluate
                value = Eval(replaced);

                // Updates value in list
                Expressions[index].EvaluatedValue = value;
            }
            else
            {
                value = result.EvaluatedValue;
            }
        }

        return Convert.ToString(value);
    }
```
</li>
<li>
<pre class="lang-cs prettyprint-override"><code>    private string Eval(String expression)
    {
        cExpressionContext context = new ExpressionContext();

        context.ParserOptions.RecreateParser();

        // Allow the expression to use all static public methods of System.Math
        context.Imports.AddType(typeof(Math));

        Flee.PublicTypes.IDynamicExpression eDynamic = context.CompileDynamic(expression);

        return Convert.ToString(eDynamic.Evaluate());
    }
</code>```

I'm already storing an expression final form and it's result, so I don't have to evaluate again if it has already been evaluated. It works well with a few expressions per call (10 or so)

Body:
I'm developing an application that works like an excel sheet: the user types a few values, and a lot of consequent calculation is done, in Blazor.

Right now I'm following this sequence (simplified code can be found at the end of question):

Retrieve all expressions from DB into a List.

The expressions can be written by the user, in another section. For example, the user can insert that BMI formula is "= @Weight / @Height ^2"

Each property call "RetrieveValue(propertyName)"

Substitute refferences in expression for it's value

That means, if the expression is "= @Weight / @Height ^ 2", I'll replace '@Weight' and '@Height' for either user-typed values, or for values from other expressions

Evaluate using FLEE (fast lightweight expression evalutor)

I'd then send the expression "100 / 170 ^2" to be compiled and return it's value to the property

But it's taking too much time (around 300 evaluations taking 40 seconds), so I'm not sure this is the best method. I'm already storing an expression final form and it's result, so I don't have to evaluate again if it has already been evaluated.

What changes can I do to improve performance?

    Expressions = expressionsLibrary.ToList();

    public string? BMI
    {
        get
        {
            return RetrieveValue("BMI");
        }
        set
        {
            return;
        }
    }

    public string RetrieveValue(string propertyName)
    {
        // Retrieve property expression from list
        var result = Expressions.FirstOrDefault(e => d.Name == propertyName) ?? null;
        object value = result.Value;

        // Check for null
        if (result is null)
        {
            return null;
        }
        else if (!(result.Value is null) && result.ValueTrim().StartsWith('='))
        {
            // Replace refferences for numeric valuess
            var replaced = ReplaceRefferences(result.Value)GetAwaiter().GetResult();

            // If I didn't evaluate this expression yet, or it has changed
            if (string.IsNullOrEmpty(result.ReplacedValue) || resultado.ReplacedValue != replaced)
            {
                var index = Expressions.IndexOf(result);

                // Updates expression in list
                Expressions[index].ReplacedValue = replaced;

                // Evaluate
                value = Eval(replaced);

                // Updates value in list
                Expressions[index].EvaluatedValue = value;
            }
            else
            {
                value = result.EvaluatedValue;
            }
        }

        return Convert.ToString(value);
    }

    private string Eval(String expression)
    {
        cExpressionContext context = new ExpressionContext();

        context.ParserOptions.RecreateParser();

        // Allow the expression to use all static public methods of System.Math
        context.Imports.AddType(typeof(Math));

        Flee.PublicTypes.IDynamicExpression eDynamic = context.CompileDynamic(expression);

        return Convert.ToString(eDynamic.Evaluate());
    }

I'm already storing an expression final form and it's result, so I don't have to evaluate again if it has already been evaluated. It works well with a few expressions per call (10 or so)


问:
Shiny app deployment error on shinyapps.io
I am trying to deploy shiny app on shinyapps.io but keep getting the error:

```<code>Error in curl::curl_fetch_memory(url, handle = handle) :
  Failure when receiving data from the peer
Calls: <Anonymous> ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Timing stopped at: 0.01 0 0.57
Execution halted
</code>```

What is the reason for it and how I can fix it?

I tried to change proxy but it didn't help

Body:
I am trying to deploy shiny app on shinyapps.io but keep getting the error:

Error in curl::curl_fetch_memory(url, handle = handle) :
  Failure when receiving data from the peer
Calls: <Anonymous> ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Timing stopped at: 0.01 0 0.57
Execution halted

What is the reason for it and how I can fix it?

I tried to change proxy but it didn't help


问:
Is there any other ways to send data from frontend to backend
I begin making a rating component and I'm supposed to send the rating data to the backend after the visitor selects a rating and hits the submit button, I can do it just using HTML form and submit it but my question is, is there any other ways to send this data to the backend if so what are they?

What would happen if I use JavaScript fetch to post this data to the backend or Axios?


问:
Improving python code - Object Oriented (writing a deposit and charging code for bank)
I wrote 2 codes for a task that asked for a code to be used for the deposit and charging functions, and I want to see if there is a way to improve my code; make it more generic, or use __init__ function for if for example.

```<code>class Account:
    last_id = 1000

    def __init__(self, customer):
        self.customer = customer
        Account.last_id += 1
        self.id = Account.last_id
        self._balance = 0

#deposit

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            print('Deposit: ' + str(self._balance))
        else:
            print('Operation was successful')
        pass

#charge

    def charge(self, amount):
        if amount > self._balance:
            raise NotEnoughBalanceException(
                "Not enough balance in your account " + str(self._balance))

        if amount <= 0:
            raise NegativeAmountException("Operation can't be done. Choose another amount")
        else:
            pass
</code>```

Body:
I wrote 2 codes for a task that asked for a code to be used for the deposit and charging functions, and I want to see if there is a way to improve my code; make it more generic, or use __init__ function for if for example.

class Account:
    last_id = 1000

    def __init__(self, customer):
        self.customer = customer
        Account.last_id += 1
        self.id = Account.last_id
        self._balance = 0

#deposit

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            print('Deposit: ' + str(self._balance))
        else:
            print('Operation was successful')
        pass

#charge

    def charge(self, amount):
        if amount > self._balance:
            raise NotEnoughBalanceException(
                "Not enough balance in your account " + str(self._balance))

        if amount <= 0:
            raise NegativeAmountException("Operation can't be done. Choose another amount")
        else:
            pass


问:
upload and get files to frontend
im having truble to get files after uploading them, i used multer in the backend and here is my fileUpload code.. i don't undrestand what's not working well n how to fix it.. any help please ?i know my code don't seems pretty, i'm a junior dev and this is my first fullstack project..
file supported (/jpeg|jpg|png|pdf|doc|txt/) thank you

```<code>import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import Form from 'react-bootstrap/Form'

function FileUpload() {

    const [file, setFile] = useState([]);

    //const [fileName, setFileName] = useState("");

    const saveFile = (e) => {
        console.log(e.target.files)
        setFile(e.target.files[0]);
        //setFileName(e.target.files[0].name);
    };

    const uploadFile = async (e) => { console.log("hello")
        const formData = new FormData();
        formData.append("files", file);
        //formData.append("fileName", fileName);

        const config = {
    headers: { 'content-type': 'multipart/form-data' }
}
        try {
            const res = await axios.post(
                "http://localhost:8000/imageAPI/newImage",
            formData, config
        );
        } catch (ex) {
        }
    };

        return (
            <div className="upld">
                <Form.Group controlId="formFileLg" className="mb-3">
                    <Form.Label>choose your file from here</Form.Label>
                    <Form.Control type="file" size="lg" onChange={saveFile} />
                    <div>{file && `${file.name} - ${file.files} - ${file.description}`}</div>
                </Form.Group>
                <button className='w-25 mb-4' size='md' onClick={uploadFile}>Upload</button>
                <img scr={file}/>
            </div>
        );
    }

export default FileUpload;
</code>```

every single search i made i found the same code or similar to mine so i'm kind of stuck here

Title: upload and get files to frontend

Body:
im having truble to get files after uploading them, i used multer in the backend and here is my fileUpload code.. i don't undrestand what's not working well n how to fix it.. any help please ?i know my code don't seems pretty, i'm a junior dev and this is my first fullstack project..
file supported (/jpeg|jpg|png|pdf|doc|txt/) thank you

import React from 'react'
import axios from 'axios';
import { useState } from 'react';
import Form from 'react-bootstrap/Form'

function FileUpload() {

    const [file, setFile] = useState([]);

    //const [fileName, setFileName] = useState("");

    const saveFile = (e) => {
        console.log(e.target.files)
        setFile(e.target.files[0]);
        //setFileName(e.target.files[0].name);
    };

    const uploadFile = async (e) => { console.log("hello")
        const formData = new FormData();
        formData.append("files", file);
        //formData.append("fileName", fileName);

        const config = {
    headers: { 'content-type': 'multipart/form-data' }
}
        try {
            const res = await axios.post(
                "http://localhost:8000/imageAPI/newImage",
            formData, config
        );
        } catch (ex) {
        }
    };

        return (

                <Form.Group controlId="formFileLg" className="mb-3">
                    <Form.Label>choose your file from here</Form.Label>
                    <Form.Control type="file" size="lg" onChange={saveFile} />

{file && `${file.name} - ${file.files} - ${file.description}`}

                </Form.Group>
                <button className='w-25 mb-4' size='md' onClick={uploadFile}>Upload</button>

        );
    }

export default FileUpload;

every single search i made i found the same code or similar to mine so i'm kind of stuck here


问:
No button "Next" on CloudFormation - AWS - Forecast
I'm trying to use CloudFormation (AWS) to try Forecast. I'm following this tuto.

However, I don't have the button "Next" at the end of step 1 I d'ont have the expected button "Next" like we can see in the picture below :

I have the following screen :

What should I do to get the orange "Next" button ? What do I'm missing ?


问:
How to increase the size of Textarea when the cursor reaches last line using React
I have a textarea in which I have a button as well in the bottom right corner.

Everything looks great unless I add more words and it overlaps the button.

What I want to do is as soon as someone reaches the last line, the size of the textarea increases automatically. I have found one solution in codepen - https://codepen.io/anon/pen/gLdRXE
But I am not sure how to implement the same using React. Also, I am using textarea and not input tag.

```<code>textarea{
  width:100%;
  min-height:80px;
  max-height:200px;
  overflow:auto;
  resize:vertical;
}
</code>```
```<code>var textarea = document.querySelector('textarea');

textarea.addEventListener('keydown', autosize);

function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}
</code>```

Many thanks

Body:
I have a textarea in which I have a button as well in the bottom right corner.

Everything looks great unless I add more words and it overlaps the button.

What I want to do is as soon as someone reaches the last line, the size of the textarea increases automatically. I have found one solution in codepen - https://codepen.io/anon/pen/gLdRXE
But I am not sure how to implement the same using React. Also, I am using textarea and not input tag.

textarea{
  width:100%;
  min-height:80px;
  max-height:200px;
  overflow:auto;
  resize:vertical;
}

var textarea = document.querySelector('textarea');

textarea.addEventListener('keydown', autosize);

function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}

Many thanks


问:
Selecting all check boxes of one group when select all is clicked in React
I am showing permissions for my project in an accordion which whose title is the group from which the permission belongs, I have put select all checkbox in each accordion now I want to check the select all checkbox and all the check boxes in that accordion only gets selected and their ids being pushed in the array which will be then passed to PHP API. Here is the code:

```<code>const Add_AssignPermission = () => {
    const [permissionData, setPermissionData] = useState([])
    const [roleData, setRoleData] = useState([])
    const [selectedRole, setSelectedRole] = useState('')
    const [selectedPermission, setSelectedPermission] = useState('')
    const [checkPermission, setCheckedPermission] = useState([])
    const { role_id } = useParams()

    function getPermissionData() {
        const url = '/permission?length=10000'
        axios.get(url)
            .then((response) => {
                console.log(response)
                setPermissionData(response.data.data.data)
                setSelectedPermission(response.data.data.data[0].id)
            })
            .catch((err) => console.log(err))
    }

    function getRoleData() {
        const url = '/roles'
        axios.get(url)
            .then((response) => {
                console.log(response)
                setRoleData(response.data.data.data)
                setSelectedRole(response.data.data.data[0].id)
            })
            .catch((err) => console.log(err))
    }

    const [successMessage, setSuccessMessage] = useState(null)

    useEffect(() => {
        getPermissionData()
        getRoleData()
    }, [])

    useEffect(() => {
        window.scrollTo(0, 0)
    }, [successMessage])

    const resetForm = () => {
        setPermissionData("")
        setRoleData("")
    }

    function submit(event, errors, values) {

        event.preventDefault()
        if (errors.length < 1) {
            const body = {
                checkedPermission: checkPermission
            }
            const config = {
                method: 'post',
                url: `/assignPermissiontoRole/${role_id}`,
                headers: AuthHeader(),
                data: body
            }
            console.log(config)
            axios(config)
            // const response = axios.post(`/assignPermissiontoRole/${role_id}`, checkPermission)
            // console.log(response)
            .then(function (response) {
                console.log(response)
                    setSuccessMessage("Permissions Assigned Successfully")
                    getPermissionData()
                    getRoleData()
                })
                .catch(function (error) {
                    console.log(error)
                    setSuccessMessage(null)
                })
        }
    }

    return (
        <>
        <Card>
            <CardHeader>
                <CardTitle tag="h4">Assign A New Permission to Role</CardTitle>
            </CardHeader>
                {/* {successMessage && <Alert> {successMessage}</Alert>}
                <AvForm
                    onSubmit={(event, errors, values) => submit(event, errors, values)
                    }
                >
                    <Row>
                        <Col sm ='12' md='6'>
                        <Row>
                            <Col sm='6'>
                                <AvGroup>
                                    <Label> Permission Name </Label>
                                    <AvInput
                                        name="permission"
                                        id="permission"
                                        type = "select"
                                        onChange={(e) => setSelectedPermission(e.target.value)}
                                        required
                                        value = {selectedPermission}
                                    >
                                    {permissionData.map((value, key) => {
                                        // let permissionName =  properCase(value.name, '-')
                                        // permissionName = properCase(permissionName, '_')
                                        return (
                                            <option value={value.id} key={key}>
                                                {value.name}
                                            </option>
                                        )
                                    })}
                                    </AvInput>
                                <AvFeedback>Please enter a Permission!</AvFeedback>
                                </AvGroup>
                            </Col>

                            <Col sm='6'>
                                <AvGroup>
                                    <Label> Role Name </Label>
                                    <AvInput
                                        name="role"
                                        id="role"
                                        type = "select"
                                        onChange={(e) => setSelectedRole(e.target.value)}
                                        required
                                        value = {selectedRole}
                                    >
                                    {roleData.map((value, key) => {
                                        const roleName =  properCase(value.name, '_')
                                        return (
                                            <option value={value.id} key={key}>
                                                {roleName}
                                            </option>
                                        )
                                    })}
                                    </AvInput>
                                <AvFeedback>Please enter a Role!</AvFeedback>
                                </AvGroup>
                            </Col>
                      </Row>
                        </Col>
                        <Col sm ='12' md='6' className = 'align-self-center mt-75'>
                        <AvGroup className="d-flex mb-0">
                        <Button.Ripple
                            className="mr-1"
                            color="primary"
                            type="submit"
                        >
                            Submit
                        </Button.Ripple>
                        <Button outline color='secondary' onClick={resetForm}>
                            Reset
                        </Button>
                    </AvGroup>
                    </Col>
                    </Row>

                </AvForm> */}
            {successMessage && <Alert> {successMessage}</Alert>}
        </Card>
        <Row>
        <Col sm="12">
        <AvForm onSubmit={(event, errors, values) => submit(event, errors, values)} >
            {permissionData.map((ele) => {
                return (
                <Accordion title={ele.group_name} Open={true} key={ele.group_name}>
                <Row>
                    <Col sm='3'>
                        <AvGroup>
                        <AvInput type='checkbox' name='select_all_checkbox' id='select_all_checkbox'
                        //onChange={handleChange}
                         onChange={(e) => {
                          if (e.target.checked) {
                                ele.grouped_permissions.map((permissions) => {
                                        setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            id: permissions.permission_id
                                        }
                                    ])
                                    })
                                    console.log(checkPermission)
                             } else {
                                console.log("IN ELSE")
                             }
                         }}
                         />
                         {console.log(checkPermission)}
                         <Label for='decimal_point_in_valueVertical'>Select All</Label>
                    </AvGroup>

                    {/* <AvGroup>
                        <AvInput type='checkbox' name='select_all_checkbox' id='select_all_checkbox'
                        //onChange={handleChange}
                         onChange={(e) => {
                          if (e.target.checked) {
                                ele.grouped_permissions.map((permissions) => {
                                        setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            id: permissions.permission_id
                                        }
                                    ])
                                    })
                                    console.log(checkPermission)
                             } else {
                                console.log("IN ELSE")
                             }
                         }}
                         />
                         {console.log(checkPermission)}
                         <Label for='decimal_point_in_valueVertical'>Select All</Label>
                    </AvGroup> */}
                    </Col>
                    {ele.grouped_permissions.map((ele2) => {
                        return (
                            <Col sm='3' key={ele2.permissions.name}>
                        <AvGroup>
                            <AvInput type='checkbox' name='permission_checkbox' id='permission_checkbox'
                            //key={ele2.permissions.name}
                             onChange={(e) => {
                                console.log(e.target)
                                if (e.target.checked) {
                                    setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            // id: ele2.permissions.id
                                            id: ele2.permissions.id
                                        }
                                    ])
                                    //console.log(checkPermission)
                                } else {
                                    setCheckedPermission(
                                        checkPermission.filter((checkedBox) => checkedBox.id !== ele2.permissions.id)
                                    )
                                }
                             }}
                             data={ele2.permissions.id}
                             value={checkPermission}
                             />
                            <Label for='decimal_point_in_valueVertical'>{ele2.permissions.name}</Label>
                            {/* <AvInput type='text' name='mask_name' id='mask_name' placeholder='mask_name'
                            /> */}
                        </AvGroup>
                    </Col>
                        )
                    })}
                </Row>
                </Accordion>
                )
            })}
            <Col sm='12'>
                    <AvGroup className='d-flex mb-0 float-right'>
                        <Button.Ripple className='mr-1' color='primary' type='submit' >
                            Assign Permission
                                </Button.Ripple>
                        </AvGroup>
                    </Col>
            </AvForm>
        </Col>
    </Row>
    </>
    )
}

export default Add_AssignPermission
</code>```

I have tried multiple things but nothing worked for me. In the above code snippet I was trying to push that group values into the state using map but when I consoled it contains only the last permission id in the accordion. PLEASE HELP !!!!

Body:
I am showing permissions for my project in an accordion which whose title is the group from which the permission belongs, I have put select all checkbox in each accordion now I want to check the select all checkbox and all the check boxes in that accordion only gets selected and their ids being pushed in the array which will be then passed to PHP API. Here is the code:

const Add_AssignPermission = () => {
    const [permissionData, setPermissionData] = useState([])
    const [roleData, setRoleData] = useState([])
    const [selectedRole, setSelectedRole] = useState('')
    const [selectedPermission, setSelectedPermission] = useState('')
    const [checkPermission, setCheckedPermission] = useState([])
    const { role_id } = useParams()

    function getPermissionData() {
        const url = '/permission?length=10000'
        axios.get(url)
            .then((response) => {
                console.log(response)
                setPermissionData(response.data.data.data)
                setSelectedPermission(response.data.data.data[0].id)
            })
            .catch((err) => console.log(err))
    }

    function getRoleData() {
        const url = '/roles'
        axios.get(url)
            .then((response) => {
                console.log(response)
                setRoleData(response.data.data.data)
                setSelectedRole(response.data.data.data[0].id)
            })
            .catch((err) => console.log(err))
    }

    const [successMessage, setSuccessMessage] = useState(null)

    useEffect(() => {
        getPermissionData()
        getRoleData()
    }, [])

    useEffect(() => {
        window.scrollTo(0, 0)
    }, [successMessage])

    const resetForm = () => {
        setPermissionData("")
        setRoleData("")
    }

    function submit(event, errors, values) {

        event.preventDefault()
        if (errors.length < 1) {
            const body = {
                checkedPermission: checkPermission
            }
            const config = {
                method: 'post',
                url: `/assignPermissiontoRole/${role_id}`,
                headers: AuthHeader(),
                data: body
            }
            console.log(config)
            axios(config)
            // const response = axios.post(`/assignPermissiontoRole/${role_id}`, checkPermission)
            // console.log(response)
            .then(function (response) {
                console.log(response)
                    setSuccessMessage("Permissions Assigned Successfully")
                    getPermissionData()
                    getRoleData()
                })
                .catch(function (error) {
                    console.log(error)
                    setSuccessMessage(null)
                })
        }
    }

    return (
        <>
        <Card>
            <CardHeader>
                <CardTitle tag="h4">Assign A New Permission to Role</CardTitle>
            </CardHeader>
                {/* {successMessage && <Alert> {successMessage}</Alert>}
                <AvForm
                    onSubmit={(event, errors, values) => submit(event, errors, values)
                    }
                >
                    <Row>
                        <Col sm ='12' md='6'>
                        <Row>
                            <Col sm='6'>
                                <AvGroup>
                                     Permission Name
                                    <AvInput
                                        name="permission"
                                        id="permission"
                                        type = "select"
                                        onChange={(e) => setSelectedPermission(e.target.value)}
                                        required
                                        value = {selectedPermission}
                                    >
                                    {permissionData.map((value, key) => {
                                        // let permissionName =  properCase(value.name, '-')
                                        // permissionName = properCase(permissionName, '_')
                                        return (
                                            <option value={value.id} key={key}>
                                                {value.name}
                                            </option>
                                        )
                                    })}
                                    </AvInput>
                                <AvFeedback>Please enter a Permission!</AvFeedback>
                                </AvGroup>
                            </Col>

                            <Col sm='6'>
                                <AvGroup>
                                     Role Name
                                    <AvInput
                                        name="role"
                                        id="role"
                                        type = "select"
                                        onChange={(e) => setSelectedRole(e.target.value)}
                                        required
                                        value = {selectedRole}
                                    >
                                    {roleData.map((value, key) => {
                                        const roleName =  properCase(value.name, '_')
                                        return (
                                            <option value={value.id} key={key}>
                                                {roleName}
                                            </option>
                                        )
                                    })}
                                    </AvInput>
                                <AvFeedback>Please enter a Role!</AvFeedback>
                                </AvGroup>
                            </Col>
                      </Row>
                        </Col>
                        <Col sm ='12' md='6' className = 'align-self-center mt-75'>
                        <AvGroup className="d-flex mb-0">
                        <Button.Ripple
                            className="mr-1"
                            color="primary"
                            type="submit"
                        >
                            Submit
                        </Button.Ripple>
                        <Button outline color='secondary' onClick={resetForm}>
                            Reset
                        </Button>
                    </AvGroup>
                    </Col>
                    </Row>

                </AvForm> */}
            {successMessage && <Alert> {successMessage}</Alert>}
        </Card>
        <Row>
        <Col sm="12">
        <AvForm onSubmit={(event, errors, values) => submit(event, errors, values)} >
            {permissionData.map((ele) => {
                return (
                <Accordion title={ele.group_name} Open={true} key={ele.group_name}>
                <Row>
                    <Col sm='3'>
                        <AvGroup>
                        <AvInput type='checkbox' name='select_all_checkbox' id='select_all_checkbox'
                        //onChange={handleChange}
                         onChange={(e) => {
                          if (e.target.checked) {
                                ele.grouped_permissions.map((permissions) => {
                                        setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            id: permissions.permission_id
                                        }
                                    ])
                                    })
                                    console.log(checkPermission)
                             } else {
                                console.log("IN ELSE")
                             }
                         }}
                         />
                         {console.log(checkPermission)}
                         Select All
                    </AvGroup>

                    {/* <AvGroup>
                        <AvInput type='checkbox' name='select_all_checkbox' id='select_all_checkbox'
                        //onChange={handleChange}
                         onChange={(e) => {
                          if (e.target.checked) {
                                ele.grouped_permissions.map((permissions) => {
                                        setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            id: permissions.permission_id
                                        }
                                    ])
                                    })
                                    console.log(checkPermission)
                             } else {
                                console.log("IN ELSE")
                             }
                         }}
                         />
                         {console.log(checkPermission)}
                         Select All
                    </AvGroup> */}
                    </Col>
                    {ele.grouped_permissions.map((ele2) => {
                        return (
                            <Col sm='3' key={ele2.permissions.name}>
                        <AvGroup>
                            <AvInput type='checkbox' name='permission_checkbox' id='permission_checkbox'
                            //key={ele2.permissions.name}
                             onChange={(e) => {
                                console.log(e.target)
                                if (e.target.checked) {
                                    setCheckedPermission([
                                        ...checkPermission,
                                        {
                                            // id: ele2.permissions.id
                                            id: ele2.permissions.id
                                        }
                                    ])
                                    //console.log(checkPermission)
                                } else {
                                    setCheckedPermission(
                                        checkPermission.filter((checkedBox) => checkedBox.id !== ele2.permissions.id)
                                    )
                                }
                             }}
                             data={ele2.permissions.id}
                             value={checkPermission}
                             />
                            {ele2.permissions.name}
                            {/* <AvInput type='text' name='mask_name' id='mask_name' placeholder='mask_name'
                            /> */}
                        </AvGroup>
                    </Col>
                        )
                    })}
                </Row>
                </Accordion>
                )
            })}
            <Col sm='12'>
                    <AvGroup className='d-flex mb-0 float-right'>
                        <Button.Ripple className='mr-1' color='primary' type='submit' >
                            Assign Permission
                                </Button.Ripple>
                        </AvGroup>
                    </Col>
            </AvForm>
        </Col>
    </Row>
    </>
    )
}

export default Add_AssignPermission

I have tried multiple things but nothing worked for me. In the above code snippet I was trying to push that group values into the state using map but when I consoled it contains only the last permission id in the accordion. PLEASE HELP !!!!


问:
Nginx and UWSGI Timeout
I am trying to deploy my keras model using a flask rest api with Nginx and Uwsgi. it works fine with flask on port 5000. I need to upload large files(>500mb) which need  to be processed and then predictions made( The process takes 10-15 minute). However I get 499 status code on Nginx logs and 503 error from the request made.

My nginx.conf file

```<code>server{
    listen 80;

    client_max_body_size 5g;
    client_body_buffer_size 1000m;

    proxy_connect_timeout   3000s;
    proxy_send_timeout      3000s;
    proxy_read_timeout      3000s;

    include uwsgi_params;
    uwsgi_connect_timeout   3000s;
    uwsgi_read_timeout  3000s;
    uwsgi_send_timeout  3000s;
    uwsgi_socket_keepalive  on;
    uwsgi_max_temp_file_size 1000m;

    client_body_timeout     3000;
    client_header_timeout   3000;
    keepalive_timeout       3000;
    send_timeout        3000;

    location / {

        client_body_buffer_size 10000m;

        include uwsgi_params;
        uwsgi_pass myapp:5000;

    proxy_connect_timeout   3000s;
    proxy_send_timeout      3000s;
    proxy_read_timeout      3000s;

    uwsgi_read_timeout 3000;
    uwsgi_send_timeout 3000;
    uwsgi_socket_keepalive  on;
    }
}
</code>```

and my uwsgi.ini file

```<code>[uwsgi]
module = app:app
callabale = app
socket = :5000
processes = 1
threads = 2
master = true
chmod-socket = 660
vaccum = true
die-on-term = true
lazy-apps = true
socket-timeout = 3000
socket-send-timeout = 3000
socket-write-timeout = 3000
http-timeout = 3000
http-keepalive = 1
so-keepalive = true
so-send-timeout = 3000
socket-write-timeout = 3000
</code>```

Title: Nginx and UWSGI Timeout

Body:
I am trying to deploy my keras model using a flask rest api with Nginx and Uwsgi. it works fine with flask on port 5000. I need to upload large files(>500mb) which need  to be processed and then predictions made( The process takes 10-15 minute). However I get 499 status code on Nginx logs and 503 error from the request made.

My nginx.conf file

server{
    listen 80;

    client_max_body_size 5g;
    client_body_buffer_size 1000m;

    proxy_connect_timeout   3000s;
    proxy_send_timeout      3000s;
    proxy_read_timeout      3000s;

    include uwsgi_params;
    uwsgi_connect_timeout   3000s;
    uwsgi_read_timeout  3000s;
    uwsgi_send_timeout  3000s;
    uwsgi_socket_keepalive  on;
    uwsgi_max_temp_file_size 1000m;

    client_body_timeout     3000;
    client_header_timeout   3000;
    keepalive_timeout       3000;
    send_timeout        3000;

    location / {

        client_body_buffer_size 10000m;

        include uwsgi_params;
        uwsgi_pass myapp:5000;

    proxy_connect_timeout   3000s;
    proxy_send_timeout      3000s;
    proxy_read_timeout      3000s;

    uwsgi_read_timeout 3000;
    uwsgi_send_timeout 3000;
    uwsgi_socket_keepalive  on;
    }
}

and my uwsgi.ini file

[uwsgi]
module = app:app
callabale = app
socket = :5000
processes = 1
threads = 2
master = true
chmod-socket = 660
vaccum = true
die-on-term = true
lazy-apps = true
socket-timeout = 3000
socket-send-timeout = 3000
socket-write-timeout = 3000
http-timeout = 3000
http-keepalive = 1
so-keepalive = true
so-send-timeout = 3000
socket-write-timeout = 3000


问:
After oracle client upgrade from v11 to v12 getting System.InvalidOperationException: Operation is not valid due to the current state of the object
After I upgraded oracle client version 11 to 12.2, asp.net application start to give:

```<code>System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at Oracle.DataAccess.Client.OracleTransaction.Commit()
</code>```

Nothing changed in the code, and it works in v11 without any errors.

I believe there is something btw v11 and v12.2 to create such a this error, but cant figure out from oracle support cases.

Body:
After I upgraded oracle client version 11 to 12.2, asp.net application start to give:

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at Oracle.DataAccess.Client.OracleTransaction.Commit()

Nothing changed in the code, and it works in v11 without any errors.

I believe there is something btw v11 and v12.2 to create such a this error, but cant figure out from oracle support cases.


问:
Not able to connect to MySQL database when reading db parameters from config file
Okay.. I'm having a really strange issue and not able to figure out why it's happening. I have an AWS lambda function (Node.js) which connects to a MySQL database.

When DB parameters are hardcoded in Node.js, it works fine.  Please see below.

```<code>const con = mysql.createConnection({
    host     : "myapp.something.us-west-2.rds.amazonaws.com",
    user     : "someuser",
    password : "somepassword",
    port     : "3306",
    database : "somedatabse"
});
const query = util.promisify(con.query).bind(con);
</code>```

When I try to connect to the DB by reading these parameters from a config file or lambda environment variables, I get this error.

"ERROR Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)"

```<code>const con = mysql.createConnection({
    host     : dbHost,
    user     : dbUser,
    password : dbPassword,
    port     : dbPort,
    database : dbName
});
const query = util.promisify(con.query).bind(con);

// Retrieving DB parameters from my config file like this.  Values are being retrieved successfully.
dbHost = dbConfig.dev_db_host;
dbUser = dbConfig.dev_db_user;
dbPassword = dbConfig.dev_db_password;
dbPort = dbConfig.dev_db_port;
dbName = dbConfig.dev_db_name;

// Able to log all these values correctly.
console.log(dbHost); // myapp.something.us-west-2.rds.amazonaws.com
console.log(dbUser);// someuser
console.log(dbPassword); // somepassword
console.log(dbPort); // 3306
console.log(dbName); // somedatabase
</code>```

Note - I am able to retrieve the values successfully from config file.  I verified by logging the info.  Not sure why the DB connection is failing.

Also, I run into the exact same issue when I read the DB parameters from lambda environment variables.
Any help is appreciated.  Thanks in advance!

Body:
Okay.. I'm having a really strange issue and not able to figure out why it's happening. I have an AWS lambda function (Node.js) which connects to a MySQL database.

When DB parameters are hardcoded in Node.js, it works fine.  Please see below.

const con = mysql.createConnection({
    host     : "myapp.something.us-west-2.rds.amazonaws.com",
    user     : "someuser",
    password : "somepassword",
    port     : "3306",
    database : "somedatabse"
});
const query = util.promisify(con.query).bind(con);

When I try to connect to the DB by reading these parameters from a config file or lambda environment variables, I get this error.

"ERROR Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)"

const con = mysql.createConnection({
    host     : dbHost,
    user     : dbUser,
    password : dbPassword,
    port     : dbPort,
    database : dbName
});
const query = util.promisify(con.query).bind(con);

// Retrieving DB parameters from my config file like this.  Values are being retrieved successfully.
dbHost = dbConfig.dev_db_host;
dbUser = dbConfig.dev_db_user;
dbPassword = dbConfig.dev_db_password;
dbPort = dbConfig.dev_db_port;
dbName = dbConfig.dev_db_name;

// Able to log all these values correctly.
console.log(dbHost); // myapp.something.us-west-2.rds.amazonaws.com
console.log(dbUser);// someuser
console.log(dbPassword); // somepassword
console.log(dbPort); // 3306
console.log(dbName); // somedatabase

Note - I am able to retrieve the values successfully from config file.  I verified by logging the info.  Not sure why the DB connection is failing.

Also, I run into the exact same issue when I read the DB parameters from lambda environment variables.
Any help is appreciated.  Thanks in advance!


问:
How to get rid of google dialogue using speech to text in android studio?
TEST#

Is there a way to hide it? or remove it for popping pop?


问:
Is there a way to add the OpenGL documentation to Visual Studio to see it on hover?
Is there a way to add hover documentation functionality for OpenGL in Visual Studio? Or if a library doesn't have it built in am I stuck looking at the online documentation?

A lot of libraries that I install allow me to see the documentation on hover. From what I could tell, the hover documentation summary/parameters/returns are generated from XML comments within the library.


问:
Excel javascript function always returning undefined
I'm new to javascript and I'm struggling to return a value from what seems to be a synchronous function.

Here is the calling code:

```<code>async function testPromises() {
  await Excel.run(async (context) => {
    const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      findLatestRoundInLMS()
      .then((value) => {
        console.log('Returned data = "' + value + '"');
        resolve(value);
        })
      }, 2000);
    });
  });
} // end of testPromises function
</code>```

Here is the function:

```<code>// Activate Sheet and find latest round
async function findLatestRoundInLMS() {
  await Excel.run(async (context) => {
    const sLMS = context.workbook.worksheets.getItemOrNullObject("LMS");

    //  Search LMS tab for latest Round
    let sourceRangeLMS;
    let j;

    sLMS.activate();
    await context.sync();

    sourceRangeLMS = sLMS.getRange("A1:CC1");
    sourceRangeLMS.load("values");
    await context.sync();

    for (j = 3; j < 53; j += 4) {
      if (sourceRangeLMS.values[0][j] > 0) {
        if (sourceRangeLMS.values[0][j + 4] === 0) {
          console.log("LMS index for current Round, j = " + j);
          break;
        } // end of IF
      } // end of IF
    } // end of FOR
    console.log("Returning current Round Index, j = " + j);
    await context.sync();
    return j;
  });
}

</code>```

I've read lots about promises and watched some good YouTube videos but still cannot get the value to return to the calling code.  Any help would be much appreciated.

I've tried several versions of promises and queues using .then coding to no avail.

Body:
I'm new to javascript and I'm struggling to return a value from what seems to be a synchronous function.

Here is the calling code:

async function testPromises() {
  await Excel.run(async (context) => {
    const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      findLatestRoundInLMS()
      .then((value) => {
        console.log('Returned data = "' + value + '"');
        resolve(value);
        })
      }, 2000);
    });
  });
} // end of testPromises function

Here is the function:

// Activate Sheet and find latest round
async function findLatestRoundInLMS() {
  await Excel.run(async (context) => {
    const sLMS = context.workbook.worksheets.getItemOrNullObject("LMS");

    //  Search LMS tab for latest Round
    let sourceRangeLMS;
    let j;

    sLMS.activate();
    await context.sync();

    sourceRangeLMS = sLMS.getRange("A1:CC1");
    sourceRangeLMS.load("values");
    await context.sync();

    for (j = 3; j < 53; j += 4) {
      if (sourceRangeLMS.values[0][j] > 0) {
        if (sourceRangeLMS.values[0][j + 4] === 0) {
          console.log("LMS index for current Round, j = " + j);
          break;
        } // end of IF
      } // end of IF
    } // end of FOR
    console.log("Returning current Round Index, j = " + j);
    await context.sync();
    return j;
  });
}

I've read lots about promises and watched some good YouTube videos but still cannot get the value to return to the calling code.  Any help would be much appreciated.

I've tried several versions of promises and queues using .then coding to no avail.


问:
Load Error on C extension of Cached Ruby gem in Rails
For a Rails app, I have a gitlab CI/CD set up with three stages. First stage is caching of gems and assets.

```<code>cache: &default-cache
  untracked: true
  key: "assets-compile:vendor_ruby:.yarn-cache:tmp_cache_assets_sprockets:v3"
  paths:
    - vendor/ruby/
    - .yarn-cache/
    - public/assets/
    - node_modules/
  policy: pull-push
</code>```

In the next stage, I pull from the cached gems in vendor/ruby folder.

```<code>testing:
  cache:
    <<: *default-cache
    policy: pull
  stage: test
  image: "ruby:3.0"
  timeout: one hour
  script:
  - apt-get update -qq && apt-get install -y -qq nodejs
  - export PATH="/usr/local/bundle/bin:$PATH"
  - bundle config set --local path 'vendor/ruby'
  - RAILS_ENV=test bundle install -j $(nproc)
</code>```

This works well, but for a gem 'ox', throws a LoadError

```<code>Failure/Error: require 'ox'

LoadError:
  cannot load such file -- ox/ox
# ./vendor/ruby/ruby/3.0.0/gems/zeitwerk-2.6.6/lib/zeitwerk/kernel.rb:38:in `require'
# ./vendor/ruby/ruby/3.0.0/gems/zeitwerk-2.6.6/lib/zeitwerk/kernel.rb:38:in `require'
# ./vendor/ruby/ruby/3.0.0/gems/ox-2.14.11/lib/ox.rb:79:in `<top (required)>'
</code>```

My understanding is that it is unable to load ox.rb which would be created after the C extension is compiled, which is not happening during caching.

How do I solve this?

I tried removing require: false from the Gemfile, but didn't work.

Body:
For a Rails app, I have a gitlab CI/CD set up with three stages. First stage is caching of gems and assets.

cache: &default-cache
  untracked: true
  key: "assets-compile:vendor_ruby:.yarn-cache:tmp_cache_assets_sprockets:v3"
  paths:
    - vendor/ruby/
    - .yarn-cache/
    - public/assets/
    - node_modules/
  policy: pull-push

In the next stage, I pull from the cached gems in vendor/ruby folder.

testing:
  cache:
    <<: *default-cache
    policy: pull
  stage: test
  image: "ruby:3.0"
  timeout: one hour
  script:
  - apt-get update -qq && apt-get install -y -qq nodejs
  - export PATH="/usr/local/bundle/bin:$PATH"
  - bundle config set --local path 'vendor/ruby'
  - RAILS_ENV=test bundle install -j $(nproc)

This works well, but for a gem 'ox', throws a LoadError

Failure/Error: require 'ox'

LoadError:
  cannot load such file -- ox/ox
# ./vendor/ruby/ruby/3.0.0/gems/zeitwerk-2.6.6/lib/zeitwerk/kernel.rb:38:in `require'
# ./vendor/ruby/ruby/3.0.0/gems/zeitwerk-2.6.6/lib/zeitwerk/kernel.rb:38:in `require'
# ./vendor/ruby/ruby/3.0.0/gems/ox-2.14.11/lib/ox.rb:79:in `<top (required)>'

My understanding is that it is unable to load ox.rb which would be created after the C extension is compiled, which is not happening during caching.

How do I solve this?

I tried removing require: false from the Gemfile, but didn't work.


问:
Ending For Loop based on React State
I'm attempting to end a for loop from executing anytime a button is tapped. I was doing so by setting state when the stop button is tapped, then in the for loop have it check in each iteration if the state has changed or not before proceeding. If it's changed, end the for loop execution. I am thinking it has to do with synchronization and maybe the updated state doesn't get reflected until the entire loop is done executing. This seems like a pretty simply use case to solve but maybe I am over thinking it at this point. Any help is appreciated.</p>
```<code>    const onStartScan = () => {
        setIsScanning(true);
        var un = new Array(4000);
        for (var i = 0; i < un.length; i++) {
            if (!isScanning) { break; }
            console.log(un[i]);
        };
        //setIsScanning(false);
    };

    const onStopScan = () => {
        setIsScanning(false);
    };
</code>```
```<code> return (
      <Layout>
        <Layout>
          <Button onPress={onStartScan} disabled={isScanning}>Start Scan</Button>
          <Button onPress={onStopScan} disabled={!isScanning}>Stop Scan</Button>
        </Layout>
      </Layout>

    );
  };
</code>```

Title: Ending For Loop based on React State

Body:
I'm attempting to end a for loop from executing anytime a button is tapped. I was doing so by setting state when the stop button is tapped, then in the for loop have it check in each iteration if the state has changed or not before proceeding. If it's changed, end the for loop execution. I am thinking it has to do with synchronization and maybe the updated state doesn't get reflected until the entire loop is done executing. This seems like a pretty simply use case to solve but maybe I am over thinking it at this point. Any help is appreciated.

    const onStartScan = () => {
        setIsScanning(true);
        var un = new Array(4000);
        for (var i = 0; i < un.length; i++) {
            if (!isScanning) { break; }
            console.log(un[i]);
        };
        //setIsScanning(false);
    };

    const onStopScan = () => {
        setIsScanning(false);
    };

 return (
      <Layout>
        <Layout>
          <Button onPress={onStartScan} disabled={isScanning}>Start Scan</Button>
          <Button onPress={onStopScan} disabled={!isScanning}>Stop Scan</Button>
        </Layout>
      </Layout>

    );
  };


问:
IONIC 6 - ANGULAR app - Android - UI jank, Slow rendering issue
I have IONIC 6 - Angular app deployed on Android that has a video player NGX Videogular embdded within it to play either downloaded videos or those from a CDN.

However, the UI janks after sometime. I think Android simply freezes the UI frame. Only if I perform some action on the app like touching or scrolling the app, the video plays otherwise freezes up completely.

I am not an expert in Android - UI Jank - debugging. With whatever I could search and come up, I was able to enable Hardware rendering on the device and started seeing UI debug bars within the app.

How do I do deeper analysis to find the issue within the app? If the community would be kind enough  to help us with a direction, tool, suggestion, optimization, etc., it will be of supreme help. I am stuck with this issue for 3 months now and discovered UI Jank to be a possible cause only a few days ago.


问:
Hilt using In recyclerView Adapter for Picassso framework
I try to Hilt injection in RecyclerView Adapter but it throw me this error;

public final class RecyclerAdapterPhotos extends androidx.recyclerview.widget.RecyclerView.Adapter<com.packagename.projectName.RecyclerAdapters.RecyclerAdapterPhotos.PhotosVH> {

@AndroidEntryPoint base class must extend ComponentActivity, (support) Fragment, View, Service, or BroadcastReceiver.

Head My adapter.

```<code>

@AndroidEntryPoint
class RecyclerAdapterPhotos(var context:Context, private val photoList:List\<PhotosModelItem\>):RecyclerView.Adapter\<RecyclerAdapterPhotos.PhotosVH\>() {

@Inject
lateinit var imageLoader:ImageLoaderHiltClass

...

override fun onBindViewHolder(holder: PhotosVH, position: Int) {
    imageLoader.imageLoader(photoList[position].thumbnailUrl,holder.photosThumbnailVH)
...
</code>```

Module of Picasso

```<code>@Module
@InstallIn(SingletonComponent::class)
object ImageLoaderModule {
    @Provides
    fun ProvidesImageLoader(photoUri:String,photoVH:ImageView):Picasso{
        return Picasso.get()

    }
</code>```

I try to use Hilt  for Picasso frame in my recyclerView adapter

Body:
I try to Hilt injection in RecyclerView Adapter but it throw me this error;

public final class RecyclerAdapterPhotos extends androidx.recyclerview.widget.RecyclerView.Adapter<com.packagename.projectName.RecyclerAdapters.RecyclerAdapterPhotos.PhotosVH> {

@AndroidEntryPoint base class must extend ComponentActivity, (support) Fragment, View, Service, or BroadcastReceiver.

Head My adapter.

@AndroidEntryPoint
class RecyclerAdapterPhotos(var context:Context, private val photoList:List\<PhotosModelItem\>):RecyclerView.Adapter\<RecyclerAdapterPhotos.PhotosVH\>() {

@Inject
lateinit var imageLoader:ImageLoaderHiltClass

...

override fun onBindViewHolder(holder: PhotosVH, position: Int) {
    imageLoader.imageLoader(photoList[position].thumbnailUrl,holder.photosThumbnailVH)
...

Module of Picasso

@Module
@InstallIn(SingletonComponent::class)
object ImageLoaderModule {
    @Provides
    fun ProvidesImageLoader(photoUri:String,photoVH:ImageView):Picasso{
        return Picasso.get()

    }

I try to use Hilt  for Picasso frame in my recyclerView adapter