问:
How to get the object key and value from another javascript files
i am using $ npm run index.js

in index.js file i am looping and get list of below files, from the file we need to read the "testData", could you please help to get the data

```<code>var listOfFiles = ['test/fileOne.js',
,test/example.js,]
</code>```

each file having

```<code>/test/fileOne.js

var testData = {
    tags: 'tag1 tag2 tag3',
    setup: 'one_tier'
}
</code>```

```<code>/test/example.js

var testData = {
    tags: 'tag3',
    setup: 'two_tier'
}
</code>```

My Code: index.js

```<code>let fs = require("fs")
const glob = require("glob");

var getDirectories = function (src, callback) {
    glob(src + '/**/*.js', callback);
};
getDirectories('tests', function (err, res) {
if (err) {
    console.log('Error', err);
}
else {
    var listOfFiles = res;
    for (let val of listOfFiles){
       ///// HERE we have to get the Tags and setup from each js file////
    }
}

</code>```

答:
You can read the content of the file as string using fs.readFileSync:

```<code>for (const val of listOfFiles) {
    ///// HERE we have to get the Tags and setup from each js file////
    const content = fs.readFileSync(val, 'utf8');
    console.log(content);
    const tags = content.match(/tags: '(.*?)'/)[1];
    console.log(tags);
    const setup = content.match(/setup: '(.*?)'/)[1];
    console.log(setup);
}
</code>```

Body:
i am using $ npm run index.js

in index.js file i am looping and get list of below files, from the file we need to read the "testData", could you please help to get the data

var listOfFiles = ['test/fileOne.js',
,test/example.js,]

each file having

/test/fileOne.js

var testData = {
    tags: 'tag1 tag2 tag3',
    setup: 'one_tier'
}

/test/example.js

var testData = {
    tags: 'tag3',
    setup: 'two_tier'
}

My Code: index.js

let fs = require("fs")
const glob = require("glob");

var getDirectories = function (src, callback) {
    glob(src + '/**/*.js', callback);
};
getDirectories('tests', function (err, res) {
if (err) {
    console.log('Error', err);
}
else {
    var listOfFiles = res;
    for (let val of listOfFiles){
       ///// HERE we have to get the Tags and setup from each js file////
    }
}

Body:
You can read the content of the file as string using fs.readFileSync:

for (const val of listOfFiles) {
    ///// HERE we have to get the Tags and setup from each js file////
    const content = fs.readFileSync(val, 'utf8');
    console.log(content);
    const tags = content.match(/tags: '(.*?)'/)[1];
    console.log(tags);
    const setup = content.match(/setup: '(.*?)'/)[1];
    console.log(setup);
}


来源: stackexchange

问:
R pivot_longer combining several columns
I have a dataframe where several columns have similar information that I'd like to collapse into fewer columns. This seemed a little different from the normal uses of pivot_long or gather and I am stuck. My first thought was to make 3 separate sets and row-bind.. but I think someone here will have a more elegant solution!

df<-data.frame("PicID"=letters[1:8],
"Near_Species1" = c("bird","bird", "bird", "dog", "dog", "human", "none", "human"),
"Count1" = c(1,1,1,1,2,1,0,1),
"Near_Species2" = c(NA,"human", NA, NA, "human", NA, NA, NA),
"Count2" = c(NA,1, NA, NA, 1, NA, NA, NA),
"Far_Species"=c(NA, NA, NA,NA, NA, NA, NA, "bird"))
```

<p>I'd like to pivot this longer with the basic structure of </p>

```PicID   NearorFar   Species   Count
```

<p>I'd like to have at least 1 row per picture based on Near_Species1, regardless of what is there (none, NA, etc). </p>

<p>And if there are any species other than "none" in Near_Species2, Count2 OR Far_Species, I'd like another row. Essentially a "none" for species is an NA. But I'd like at least 1 row to keep track of that ID. </p>

<p>output would look like this, but remove rows where species is an NA. </p>

<pre class="lang-r prettyprint-override"><code>df_out <- data.frame(
  "PicID" = c("a", "b", "c", "d", "e", "f", "g", "h",
          "a", "b", "c", "d", "e", "f", "g", "h",
          "a", "b", "c", "d", "e", "f", "g", "h"),
"NearorFar"=rep(c("Near", "Far"),times=c(16, 8)),
"Species"= paste(c("bird","bird", "bird", "dog", "dog", "human", "none", "human",
                NA,"human", NA, NA, "human", NA, NA, NA,
                NA, NA, NA,NA, NA, NA, NA, "bird")),
"Count"= c(1,1,1,1,2,1,0,1,
          NA,1, NA, NA, 1, NA, NA, NA,
          rep(NA, 8))
)

</code>```

答:
We can use pivot_longer

```<code>library(dplyr)
library(tidyr)
library(stringr)
df %>%
  pivot_longer(cols = matches('Species'), names_to = 'NearorFar',
         values_to = 'Species') %>%
  mutate(NearorFar = str_remove(NearorFar, "_.*")) %>%
  pivot_longer(cols = starts_with('Count'), names_to = NULL,
          values_to = 'Count', values_drop_na = TRUE) %>%
  distinct
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe where several columns have similar information that I'd like to collapse into fewer columns. This seemed a little different from the normal uses of pivot_long or gather and I am stuck. My first thought was to make 3 separate sets and row-bind.. but I think someone here will have a more elegant solution!

df<-data.frame("PicID"=letters[1:8],
"Near_Species1" = c("bird","bird", "bird", "dog", "dog", "human", "none", "human"),
"Count1" = c(1,1,1,1,2,1,0,1),
"Near_Species2" = c(NA,"human", NA, NA, "human", NA, NA, NA),
"Count2" = c(NA,1, NA, NA, 1, NA, NA, NA),
"Far_Species"=c(NA, NA, NA,NA, NA, NA, NA, "bird"))

I'd like to pivot this longer with the basic structure of

PicID   NearorFar   Species   Count

I'd like to have at least 1 row per picture based on Near_Species1, regardless of what is there (none, NA, etc).

And if there are any species other than "none" in Near_Species2, Count2 OR Far_Species, I'd like another row. Essentially a "none" for species is an NA. But I'd like at least 1 row to keep track of that ID.

output would look like this, but remove rows where species is an NA.

df_out <- data.frame(
  "PicID" = c("a", "b", "c", "d", "e", "f", "g", "h",
          "a", "b", "c", "d", "e", "f", "g", "h",
          "a", "b", "c", "d", "e", "f", "g", "h"),
"NearorFar"=rep(c("Near", "Far"),times=c(16, 8)),
"Species"= paste(c("bird","bird", "bird", "dog", "dog", "human", "none", "human",
                NA,"human", NA, NA, "human", NA, NA, NA,
                NA, NA, NA,NA, NA, NA, NA, "bird")),
"Count"= c(1,1,1,1,2,1,0,1,
          NA,1, NA, NA, 1, NA, NA, NA,
          rep(NA, 8))
)

Body:
We can use pivot_longer

library(dplyr)
library(tidyr)
library(stringr)
df %>%
  pivot_longer(cols = matches('Species'), names_to = 'NearorFar',
         values_to = 'Species') %>%
  mutate(NearorFar = str_remove(NearorFar, "_.*")) %>%
  pivot_longer(cols = starts_with('Count'), names_to = NULL,
          values_to = 'Count', values_drop_na = TRUE) %>%
  distinct


问:
Passing authorization code to Python Notebook
As I am trying to connect to Google's BigQuery environment from a Python notebook using the google.cloud library, the response from the server is to visit a link that generates a code and to "Enter the authorization code:" . However, as this response is just text, I do not know how to pass the code back to the server response. I am running this notebook in a Databricks environment.

Does anyone know how I can push this code back to the server and complete the authorization?

答: It doesnn't look like you are using the correct . The flow which you mentioned will work on a UI not not with any automation . I suggest you to share more dtails here and also check for more documenataion on the same .</p>


问:
Doxygen strange problem while documenting PHP if
I face a strange problem while I'm trying to document a project of mine. I have the following code:

```<code>//! Set default ::$action for called controller. If no action is called, default (index) will be set.
$action = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

if ($action) {
    echo 'something 1';
}else{
    echo 'something 2';
}

//! Set default ::$action2 for called controller. If no action is called, default (index) will be set.
$action2 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

//! Set default ::$action3 for called controller. If no action is called, default (index) will be set.
$action3 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';
</code>```

Doxygen generates the following:

As you may see, $action2 is missing. I check one of my other files and saw same problem. Next thing after if statement is never documented, but the one after that is documented. If I remove the if statement from above example, I get documentation for all 4 variables - $page, $action, action2 and action3.

I spend enormous time of trying to understand what exactly is wrong, but no luck, so every suggestion is welcomed.

System is:
Windows XP x64 with Doxygen 1.7.4. (I'm using the Doxygen GUI)

UPDATE
Also, when I have something like that in my code (notice the missing else for the if statement). When I add the }else{} however it works. Next $variables is not documented again, but that update was about the if/else.

Doxygen converts it to this

答:
I believe it's a bug in doxygen when parsing php.  There was a similar issue from 2008 that was worked on but never resolved - https://bugzilla.gnome.org/show_bug.cgi?id=528815

I'm willing to bet that your issue is related.

I have a couple of suggestions:

1) I may have stumbled onto a workaround.  Adding a semicolon after the block seems to make it behave correctly.

```<code>if ($action) {
  echo 'something 1';
}else{
  echo 'something 2';
};
</code>```

However, I don't know if this will cause other issues with doxygen's parsing.

2) I use doxygen for my c++ projects, but I use phpdoc for my php projects because I have had better results with it.  You might consider doing the same if you're not tied to doxygen for political or practical reasons.

ContentLicense: CC BY-SA 3.0

Body:
I face a strange problem while I'm trying to document a project of mine. I have the following code:

//! Set default ::$action for called controller. If no action is called, default (index) will be set.
$action = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

if ($action) {
    echo 'something 1';
}else{
    echo 'something 2';
}

//! Set default ::$action2 for called controller. If no action is called, default (index) will be set.
$action2 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

//! Set default ::$action3 for called controller. If no action is called, default (index) will be set.
$action3 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

Doxygen generates the following:

As you may see, $action2 is missing. I check one of my other files and saw same problem. Next thing after if statement is never documented, but the one after that is documented. If I remove the if statement from above example, I get documentation for all 4 variables - $page, $action, action2 and action3.

I spend enormous time of trying to understand what exactly is wrong, but no luck, so every suggestion is welcomed.

System is:
Windows XP x64 with Doxygen 1.7.4. (I'm using the Doxygen GUI)

UPDATE
Also, when I have something like that in my code (notice the missing else for the if statement). When I add the }else{} however it works. Next $variables is not documented again, but that update was about the if/else.

Doxygen converts it to this

Body:
I believe it's a bug in doxygen when parsing php.  There was a similar issue from 2008 that was worked on but never resolved - https://bugzilla.gnome.org/show_bug.cgi?id=528815

I'm willing to bet that your issue is related.

I have a couple of suggestions:

1) I may have stumbled onto a workaround.  Adding a semicolon after the block seems to make it behave correctly.

if ($action) {
  echo 'something 1';
}else{
  echo 'something 2';
};

However, I don't know if this will cause other issues with doxygen's parsing.

2) I use doxygen for my c++ projects, but I use phpdoc for my php projects because I have had better results with it.  You might consider doing the same if you're not tied to doxygen for political or practical reasons.


问:
Cloudformation API GW IntegrationResponse/response headers
It is possible to use !Ref to a S3 bucket to use within a ResponseParameter.  For example:

```<code>IntegrationResponses:
      - ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
          method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
          method.response.header.Access-Control-Allow-Origin: "'https://dynamicbucketname.s3-us-west-2.amazonaws.com'"
          method.response.header.Access-Control-Allow-Credentials: "'true'"

S3Bucket:
 Type: AWS::S3::Bucket
 Properties:
   PublicAccessBlockConfiguration:
     BlockPublicAcls: true
     IgnorePublicAcls: false
     BlockPublicPolicy: true
     RestrictPublicBuckets: true
   WebsiteConfiguration:
     IndexDocument: index.html
     ErrorDocument: error.html
</code>```

So essentially I'm using a resource AWS::S3::Bucket which allows the template to create the bucket.  Hence the name will be dynamic.  I want to be able to !Ref S3Bucket within the Origin.  Is that even possible?  I know it can be static like "'https://www.example.com'"

答:
One way would be to this as follows using Sub function:

It is possible to use !Ref to a S3 bucket to use within a ResponseParameter. For example:

```<code>IntegrationResponses:
      - ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
          method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
          method.response.header.Access-Control-Allow-Origin: !Sub "'https://${S3Bucket.DomainName}'"
          method.response.header.Access-Control-Allow-Credentials: "'true'"
</code>```

Other Bucket return values than DomainName are listed here:

Body:
It is possible to use !Ref to a S3 bucket to use within a ResponseParameter.  For example:

IntegrationResponses:
      - ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
          method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
          method.response.header.Access-Control-Allow-Origin: "'https://dynamicbucketname.s3-us-west-2.amazonaws.com'"
          method.response.header.Access-Control-Allow-Credentials: "'true'"

S3Bucket:
 Type: AWS::S3::Bucket
 Properties:
   PublicAccessBlockConfiguration:
     BlockPublicAcls: true
     IgnorePublicAcls: false
     BlockPublicPolicy: true
     RestrictPublicBuckets: true
   WebsiteConfiguration:
     IndexDocument: index.html
     ErrorDocument: error.html

So essentially I'm using a resource AWS::S3::Bucket which allows the template to create the bucket.  Hence the name will be dynamic.  I want to be able to !Ref S3Bucket within the Origin.  Is that even possible?  I know it can be static like "'https://www.example.com'"

Body:
One way would be to this as follows using Sub function:

It is possible to use !Ref to a S3 bucket to use within a ResponseParameter. For example:

IntegrationResponses:
      - ResponseParameters:
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
          method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
          method.response.header.Access-Control-Allow-Origin: !Sub "'https://${S3Bucket.DomainName}'"
          method.response.header.Access-Control-Allow-Credentials: "'true'"

Other Bucket return values than DomainName are listed here:


问:
Spring Boot with Embedded Derby Server not working when I exported to Jar
Spring Boot with Embedded Derby Server not working when I exported to Jar. But when I run the app within eclipse it works. It just when I export it to jar when it does not work.

Here is my POM

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE

    com.webupps.spring
    app
    0.0.1-SNAPSHOT
    app
    Boilerplate

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    <querydsl.version>4.2.1</querydsl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- JSON Web Token Support -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>
    <!-- End JSON Web Token Support -->
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
   <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
    </dependency>
    <!-- io.springfox setup  -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
            <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>

            <dependencies>
                <dependency>
                    <groupId>com.querydsl</groupId>
                    <artifactId>querydsl-apt</artifactId>
                    <version>4.1.2</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
</code>```

Here is my error
A child container failed during start

```<code>java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@228605e1]
        at java.util.concurrent.FutureTask.report(FutureTask.java:122) [na:1.8.0_241]
        at java.util.concurrent.FutureTask.get(FutureTask.java:192) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_241]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.startup.Tomcat.start(Tomcat.java:468) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:437) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:176) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:158) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) [jar:rsrc:spring-context-5.2.6.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at com.webupps.spring.app.AppApplication.main(AppApplication.java:14) [rsrc:./:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) [springbootswagger.jar:na]
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@228605e1]
        at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4800) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4936) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_241]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        ... 35 common frames omitted
Caused by: java.lang.Error: factory already defined
        at java.net.URL.setURLStreamHandlerFactory(URL.java:1134) ~[na:1.8.0_241]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.<init>(TomcatURLStreamHandlerFactory.java:130) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.getInstanceInternal(TomcatURLStreamHandlerFactory.java:53) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register(TomcatURLStreamHandlerFactory.java:77) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.StandardRoot.registerURLStreamHandlerFactory(StandardRoot.java:700) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.StandardRoot.initInternal(StandardRoot.java:682) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        ... 45 common frames omitted
</code>```

答: Nevermind. Just a noob error. Here's the fix.

Body:
Spring Boot with Embedded Derby Server not working when I exported to Jar. But when I run the app within eclipse it works. It just when I export it to jar when it does not work.

Here is my POM

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE

    com.webupps.spring
    app
    0.0.1-SNAPSHOT
    app
    Boilerplate

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    <querydsl.version>4.2.1</querydsl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
   <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
            <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>apt-maven-plugin</artifactId>
            <version>1.1.3</version>

            <dependencies>
                <dependency>
                    <groupId>com.querydsl</groupId>
                    <artifactId>querydsl-apt</artifactId>
                    <version>4.1.2</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Here is my error
A child container failed during start

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@228605e1]
        at java.util.concurrent.FutureTask.report(FutureTask.java:122) [na:1.8.0_241]
        at java.util.concurrent.FutureTask.get(FutureTask.java:192) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_241]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.startup.Tomcat.start(Tomcat.java:468) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:123) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:437) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:176) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:158) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) [jar:rsrc:spring-context-5.2.6.RELEASE.jar!/:na]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [jar:rsrc:spring-boot-2.3.0.RELEASE.jar!/:na]
        at com.webupps.spring.app.AppApplication.main(AppApplication.java:14) [rsrc:./:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_241]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_241]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_241]
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58) [springbootswagger.jar:na]
Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.StandardRoot@228605e1]
        at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4800) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4936) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_241]
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_241]
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        ... 35 common frames omitted
Caused by: java.lang.Error: factory already defined
        at java.net.URL.setURLStreamHandlerFactory(URL.java:1134) ~[na:1.8.0_241]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.<init>(TomcatURLStreamHandlerFactory.java:130) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.getInstanceInternal(TomcatURLStreamHandlerFactory.java:53) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register(TomcatURLStreamHandlerFactory.java:77) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.StandardRoot.registerURLStreamHandlerFactory(StandardRoot.java:700) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.webresources.StandardRoot.initInternal(StandardRoot.java:682) ~[jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) [jar:rsrc:tomcat-embed-core-9.0.35.jar!/:na]
        ... 45 common frames omitted


问:
Z-index not working to keep an image on top... Toggle on/off image, menu gets hidden
So I am using the input checkbox to toggle on/off the mascot logo on top of the main container div's background. The logo has to start in the top 0 left 0 just like the background but when I toggle it on to show the mascot logo the menu with the check boxes is hidden.

My z-index won't work and I am looking for any solutions to keep the menu group of checkboxes on top of all.

Thanks

body, html {
  height: 100%;
}

#map {
  background-image: url(https://image.freepik.com/free-vector/vector-illustration-mountain-landscape_1441-71.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

input:checked + .hidable {
    display: none;
    position: absolute;
    z-index: 10;
}

input:not(:checked) + .showable {
    display: none;
    position: absolute;
    z-index: 10;
  }

  #mascot1 {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Splash Page</title>
</head>
<body>

  <div id="map">
    <div id="menu">
      <input type="checkbox" /> Mascot 1
      <div class="showable"><img id="mascot1" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 2
      <div class="showable"><img id="mascot2" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 3
      <div class="showable"><img id="mascot3" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
    </div>
  </div>

</body>
</html></code>```

答:
add a negative z-index to all the image and z-index:0 to the main wrapper. You can then remove all the other z-index

body,
html {
  height: 100%;
}

#map {
  background-image: url(https://image.freepik.com/free-vector/vector-illustration-mountain-landscape_1441-71.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  z-index: 0
}

#menu {
  display: grid;
  grid-template-columns:auto 1fr;
}

input:checked+.hidable,
input:not(:checked)+.showable {
  display: none;
}

.showable {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="map">
    <div id="menu">
      <input type="checkbox" /> Mascot 1 long text here
      <div class="showable"><img id="mascot1" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 2
      <div class="showable"><img id="mascot2" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 3
      <div class="showable"><img id="mascot3" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
    </div>
  </div></code>```

Related for mroe details: Why can't an element with a z-index value cover its child?

Body:
So I am using the input checkbox to toggle on/off the mascot logo on top of the main container div's background. The logo has to start in the top 0 left 0 just like the background but when I toggle it on to show the mascot logo the menu with the check boxes is hidden.

My z-index won't work and I am looking for any solutions to keep the menu group of checkboxes on top of all.

Thanks

body, html {
  height: 100%;
}

#map {
  background-image: url(https://image.freepik.com/free-vector/vector-illustration-mountain-landscape_1441-71.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  }

  #menu {
    display: block;
    width: 100px;
  }

input:checked + .hidable {
    display: none;
    position: absolute;
    z-index: 10;
}

input:not(:checked) + .showable {
    display: none;
    position: absolute;
    z-index: 10;
  }

  #mascot1 {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
  }

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<title>Splash Page</title>

      <input type="checkbox" /> Mascot 1

      <input type="checkbox" /> Mascot 2

      <input type="checkbox" /> Mascot 3

Body:
add a negative z-index to all the image and z-index:0 to the main wrapper. You can then remove all the other z-index

body,
html {
  height: 100%;
}

#map {
  background-image: url(https://image.freepik.com/free-vector/vector-illustration-mountain-landscape_1441-71.jpg);
  height: 1080px;
  width: 1080px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
  z-index: 0
}

#menu {
  display: grid;
  grid-template-columns:auto 1fr;
}

input:checked+.hidable,
input:not(:checked)+.showable {
  display: none;
}

.showable {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: -1;
}

<div id="map">
    <div id="menu">
      <input type="checkbox" /> Mascot 1 long text here
      <div class="showable"><img id="mascot1" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 2
      <div class="showable"><img id="mascot2" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
      <input type="checkbox" /> Mascot 3
      <div class="showable"><img id="mascot3" src="https://banner2.cleanpng.com/20180510/fkq/kisspng-tiger-mascot-5af4168e2aa482.2537194215259459981747.jpg" alt="Map Locations"></div>
    </div>
  </div>

Related for mroe details: Why can't an element with a z-index value cover its child?


问:
How do I generate a uniqueidentifier for a set of records with a distinct key?
I have a record set that looks like this:

| key_sk | unique_id                            |
|--------|--------------------------------------|
| 2      | null                                 |
| 2      | null                                 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 4      | 4ce66783-0b84-4e8a-a0de-c3284e4d9cd0 |
| 5      | null                                 |
```

<p>I would like to generate a unique id for each unique <code>key_sk</code> set where the <code>unique_id</code> is null. For the above I'd like <code>key_sk 2</code> to have a a single <code>unique_id</code> like <code>key_sk 3</code> does.</p>

<p>My attempt below generated a different <code>uniqueidentifier</code> for each set. I think this is because of the recursive nature of common table expressions: each join to the CTE causes <code>NEWID()</code> to be called.</p>

<pre class="lang-sql prettyprint-override"><code>;with update_id_cte as
(
  select distinct hr.key_sk
        ,NEWID() as gened_unique_id
    from history_record hr
   where hr.unique_id is null
)
update hr
   set hr.unique_id = cte.gened_unique_id
  from history_record hr
       join update_id_cte cte
         on hr.key_sk = cte.key_sk
</code>```

There's probably a simpler way than utilizing a CTE to do this. How can I generate and update the history_record table with a single uniqueidentifier for each distinct key_sk?

答:
I think that it should work as you expect if you first select distinct key_sk in a subquery, then assign a new id. This way, the newid() is invoked only once per distinct target key_sk:

```<code>with update_id_cte as (
    select key_sk, newid() as gened_unique_id
    from (select distinct key_sk from history_record where unique_id is null) t
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr
inner join update_id_cte cte on hr.key_sk = cte.key_sk
</code>```

Body:
I have a record set that looks like this:

| key_sk | unique_id                            |
|--------|--------------------------------------|
| 2      | null                                 |
| 2      | null                                 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 4      | 4ce66783-0b84-4e8a-a0de-c3284e4d9cd0 |
| 5      | null                                 |

I would like to generate a unique id for each unique key_sk set where the unique_id is null. For the above I'd like key_sk 2 to have a a single unique_id like key_sk 3 does.

My attempt below generated a different uniqueidentifier for each set. I think this is because of the recursive nature of common table expressions: each join to the CTE causes NEWID() to be called.

;with update_id_cte as
(
  select distinct hr.key_sk
        ,NEWID() as gened_unique_id
    from history_record hr
   where hr.unique_id is null
)
update hr
   set hr.unique_id = cte.gened_unique_id
  from history_record hr
       join update_id_cte cte
         on hr.key_sk = cte.key_sk

There's probably a simpler way than utilizing a CTE to do this. How can I generate and update the history_record table with a single uniqueidentifier for each distinct key_sk?

Body:
I think that it should work as you expect if you first select distinct key_sk in a subquery, then assign a new id. This way, the newid() is invoked only once per distinct target key_sk:

with update_id_cte as (
    select key_sk, newid() as gened_unique_id
    from (select distinct key_sk from history_record where unique_id is null) t
)
update hr
set hr.unique_id = cte.gened_unique_id
from history_record hr
inner join update_id_cte cte on hr.key_sk = cte.key_sk


问:
Replacing service layer with MediatR - is it worth to do it?
Do you think it might be reasonable to replace my service layer or service classes with MediatR? For example, my service classes look like this:

```<code>public interface IEntityService<TEntityDto> where TEntityDto : class, IDto
{
    Task<TEntityDto> CreateAsync(TEntityDto entityDto);
    Task<bool> DeleteAsync(int id);
    Task<IEnumerable<TEntityDto>> GetAllAsync(SieveModel sieveModel);
    Task<TEntityDto> GetByIdAsync(int id);
    Task<TEntityDto> UpdateAsync(int id, TEntityDto entityDto);
}
</code>```

I want to achieve some sort of modular design so other dynamically loaded modules
 or plugins can write their own notification or command handlers for my main core application.

Currently, my application is not event-driven at all and there's no easy way for my dynamically loaded plugins to communicate.

I can either incorporate MediatR in my controllers removing service layer completely or use it with my service layer just publishing notifications so my plugins can handle them.

Currently, my logic is mostly CRUD but there's a lot of custom logic going on before creating, updating, deleting.

Possible replacement of my service would look like:

```<code>public class CommandHandler : IRequestHandler<CreateCommand, Response>, IRequestHandler<UpdateCommand, Response>, IRequestHandler<DeleteCommand, bool>
{
    private readonly DbContext _dbContext;

    public CommandHandler(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public Task<Response> Handle(CreateCommand request, CancellationToken cancellationToken)
    {
        //...
    }

    public Task<Response> Handle(UpdateCommand request, CancellationToken cancellationToken)
    {
        //...
    }

    public Task<bool> Handle(DeleteCommand request, CancellationToken cancellationToken)
    {
        ///...
    }
}
</code>```

Would it be something wrong to do?

Basically, I'm struggling what to choose for my logic flow:

Controller -> Service -> MediatR -> Notification handlers -> Repository

Controller -> MediatR -> Command handlers -> Repository

It seems like with MediatR I can't have a single model for Create, Update and Delete, so one way to re-use it I'd need to derive requests like:

```<code>public CreateRequest : MyDto, IRequest<MyDto> {}
public UpdateRequest : MyDto, IRequest<MyDto> {}
</code>```

or embed it in my command like:

```<code>public CreateRequest : IRequest<MyDto>
{
    MyDto MyDto { get; set; }
}
</code>```

One advantage of MediatR is the ability to plug logic in and plug it out easily which seems like a nice fit for modular architecture but still, I'm a bit confused how to shape my architecture with it.

答:
Update: I'm preserving the answer, but my position on this has changed somewhat as indicated in this blog post.

If you have a class, let's say an API controller, and it depends on

IRequestHandler<CreateCommand, Response>

What is the benefit of changing your class so that it depends on IMediator,

and instead of calling

```<code>return requestHandler.HandleRequest(request);
</code>```

it calls

```<code>return mediator.Send(request);
</code>```

The result is that instead of injecting the dependency we need, we inject a service locator which in turn resolves the dependency we need.

Quoting Mark Seeman's article,

In short, the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

It's not exactly the same as

```<code>var commandHandler = serviceLocator.Resolve<IRequestHandler<CreateCommand, Response>>();
return commandHandler.Handle(request);
</code>```

because the mediator is limited to resolving command and query handlers, but it's close. It's still a single interface that provides access to lots of other ones.

It makes code harder to navigate

After we introduce IMediator, our class still indirectly depends on IRequestHandler<CreateCommand, Response>. The difference is that now we can't tell by looking at it. We can't navigate from the interface to its implementations. We might reason that we can still follow the dependencies if we know what to look for - that is, if we know the conventions of command handler interface names. But that's not nearly as helpful as a class actually declaring what it depends on.

Sure, we get the benefit of having interfaces wired up to concrete implementations without writing the code, but the savings are trivial and we'll likely lose whatever time we save because of the added (if minor) difficulty of navigating the code. And there are libraries which will register those dependencies for us anyway while still allowing us to inject abstraction we actually depend on.

It's a weird, skewed way of depending on abstractions

It's been suggested that using a mediator assists with implementing the decorator pattern. But again, we already gain that ability by depending on an abstraction. We can use one implementation of an interface or another that adds a decorator. The point of depending on abstractions is that we can change such implementation details without changing the abstraction.

To elaborate: The point of depending on ISomethingSpecific is that we can change or replace the implementation without modifying the classes that depend on it. But if we say, "I want to change the implementation of ISomethingSpecific (by adding a decorator), so to accomplish that I'm going to change the classes that depend on ISomethingSpecific, which were working just fine, and make them depend on some generic, all-purpose interface", then something has gone wrong. There are numerous other ways to add decorators without modifying parts of our code that don't need to change.

Yes, using IMediator promotes loose coupling. But we already accomplished that by using well-defined abstractions. Adding layer upon layer of indirection doesn't multiply that benefit. If you've got enough abstraction that it's easy to write unit tests, you've got enough.

Vague dependencies make it easier to violate the Single Responsibility Principle

Suppose you have a class for placing orders, and it depends on ICommandHandler<PlaceOrderCommand>. What happens if someone tries to sneak in something that doesn't belong there, like a command to update user data? They'll have to add a new dependency, ICommandHandler<ChangeUserAddressCommand>. What happens if they want to keep piling more stuff into that class, violating the SRP? They'll have to keep adding more dependencies. That doesn't prevent them from doing it, but at least it shines a light on what's happening.

On the other hand, what if you can add all sorts of random stuff into a class without adding more dependencies? The class depends on an abstraction that can do anything. It can place orders, update addresses, request sales history, whatever, and all without adding a single new dependency. That's the same problem you get if you inject an IoC container into a class where it doesn't belong. It's a single class or interface that can be used to request all sorts of dependencies. It's a service locator.

IMediator doesn't cause SRP violations, and its absence won't prevent them. But explicit, specific dependencies guide us away from such violations.

The Mediator Pattern

Curiously, using MediatR doesn't usually have anything to do with the mediator
pattern. The mediator pattern promotes loose coupling by having objects interact with a mediator rather than directly with each other. If we're already depending on an abstraction like an ICommandHandler then the tight coupling that the mediator pattern prevents doesn't exist in the first place.

The mediator pattern also encapsulates complex operations so that they appear simpler from the outside.

```<code>return mediator.Send(request);
</code>```

is not simpler than

```<code>return requestHandler.HandleRequest(request);
</code>```

The complexity of the two interactions is identical. Nothing is "mediated." Imagine that you're about to swipe your credit card at the grocery store, and then someone offers to simplify your complex interaction by leading you to another register where you do exactly the same thing.

What about CQRS?

A mediator is neutral when it comes to CQRS (unless we have two separate mediators, like ICommandMediator and IQueryMediator.) It seems counterproductive to separate our command handlers from our query handlers and then inject a single interface which in effect brings them back together and exposes all of our commands and queries in one place. At the very least it's hard to say that it helps us to keep them separate.

IMediator is used to invoke command and query handlers, but it has nothing to do with the extent to which they are segregated. If they were segregated before we added a mediator, they still are. If our query handler does something it shouldn't, the mediator will still happily invoke it.

I hope it doesn't sound like a mediator ran over my dog. But it's certainly not a silver bullet that sprinkles CQRS on our code or even necessarily improves our architecture.

We should ask, what are the benefits? What undesirable consequences could it have? Do I need that tool, or can I obtain the benefits I want without those consequences?

What I am asserting is that once we're already depending on abstractions, further steps to "hide" a class's dependencies usually add no value. They make it harder to read and understand, and erode our ability to detect and prevent other code smells.

Body:
Do you think it might be reasonable to replace my service layer or service classes with MediatR? For example, my service classes look like this:

public interface IEntityService<TEntityDto> where TEntityDto : class, IDto
{
    Task<TEntityDto> CreateAsync(TEntityDto entityDto);
    Task<bool> DeleteAsync(int id);
    Task<IEnumerable<TEntityDto>> GetAllAsync(SieveModel sieveModel);
    Task<TEntityDto> GetByIdAsync(int id);
    Task<TEntityDto> UpdateAsync(int id, TEntityDto entityDto);
}

I want to achieve some sort of modular design so other dynamically loaded modules
 or plugins can write their own notification or command handlers for my main core application.

Currently, my application is not event-driven at all and there's no easy way for my dynamically loaded plugins to communicate.

I can either incorporate MediatR in my controllers removing service layer completely or use it with my service layer just publishing notifications so my plugins can handle them.

Currently, my logic is mostly CRUD but there's a lot of custom logic going on before creating, updating, deleting.

Possible replacement of my service would look like:

public class CommandHandler : IRequestHandler<CreateCommand, Response>, IRequestHandler<UpdateCommand, Response>, IRequestHandler<DeleteCommand, bool>
{
    private readonly DbContext _dbContext;

    public CommandHandler(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public Task<Response> Handle(CreateCommand request, CancellationToken cancellationToken)
    {
        //...
    }

    public Task<Response> Handle(UpdateCommand request, CancellationToken cancellationToken)
    {
        //...
    }

    public Task<bool> Handle(DeleteCommand request, CancellationToken cancellationToken)
    {
        ///...
    }
}

Would it be something wrong to do?

Basically, I'm struggling what to choose for my logic flow:

Controller -> Service -> MediatR -> Notification handlers -> Repository

Controller -> MediatR -> Command handlers -> Repository

It seems like with MediatR I can't have a single model for Create, Update and Delete, so one way to re-use it I'd need to derive requests like:

public CreateRequest : MyDto, IRequest<MyDto> {}
public UpdateRequest : MyDto, IRequest<MyDto> {}

or embed it in my command like:

public CreateRequest : IRequest<MyDto>
{
    MyDto MyDto { get; set; }
}

One advantage of MediatR is the ability to plug logic in and plug it out easily which seems like a nice fit for modular architecture but still, I'm a bit confused how to shape my architecture with it.

Body:
Update: I'm preserving the answer, but my position on this has changed somewhat as indicated in this blog post.

If you have a class, let's say an API controller, and it depends on

IRequestHandler<CreateCommand, Response>

What is the benefit of changing your class so that it depends on IMediator,

and instead of calling

return requestHandler.HandleRequest(request);

it calls

return mediator.Send(request);

The result is that instead of injecting the dependency we need, we inject a service locator which in turn resolves the dependency we need.

Quoting Mark Seeman's article,

In short, the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

It's not exactly the same as

var commandHandler = serviceLocator.Resolve<IRequestHandler<CreateCommand, Response>>();
return commandHandler.Handle(request);

because the mediator is limited to resolving command and query handlers, but it's close. It's still a single interface that provides access to lots of other ones.

It makes code harder to navigate

After we introduce IMediator, our class still indirectly depends on IRequestHandler<CreateCommand, Response>. The difference is that now we can't tell by looking at it. We can't navigate from the interface to its implementations. We might reason that we can still follow the dependencies if we know what to look for - that is, if we know the conventions of command handler interface names. But that's not nearly as helpful as a class actually declaring what it depends on.

Sure, we get the benefit of having interfaces wired up to concrete implementations without writing the code, but the savings are trivial and we'll likely lose whatever time we save because of the added (if minor) difficulty of navigating the code. And there are libraries which will register those dependencies for us anyway while still allowing us to inject abstraction we actually depend on.

It's a weird, skewed way of depending on abstractions

It's been suggested that using a mediator assists with implementing the decorator pattern. But again, we already gain that ability by depending on an abstraction. We can use one implementation of an interface or another that adds a decorator. The point of depending on abstractions is that we can change such implementation details without changing the abstraction.

To elaborate: The point of depending on ISomethingSpecific is that we can change or replace the implementation without modifying the classes that depend on it. But if we say, "I want to change the implementation of ISomethingSpecific (by adding a decorator), so to accomplish that I'm going to change the classes that depend on ISomethingSpecific, which were working just fine, and make them depend on some generic, all-purpose interface", then something has gone wrong. There are numerous other ways to add decorators without modifying parts of our code that don't need to change.

Yes, using IMediator promotes loose coupling. But we already accomplished that by using well-defined abstractions. Adding layer upon layer of indirection doesn't multiply that benefit. If you've got enough abstraction that it's easy to write unit tests, you've got enough.

Vague dependencies make it easier to violate the Single Responsibility Principle

Suppose you have a class for placing orders, and it depends on ICommandHandler<PlaceOrderCommand>. What happens if someone tries to sneak in something that doesn't belong there, like a command to update user data? They'll have to add a new dependency, ICommandHandler<ChangeUserAddressCommand>. What happens if they want to keep piling more stuff into that class, violating the SRP? They'll have to keep adding more dependencies. That doesn't prevent them from doing it, but at least it shines a light on what's happening.

On the other hand, what if you can add all sorts of random stuff into a class without adding more dependencies? The class depends on an abstraction that can do anything. It can place orders, update addresses, request sales history, whatever, and all without adding a single new dependency. That's the same problem you get if you inject an IoC container into a class where it doesn't belong. It's a single class or interface that can be used to request all sorts of dependencies. It's a service locator.

IMediator doesn't cause SRP violations, and its absence won't prevent them. But explicit, specific dependencies guide us away from such violations.

The Mediator Pattern

Curiously, using MediatR doesn't usually have anything to do with the mediator
pattern. The mediator pattern promotes loose coupling by having objects interact with a mediator rather than directly with each other. If we're already depending on an abstraction like an ICommandHandler then the tight coupling that the mediator pattern prevents doesn't exist in the first place.

The mediator pattern also encapsulates complex operations so that they appear simpler from the outside.

return mediator.Send(request);

is not simpler than

return requestHandler.HandleRequest(request);

The complexity of the two interactions is identical. Nothing is "mediated." Imagine that you're about to swipe your credit card at the grocery store, and then someone offers to simplify your complex interaction by leading you to another register where you do exactly the same thing.

What about CQRS?

A mediator is neutral when it comes to CQRS (unless we have two separate mediators, like ICommandMediator and IQueryMediator.) It seems counterproductive to separate our command handlers from our query handlers and then inject a single interface which in effect brings them back together and exposes all of our commands and queries in one place. At the very least it's hard to say that it helps us to keep them separate.

IMediator is used to invoke command and query handlers, but it has nothing to do with the extent to which they are segregated. If they were segregated before we added a mediator, they still are. If our query handler does something it shouldn't, the mediator will still happily invoke it.

I hope it doesn't sound like a mediator ran over my dog. But it's certainly not a silver bullet that sprinkles CQRS on our code or even necessarily improves our architecture.

We should ask, what are the benefits? What undesirable consequences could it have? Do I need that tool, or can I obtain the benefits I want without those consequences?

What I am asserting is that once we're already depending on abstractions, further steps to "hide" a class's dependencies usually add no value. They make it harder to read and understand, and erode our ability to detect and prevent other code smells.


问:
Format number if the function returned a number and its a float
```<code>my_number = get_salary_range(user)
</code>```

Right now my method may return 324234.23424222

I want it to be:

2342343.23

(two decimal places)

But I have to gaurd against the return value being nil, or '' etc.

How can I do this safely?

答:
The solution depends on what you want in your string when my_number.nil? is true. Forcibly converting things to Float would be a reasonable starting point:

```<code>formatted_number = '%.2f' % my_number.to_f
</code>```

That will handle the expected numeric my_number values as well as nil, "nonsense", and '' (with the latter three producing 0.00).

If you want to more thorough, then you can ask your my_number if it understands to_f:

```<code>formatted_number = '%.2f' % (my_number.respond_to?(:to_f) ? my_number.to_f : 0.0)
</code>```

But you're still left to decide what should happen if my_number cannot be sensibly converted to a Float.

You can go one step further and make the "what about things that aren't Float-ish" configurable:

```<code>def numberify(thing, default = "0.00")
    return thing.respond_to?(:to_f) \
         ? '%.2f' % thing.to_f \
         : default
end
</code>```

Further configurability is left as an exercise for the reader.

Body:
my_number = get_salary_range(user)

Right now my method may return 324234.23424222

I want it to be:

2342343.23

(two decimal places)

But I have to gaurd against the return value being nil, or '' etc.

How can I do this safely?

Body:
The solution depends on what you want in your string when my_number.nil? is true. Forcibly converting things to Float would be a reasonable starting point:

formatted_number = '%.2f' % my_number.to_f

That will handle the expected numeric my_number values as well as nil, "nonsense", and '' (with the latter three producing 0.00).

If you want to more thorough, then you can ask your my_number if it understands to_f:

formatted_number = '%.2f' % (my_number.respond_to?(:to_f) ? my_number.to_f : 0.0)

But you're still left to decide what should happen if my_number cannot be sensibly converted to a Float.

You can go one step further and make the "what about things that aren't Float-ish" configurable:

def numberify(thing, default = "0.00")
    return thing.respond_to?(:to_f) \
         ? '%.2f' % thing.to_f \
         : default
end

Further configurability is left as an exercise for the reader.


问:
Function return type mismatching with TypeScript
I can't understand it. I am knew to TypeScript and I am trying to stick to its recommendations as much as possible but this one makes no sense to me.

Reading the tip, I see the definition of type EffectCallback which is, among other things:

```<code>type EffectCallback = (() => void)
</code>```

Just to see if it makes any difference, I put the definition of the type directly and as you can see, it doesn't trigger TypeScript anymore.

What am I missing?

And another thing is, according to what TypeScript tells me, useEffect expects an EffectCallback, which is at best a function that returns void as a parameter.

<img src="https://i.stack.imgur.com/MXoyA.png" alt="TypeScript tells us useEffect expecs an EffectCallback">

The thing is that according to React documentation about useEffect, I can pass a function that returns a function. React uses this function for cleanup purposes.

My guts tell me there is one small thing I can't get my finger on that would otherwise allow me to figure this out!

答:
In your first code example you have this:

```<code>(): EffectCallback => {
</code>```

That means this is a function that returns an EffectCallback. However, that's not what useEffect is expecting. The function needs to be an EffectCallback, not return one. An EffectCallback is either a function that returns nothing, or a function that returns a teardown function.

In your second example, you move on to this:

```<code>(): (() => void) => {
</code>```

Now you're saying it's a function that returns a teardown function. And a function which returns a teardown function is one of the legal ways to do an EffectCallback, so it matches.

Unless you're using a lint rule that requires explicit return types, i wouldn't bother doing explicit return types with useEffect. It's simpler to just do () => {, and if the code you write returns something that's illegal for useEffect, typescript will point that out.

Body:
I can't understand it. I am knew to TypeScript and I am trying to stick to its recommendations as much as possible but this one makes no sense to me.

Reading the tip, I see the definition of type EffectCallback which is, among other things:

type EffectCallback = (() => void)

Just to see if it makes any difference, I put the definition of the type directly and as you can see, it doesn't trigger TypeScript anymore.

What am I missing?

And another thing is, according to what TypeScript tells me, useEffect expects an EffectCallback, which is at best a function that returns void as a parameter.

<img src="https://i.stack.imgur.com/MXoyA.png" alt="TypeScript tells us useEffect expecs an EffectCallback">

The thing is that according to React documentation about useEffect, I can pass a function that returns a function. React uses this function for cleanup purposes.

My guts tell me there is one small thing I can't get my finger on that would otherwise allow me to figure this out!

Body:
In your first code example you have this:

(): EffectCallback => {

That means this is a function that returns an EffectCallback. However, that's not what useEffect is expecting. The function needs to be an EffectCallback, not return one. An EffectCallback is either a function that returns nothing, or a function that returns a teardown function.

In your second example, you move on to this:

(): (() => void) => {

Now you're saying it's a function that returns a teardown function. And a function which returns a teardown function is one of the legal ways to do an EffectCallback, so it matches.

Unless you're using a lint rule that requires explicit return types, i wouldn't bother doing explicit return types with useEffect. It's simpler to just do () => {, and if the code you write returns something that's illegal for useEffect, typescript will point that out.


问:
Eclipse cannot find shell script in Post-build step
I have a shell script that should be running after the build step. I can run the shell in terminal from the Release directory but when I add it to eclipse it complains that "No such file or directory". What makes it confusing is that the same script works in the post-build of another project within eclipse!

I'm not sure if this affects anything, but the file is a soft link. It works in the terminal and for another project, so I don't think this should be the problem.

Things I have checked:

The shell script is in the correct directory.

The address of the shell script is correct.

The script file is executable.

Line endings are linux style.

I'm using macOS Catalina 10.15.4, Eclipse Neon.3 Release (4.6.3)

答:
Ok this was a very stupid bug but in the off chance that someone else might be haunted by it here is what happened:

I had a sample project that I used as a reference. So I just copied the post-build command from the other project to macOS notes, edited it, and put it in my project. Little I knew that macOS note just likes to change the characters! So a " was changed to “ which threw the whole thing off!


问:
Page width exceeds the 100% of the screen width
I have a strange problem, I was designing a page and after I finished, found that there is a horizontal scroll bar in the bottom of the page, I checked the page html but found that there is a close tag for each tag.

Also I tried to check the widths using jQuery and found that
$(window).width()      =   1351px
and
$(document).width()    =   1480px

any suggestions about what reason for this problem ?

答:
The easiest way to do it I found is by </p>

```<code>* {
  max-width: 100%;
}
</code>```

Body:
The easiest way to do it I found is by

* {
  max-width: 100%;
}


问:
curl: The URI prefix is not recognized
When i want to check my ports it allows only my 80th port. I also tried with http://. It was the same. I can't check specific port. Check the screenshot. My Operation System is Windows 10 Pro and this is Powershell. I also checked it on CMD too. I'm sharing the both code and image which includes my code.

:

```<code>curl localhost  /* ( It shows the information as in image, there is no problem with default port 80) */

curl localhost: 8080  //(httpd's port as i assigned)
curl: The URI prefix is not recognized.

curl localhost: 3306 // (mysql's port as i assigned)
curl: The URI prefix is not recognized.
</code>```

enter image description here

答:
The correct invocation of curl needs to include a protocol identifier in the URL, and the port needs to be attached to the host name with a colon and no space. For example, to access an HTTP server on the local host, serving through port 8080, you need to use:

```<code>curl http://localhost:8080
</code>```

Title: curl: The URI prefix is not recognized

Body:
When i want to check my ports it allows only my 80th port. I also tried with http://. It was the same. I can't check specific port. Check the screenshot. My Operation System is Windows 10 Pro and this is Powershell. I also checked it on CMD too. I'm sharing the both code and image which includes my code.

:

curl localhost  /* ( It shows the information as in image, there is no problem with default port 80) */

curl localhost: 8080  //(httpd's port as i assigned)
curl: The URI prefix is not recognized.

curl localhost: 3306 // (mysql's port as i assigned)
curl: The URI prefix is not recognized.

enter image description here

Body:
The correct invocation of curl needs to include a protocol identifier in the URL, and the port needs to be attached to the host name with a colon and no space. For example, to access an HTTP server on the local host, serving through port 8080, you need to use:

curl http://localhost:8080


问:
Animating Network Growth with NetworkX and Matplotlib
I would like to animate a graph that grows over time.

This is what I have so far:

```<code>fig = plt.figure()
ims = []
graph = nx.Graph()
for i in range(50):
    // Code to modify Graph
    nx.draw(graph, pos=nx.get_node_attributes(graph,'Position'))
    im = plt.draw()
    self.ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,repeat_delay=1000)
ani.save('dynamic_images.mp4')
plt.show()
</code>```

However, I get the following error message:

```<code> File "main.py", line 204, in <module>
    repeat_delay=1000)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 356, in __init__
    TimedAnimation.__init__(self, fig, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 304, in __init__
    Animation.__init__(self, fig, event_source=event_source, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 53, in __init__
    self._init_draw()
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 363, in _init_draw
    artist.set_visible(False)
AttributeError: 'NoneType' object has no attribute 'set_visible'
nicomoto@nicomoto-VirtualBox:~/Desktop/CS8903-SpecialProblem/Code/
</code>```

What I want is an animation, where you can see the graph growing. I can save the graph at each stage, and might be able to create an animation outside matplotlib, but is there any way of getting it work like this?

答:
As the existing answers are quite old, here is a version of how the code could look like with current versions of matplotlib and networkx.

import random
import networkx as nx
import matplotlib.pyplot as plt

graph = nx.Graph()
num_plots = 50
for node_number in range(num_plots):
    graph.add_node(node_number, Position=(random.randrange(0, 100), random.randrange(0, 100)))
    graph.add_edge(node_number, random.choice(list(graph.nodes())))
    nx.draw(graph, pos=nx.get_node_attributes(graph,'Position'))
    plt.pause(0.5)
```

Body:
I would like to animate a graph that grows over time.

This is what I have so far:

fig = plt.figure()
ims = []
graph = nx.Graph()
for i in range(50):
    // Code to modify Graph
    nx.draw(graph, pos=nx.get_node_attributes(graph,'Position'))
    im = plt.draw()
    self.ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,repeat_delay=1000)
ani.save('dynamic_images.mp4')
plt.show()

However, I get the following error message:

 File "main.py", line 204, in <module>
    repeat_delay=1000)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 356, in __init__
    TimedAnimation.__init__(self, fig, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 304, in __init__
    Animation.__init__(self, fig, event_source=event_source, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 53, in __init__
    self._init_draw()
  File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 363, in _init_draw
    artist.set_visible(False)
AttributeError: 'NoneType' object has no attribute 'set_visible'
nicomoto@nicomoto-VirtualBox:~/Desktop/CS8903-SpecialProblem/Code/

What I want is an animation, where you can see the graph growing. I can save the graph at each stage, and might be able to create an animation outside matplotlib, but is there any way of getting it work like this?


问:
asp:UpdatePanel / Custom Control / RegisterClientScriptResource
I have built a custom control that has a small amount of JavaScript. The JS is maintained as an embeded resource. When my control is rendered, I added it to the page as follows:

```<code>Page.ClientScript.RegisterClientScriptResource(
    GetType(), "Resources.MyControl.js");
</code>```

The control works just fine but when it is rendered inside of an update panel, I am guessing that the JS resource is being added to the page object which is not being sent back to the client (only the contents inside the of the update panel make it back to the client.)

I could add the JS to my application library which fixes the issue as it is loaded at the begining of the initial page request. Any other fixes? Any way to use RegisterClientScriptResource from within an update panel?

答:
Found the answer more or less here:

http://forums.asp.net/p/1040033/1445844.aspx

OwnerDisplayName: Andrew Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have built a custom control that has a small amount of JavaScript. The JS is maintained as an embeded resource. When my control is rendered, I added it to the page as follows:

Page.ClientScript.RegisterClientScriptResource(
    GetType(), "Resources.MyControl.js");

The control works just fine but when it is rendered inside of an update panel, I am guessing that the JS resource is being added to the page object which is not being sent back to the client (only the contents inside the of the update panel make it back to the client.)

I could add the JS to my application library which fixes the issue as it is loaded at the begining of the initial page request. Any other fixes? Any way to use RegisterClientScriptResource from within an update panel?

LastEditorDisplayName: Andrew Robinson


问:
Auth0 and Next.js deployed to Vercel: Location header error
I started with this sample repo: https://github.com/vercel/next.js/tree/canary/examples/auth0

My current repo: https://github.com/rebeccapeltz/next-auth-app-1

Login/Logout work fine locally.  When I deploy to Vercel and logout I get this message in the browser:

Invalid character in header content ["Location"]

I've double checked the Auth0 env variables and they seem correct.  Login works fine on Vercel. Can't figure out how to troubleshoot the header Location value that is causing the problem.

Nothing much going on yet and easy to reproduce: https://next-auth-app-1.now.sh/

答:
Solved this by removing all env variables added to the Vercel online application settings. Then added the secrets using the now CLI now secrets add and deployed the app by setting up other env variables in now.json and using now --prod.  Working OK now.  For further external env secrets and references, I'm wondering if t's better to add them via now.json or to use the online settings GUI.  One thing that wasn't clear is that when you add variables with now add secrets you need to prefix the value in the now.json with @.  Kind of like accessing bash env variables with $.  So after adding secrets my now.json looks like this

```<code>{
  "build": {
    "env": {
      "AUTH0_DOMAIN": "<name of auth0 domain>",
      "AUTH0_CLIENT_ID": "<what you get from auth0>",
      "AUTH0_CLIENT_SECRET": "@auth0_client_secret",
      "REDIRECT_URI": "<name of vercel app or domain name>/api/callback",
      "POST_LOGOUT_REDIRECT_URI": "<name of vercel app>/",
      "SESSION_COOKIE_SECRET": "@session_cookie_secret"
    }
  }
}
</code>```

Should you add all env using secrets add and then just reference by name in the now.json? not sure.

Body:
Solved this by removing all env variables added to the Vercel online application settings. Then added the secrets using the now CLI now secrets add and deployed the app by setting up other env variables in now.json and using now --prod.  Working OK now.  For further external env secrets and references, I'm wondering if t's better to add them via now.json or to use the online settings GUI.  One thing that wasn't clear is that when you add variables with now add secrets you need to prefix the value in the now.json with @.  Kind of like accessing bash env variables with $.  So after adding secrets my now.json looks like this

{
  "build": {
    "env": {
      "AUTH0_DOMAIN": "<name of auth0 domain>",
      "AUTH0_CLIENT_ID": "<what you get from auth0>",
      "AUTH0_CLIENT_SECRET": "@auth0_client_secret",
      "REDIRECT_URI": "<name of vercel app or domain name>/api/callback",
      "POST_LOGOUT_REDIRECT_URI": "<name of vercel app>/",
      "SESSION_COOKIE_SECRET": "@session_cookie_secret"
    }
  }
}

Should you add all env using secrets add and then just reference by name in the now.json? not sure.


问:
How to get a numeric sum for a "character number" within a string in Excel
I have 4 character cells that contain a "number" in positions 1 and 4, and a character in positions 2 and 3.  I want to get a numeric sum of the numbers for positions 1 and 4 for the range of cells.

My cells look like this:

I have tried SUM(MID(VALUE(B4:B21,1,1)) which gives me an invalid type error

Also tried SUM(MID(B4:B21,1,1)*1) which works with a single cell but not for a range.

答:
```<code>=SUM(IFERROR(1*MID(B4:B21,{1,4},1),0))
</code>```

OR

```<code>=SUMPRODUCT(IFERROR(1*MID(B4:B21,{1,4},1),0))
</code>```

If you have Excel O365 with dynamic arrays, then the first formula will work OK.
If you have an earlier version, you may need to either confirm the first formula as an array formula with ctrl+shift+enter, or use the second formula entered normally.

The IFERROR takes care of any values in the range that do not have the pattern of [0-9][A-Z][A-Z][0-9]  If you would prefer to detect that by returning an error, just remove the IFERROR part of the formula:

```<code>=SUM(1*MID(B4:B21,{1,4},1))
</code>```

Body:
=SUM(IFERROR(1*MID(B4:B21,{1,4},1),0))

OR

=SUMPRODUCT(IFERROR(1*MID(B4:B21,{1,4},1),0))

If you have Excel O365 with dynamic arrays, then the first formula will work OK.
If you have an earlier version, you may need to either confirm the first formula as an array formula with ctrl+shift+enter, or use the second formula entered normally.

The IFERROR takes care of any values in the range that do not have the pattern of [0-9][A-Z][A-Z][0-9]  If you would prefer to detect that by returning an error, just remove the IFERROR part of the formula:

=SUM(1*MID(B4:B21,{1,4},1))


问:
Two dynamic select boxes with data attribute in both and dependant on them
How to get dynamic select boxes dependant on the value of data attributes in both?

Got this code

HTML

```<code><select id="hours" onchange="giveSelection()">
  <option value="somethingA" data-option="1">optionA</option>
  <option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
  <option data-option="1">optionC</option>
  <option data-option="1">optionD</option>
  <option data-option="2">optionE</option>
  <option data-option="1">optionF</option>
</select>
</code>```

JS

```<code>var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');

function giveSelection() {
  sel2.innerHTML = '';
  for(var i = 0; i < options2.length; i++) {
    if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
      sel2.appendChild(options2[i]);
    }
  }
}
</code>```

I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.

Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?

答:
Since you're using jQuery, you might as well use it all the way.

To make it consistent, always use the jQuery data() method.  data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc.  So your original was comparing a dataset.option to a data(), using === which removes type coersion.  So nothing would ever be equal.

var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');

function giveSelection() {
  var target = sel1.find(':selected').data('option');

  sel2.empty().append(
    options2.filter(function(){
      return $(this).data('option') === target;
    })
  );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
  <option value="somethingA" data-option="1">optionA</option>
  <option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
  <option data-option="1">optionC</option>
  <option data-option="1">optionD</option>
  <option data-option="2">optionE</option>
  <option data-option="1">optionF</option>
</select></code>```

Body:
How to get dynamic select boxes dependant on the value of data attributes in both?

Got this code

HTML

<select id="hours" onchange="giveSelection()">
  <option value="somethingA" data-option="1">optionA</option>
  <option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
  <option data-option="1">optionC</option>
  <option data-option="1">optionD</option>
  <option data-option="2">optionE</option>
  <option data-option="1">optionF</option>
</select>

JS

var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');

function giveSelection() {
  sel2.innerHTML = '';
  for(var i = 0; i < options2.length; i++) {
    if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
      sel2.appendChild(options2[i]);
    }
  }
}

I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.

Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?

Body:
Since you're using jQuery, you might as well use it all the way.

To make it consistent, always use the jQuery data() method.  data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc.  So your original was comparing a dataset.option to a data(), using === which removes type coersion.  So nothing would ever be equal.

var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');

function giveSelection() {
  var target = sel1.find(':selected').data('option');

  sel2.empty().append(
    options2.filter(function(){
      return $(this).data('option') === target;
    })
  );
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
  <option value="somethingA" data-option="1">optionA</option>
  <option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
  <option data-option="1">optionC</option>
  <option data-option="1">optionD</option>
  <option data-option="2">optionE</option>
  <option data-option="1">optionF</option>
</select>


问:
SQL: Error invalid filegroup specified
When I try to create a table:

```<code>USE [myDB];
CREATE TABLE [myTable] (
    [Id] [int] NOT NULL IDENTITY,
    [Guid] [uniqueidentifier] NOT NULL,
    [DataFS] [varbinary](max),
    [MimeType] [nvarchar](100),
    CONSTRAINT [PK_dbo.myTable] PRIMARY KEY ([Id])
) on NewFileStream
</code>```

I get an error.

Invalid filegroup 'NewFileStream' specified.

However, I can see the filegroup NewFileStream in the list:

```<code>select
    *
from
    sys.filegroups
</code>```

答: in ssms, first you can create database from menu by right click on databases and set filegroup same there or if DB is created, before creating any table right click on your DB name and in properties select filegroup page from the left and setting up it.</p>

Title: SQL: Error invalid filegroup specified

Body:
When I try to create a table:

USE [myDB];
CREATE TABLE [myTable] (
    [Id] [int] NOT NULL IDENTITY,
    [Guid] [uniqueidentifier] NOT NULL,
    [DataFS] [varbinary](max),
    [MimeType] [nvarchar](100),
    CONSTRAINT [PK_dbo.myTable] PRIMARY KEY ([Id])
) on NewFileStream

I get an error.

Invalid filegroup 'NewFileStream' specified.

However, I can see the filegroup NewFileStream in the list:

select
    *
from
    sys.filegroups