问:
venn diagram 5 way (with 'venn' R)
First off I would like to apologize for my basic question.
I am sure that if I was an experienced user the other threads on this topic would have been satisfactory, but I couldn't manage even after reading them.
So if this might annoy you your welcome to ignore.

For those still wanting to help:
I am trying to create a 5-way venn diagram.
My data is arranged in excel as 5 columns (each representing a site A-E) and rows each representing a species abundance (0 - 16) for each of the five sites.

I want to create a nice venn diagram similar to this:
https://i.stack.imgur.com/TeRSJ.png

I am sure its probobly only takes a few clicks.
but I cant manage to:
Load my data in the write way -
which format should it be? dataset? list? matrix?

I think R seemed to suggest i can only use presence absence data (0/1) is that right?

eventually I figure I would use this command with x as my data

```<code>venn(x, snames = c(""), ilabels = FALSE, counts = FALSE, zcolor = c("bw"),
transparency = 0.3, ellipse = FALSE, size = 15, cexil = 0.45, cexsn = 0.85,
...)
</code>```

Can anyone show me what code to use ?
I can also upload my dataset if someone tells me how to do that here.

Thanks in advance

答:
Disclaimer 1: I'm not sure if your question is about how to calculate the counts per subgroup, or how to plot a 5-set Venn diagram. I'm assuming the latter.

Disclaimer 2: I find 5-set Venn diagrams extremely difficult to read. To the point of being useless. But that's my personal opinion.

If other R packages are an option, here is a worked-out 5-set example using VennDiagram (straight from the VennDiagram reference manual)

```<code>library(VennDiagram);
venn.plot <- draw.quintuple.venn(
    area1 = 301, area2 = 321, area3 = 311, area4 = 321, area5 = 301,
    n12 = 188, n13 = 191, n14 = 184, n15 = 177,
    n23 = 194, n24 = 197, n25 = 190,
    n34 = 190, n35 = 173, n45 = 186,
    n123 = 112, n124 = 108, n125 = 108,
    n134 = 111, n135 = 104, n145 = 104,
    n234 = 111, n235 = 107, n245 = 110,
    n345 = 100,
    n1234 = 61, n1235 = 60, n1245 = 59,
    n1345 = 58, n2345 = 57,
    n12345 = 31,
    category = c("A", "B", "C", "D", "E"),
    fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.col = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.cex = 2,
    margin = 0.05,
    cex = c(
        1.5, 1.5, 1.5, 1.5, 1.5, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8,
        1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 1, 1, 1, 1, 1.5),
    ind = TRUE);

png("venn_5set.png");
grid.draw(venn.plot);
dev.off();
</code>```

Update [15 November 2017]

Your source table is in an atypical format. As I explain in my comments, you usually start with either a binary matrix (one column per set, membership of every observation indicated by 0's or 1's), or a list of set elements.

To be honest, I'm less and less sure about what you are actually trying to do. I have a feeling that there might be a misconception about Venn diagrams. For example, let's take a look at the first rows of your table

```<code># Read data
library(readxl);
data <- as.data.frame(read_excel("~/Downloads/dataset4venn.xlsx"));
rownames(data) <- data[, 1];
data <- data[, -1];
head(data);
#  A B  C D  E
#1 8 8  7 8 10
#2 0 0 10 0  2
#3 0 0  0 0  3
#4 0 0  1 2  0
#5 1 0  1 0  2
#6 0 0  0 0  1
</code>```

An observation is either the presence (encoded by 1) or the absence (encoded by 0) of a unique element (in your case a species) in a specific group (i.e. a sampling site). The number of sightings as you call it does not matter here: a Venn diagram explores the logical relations between different species sampled at different sites, or in other words which unique species are shared by sites A-E.

Having said that and ignoring the number of sightings per site, you can show overlaps between different sites in the following 5-set Venn diagram. I first define a helper function cts to calculate counts per group/overlap, and then feed those numbers into draw.quintuple.venn.

```<code># Function to calculate the count per group/overlap
# Note: data is a global variable
cts <- function(set) {
    df <- data;
    for (i in 1:length(set)) df <- subset(df, df[set[i]] >= 1);
    nrow(df);
}

# Plot
library(VennDiagram);
venn.plot <- draw.quintuple.venn(
    area1 = cts("A"), area2 = cts("B"), area3 = cts("C"),
    area4 = cts("D"), area5 = cts("E"),
    n12 = cts(c("A", "B")), n13 = cts(c("A", "C")), n14 = cts(c("A", "D")),
    n15 = cts(c("A", "E")), n23 = cts(c("B", "C")), n24 = cts(c("B", "D")),
    n25 = cts(c("B", "E")), n34 = cts(c("C", "D")), n35 = cts(c("C", "E")),
    n45 = cts(c("D", "E")),
    n123 = cts(c("A", "B", "C")), n124 = cts(c("A", "B", "D")),
    n125 = cts(c("A", "B", "E")), n134 = cts(c("A", "C", "D")),
    n135 = cts(c("A", "C", "E")), n145 = cts(c("A", "D", "E")),
    n234 = cts(c("B", "C", "D")), n235 = cts(c("B", "C", "E")),
    n245 = cts(c("B", "D", "E")), n345 = cts(c("C", "D", "E")),
    n1234 = cts(c("A", "B", "C", "D")), n1235 = cts(c("A", "B", "C", "E")),
    n1245 = cts(c("A", "B", "D", "E")), n1345 = cts(c("A", "C", "D", "E")),
    n2345 = cts(c("B", "C", "D", "E")),
    n12345 = cts(c("A", "B", "C", "D", "E")),
    category = c("A", "B", "C", "D", "E"),
    fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.col = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.cex = 2,
    margin = 0.05,
    cex = c(
        1.5, 1.5, 1.5, 1.5, 1.5, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8,
        1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 1, 1, 1, 1, 1.5),
    ind = TRUE);

png("venn_5set.png");
grid.draw(venn.plot);
dev.off();
</code>```

PS

Various R packages/internet sources offer helper functions to calculate overlaps based on e.g. a binary matrix or a list of set elements. For example, the R/Bioconductor package limma offers a function limma::vennCounts that calculates counts for all overlaps based on a binary matrix. So if you don't want to write your own function (like I did), you can also use those. Either way, in the case of more complex Venn diagrams, I would suggest to not calculate overlaps manually by hand, as it's easy to make a mistake (see your error message).

Title: venn diagram 5 way (with 'venn' R)

Body:
First off I would like to apologize for my basic question.
I am sure that if I was an experienced user the other threads on this topic would have been satisfactory, but I couldn't manage even after reading them.
So if this might annoy you your welcome to ignore.

For those still wanting to help:
I am trying to create a 5-way venn diagram.
My data is arranged in excel as 5 columns (each representing a site A-E) and rows each representing a species abundance (0 - 16) for each of the five sites.

I want to create a nice venn diagram similar to this:
https://i.stack.imgur.com/TeRSJ.png

I am sure its probobly only takes a few clicks.
but I cant manage to:
Load my data in the write way -
which format should it be? dataset? list? matrix?

I think R seemed to suggest i can only use presence absence data (0/1) is that right?

eventually I figure I would use this command with x as my data

venn(x, snames = c(""), ilabels = FALSE, counts = FALSE, zcolor = c("bw"),
transparency = 0.3, ellipse = FALSE, size = 15, cexil = 0.45, cexsn = 0.85,
...)

Can anyone show me what code to use ?
I can also upload my dataset if someone tells me how to do that here.

Thanks in advance

Body:
Disclaimer 1: I'm not sure if your question is about how to calculate the counts per subgroup, or how to plot a 5-set Venn diagram. I'm assuming the latter.

Disclaimer 2: I find 5-set Venn diagrams extremely difficult to read. To the point of being useless. But that's my personal opinion.

If other R packages are an option, here is a worked-out 5-set example using VennDiagram (straight from the VennDiagram reference manual)

library(VennDiagram);
venn.plot <- draw.quintuple.venn(
    area1 = 301, area2 = 321, area3 = 311, area4 = 321, area5 = 301,
    n12 = 188, n13 = 191, n14 = 184, n15 = 177,
    n23 = 194, n24 = 197, n25 = 190,
    n34 = 190, n35 = 173, n45 = 186,
    n123 = 112, n124 = 108, n125 = 108,
    n134 = 111, n135 = 104, n145 = 104,
    n234 = 111, n235 = 107, n245 = 110,
    n345 = 100,
    n1234 = 61, n1235 = 60, n1245 = 59,
    n1345 = 58, n2345 = 57,
    n12345 = 31,
    category = c("A", "B", "C", "D", "E"),
    fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.col = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.cex = 2,
    margin = 0.05,
    cex = c(
        1.5, 1.5, 1.5, 1.5, 1.5, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8,
        1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 1, 1, 1, 1, 1.5),
    ind = TRUE);

png("venn_5set.png");
grid.draw(venn.plot);
dev.off();

Update [15 November 2017]

Your source table is in an atypical format. As I explain in my comments, you usually start with either a binary matrix (one column per set, membership of every observation indicated by 0's or 1's), or a list of set elements.

To be honest, I'm less and less sure about what you are actually trying to do. I have a feeling that there might be a misconception about Venn diagrams. For example, let's take a look at the first rows of your table

# Read data
library(readxl);
data <- as.data.frame(read_excel("~/Downloads/dataset4venn.xlsx"));
rownames(data) <- data[, 1];
data <- data[, -1];
head(data);
#  A B  C D  E
#1 8 8  7 8 10
#2 0 0 10 0  2
#3 0 0  0 0  3
#4 0 0  1 2  0
#5 1 0  1 0  2
#6 0 0  0 0  1

An observation is either the presence (encoded by 1) or the absence (encoded by 0) of a unique element (in your case a species) in a specific group (i.e. a sampling site). The number of sightings as you call it does not matter here: a Venn diagram explores the logical relations between different species sampled at different sites, or in other words which unique species are shared by sites A-E.

Having said that and ignoring the number of sightings per site, you can show overlaps between different sites in the following 5-set Venn diagram. I first define a helper function cts to calculate counts per group/overlap, and then feed those numbers into draw.quintuple.venn.

# Function to calculate the count per group/overlap
# Note: data is a global variable
cts <- function(set) {
    df <- data;
    for (i in 1:length(set)) df <- subset(df, df[set[i]] >= 1);
    nrow(df);
}

# Plot
library(VennDiagram);
venn.plot <- draw.quintuple.venn(
    area1 = cts("A"), area2 = cts("B"), area3 = cts("C"),
    area4 = cts("D"), area5 = cts("E"),
    n12 = cts(c("A", "B")), n13 = cts(c("A", "C")), n14 = cts(c("A", "D")),
    n15 = cts(c("A", "E")), n23 = cts(c("B", "C")), n24 = cts(c("B", "D")),
    n25 = cts(c("B", "E")), n34 = cts(c("C", "D")), n35 = cts(c("C", "E")),
    n45 = cts(c("D", "E")),
    n123 = cts(c("A", "B", "C")), n124 = cts(c("A", "B", "D")),
    n125 = cts(c("A", "B", "E")), n134 = cts(c("A", "C", "D")),
    n135 = cts(c("A", "C", "E")), n145 = cts(c("A", "D", "E")),
    n234 = cts(c("B", "C", "D")), n235 = cts(c("B", "C", "E")),
    n245 = cts(c("B", "D", "E")), n345 = cts(c("C", "D", "E")),
    n1234 = cts(c("A", "B", "C", "D")), n1235 = cts(c("A", "B", "C", "E")),
    n1245 = cts(c("A", "B", "D", "E")), n1345 = cts(c("A", "C", "D", "E")),
    n2345 = cts(c("B", "C", "D", "E")),
    n12345 = cts(c("A", "B", "C", "D", "E")),
    category = c("A", "B", "C", "D", "E"),
    fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.col = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
    cat.cex = 2,
    margin = 0.05,
    cex = c(
        1.5, 1.5, 1.5, 1.5, 1.5, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8,
        1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 1, 1, 1, 1, 1.5),
    ind = TRUE);

png("venn_5set.png");
grid.draw(venn.plot);
dev.off();

PS

Various R packages/internet sources offer helper functions to calculate overlaps based on e.g. a binary matrix or a list of set elements. For example, the R/Bioconductor package limma offers a function limma::vennCounts that calculates counts for all overlaps based on a binary matrix. So if you don't want to write your own function (like I did), you can also use those. Either way, in the case of more complex Venn diagrams, I would suggest to not calculate overlaps manually by hand, as it's easy to make a mistake (see your error message).


来源: stackexchange

问:
Error conversion from Boolean to String
Why do I keep receiving this error:

Conversion from String type to Boolean is not valid.

When coding:

```<code>ElseIf Word = ("aardwolf") Or ("aardwola") Then
</code>```

Or is unconvert-able to String?

答:
Try this:</p>

```<code>ElseIf Word = ("aardwolf") Or Word = ("aardwola") Then
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error conversion from Boolean to String

Body:
Why do I keep receiving this error:

Conversion from String type to Boolean is not valid.

When coding:

ElseIf Word = ("aardwolf") Or ("aardwola") Then

Or is unconvert-able to String?

Body:
Try this:

ElseIf Word = ("aardwolf") Or Word = ("aardwola") Then


问:
Take action when an image on a webpage is loaded and seen by the user
I need to take an action (Call a WEB URL) when an image on a webpage is loaded and is seen by the user (image is not hidden in a scrollable area). If the user scrolls down, and the image gets displayed, then we take the same action.

Is this possible? Using AJAX and Javascript focus? Does focus differentiate between (a) images that are loaded and displayed on screen and (b) images that are loaded but not displayed (because they are still down the scrollable page).

Would really appreciate your help.

Thanks

答:
You can hook into the onload event of the image and the onscroll event on the container.

Use math to see if the images offset is in the viewport (inside the onscroll) and check the images onload - when both criteria are met, you have arrived at your destination.

ContentLicense: CC BY-SA 2.5


问:
jQuery doesn't removing class before .each function
I got small problem with my script.

The script looks like it works, but each time it adds the selected class. It resets it before the onclick, but the class does not remove it. What could be a problem?

Only one element of the .payment class from the collection should have a .selected class

$(".payment").each(function() {
    $(".payment").removeClass("selected");
    $(this).on("click", function() {
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
background: #eaeaea;
}</code>```

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

```

答:
Maybe you should modify your code to avoid multiple event bindings. It's not a good practice to bind events in a loop.

```<code>    $(document).ready(function() {
        $(document).on("click", ".payment", function() {
            $(".payment.selected").removeClass("selected");
            $(this).addClass("selected");
            $(this).find('input[type="radio"]').prop("checked", true);
        });
    });
</code>```

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/2237/

Body:
I got small problem with my script.

The script looks like it works, but each time it adds the selected class. It resets it before the onclick, but the class does not remove it. What could be a problem?

Only one element of the .payment class from the collection should have a .selected class

$(".payment").each(function() {
    $(".payment").removeClass("selected");
    $(this).on("click", function() {
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});

.selected {
background: #eaeaea;
}

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

Body:
Maybe you should modify your code to avoid multiple event bindings. It's not a good practice to bind events in a loop.

    $(document).ready(function() {
        $(document).on("click", ".payment", function() {
            $(".payment.selected").removeClass("selected");
            $(this).addClass("selected");
            $(this).find('input[type="radio"]').prop("checked", true);
        });
    });

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/2237/


问:
Hibernate error in Spring boot initialized JPA application
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted
</code>```

Following is my dependencies in pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

答:
Try with springBootVersion = '1.5.8.RELEASE'

I can find the org.hibernate.HibernateException class in hibernate-core-5.0.12.Final-sources.jar

Body:
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted

Following is my dependencies in pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


问:
Handling sequential numbering in relative ranges for varying list sizes
I am creating a macro that builds a document from several dozen different worksheets.  It pulls lists (which can vary in length) from each of these sheets, and places them in tables on the estimate page.  The items in each table are sequentially numbered.  This sequential numbering starts over again in each table on the estimate sheet.

I have updated this question with more information because the answers have made it clear that I'm using a non-standard way of building tables.  I've included the full macro below, as well as some sample output.

Here's the full macro script for context:

```<code>'declare global variables
Dim WorkingPercentage As Variant
Dim EstimateDate As Variant
Dim LastRow As Variant
Dim EstLastRow As Variant
Dim NumRows As Integer
Dim SourceRange As Range
Dim fillrange As Range
Dim est_sht As Worksheet
Dim answer As Integer
Dim InputPercentage As Integer
Dim i As Long
Dim j As Long
Dim subcat_yn As Variant
Dim subcatprice As Variant

Sub IterateSheets()

'associate worksheet variables with job categories worksheets
Set est_sht = ActiveWorkbook.Sheets("Estimate Report")
'declare other variables

Dim WshtNameCrnt As Variant
Dim WshtNames As Variant

'prompt user whether estimate sheets are completely filled out"
answer = MsgBox("Have you completed the estimate for all relevant labor categories?", vbYesNo + vbQuestion, "Populate Estimate")

If answer = vbYes Then

'prompt user for markup percentage
InputPercentage = Application.InputBox("What deposit percentage would you like to charge?", "Enter a number", , , , , , Type:=1)

'prompt user for date to be displayed on estimate
EstimateDate = Application.InputBox("What date would you like on the estimate document?  Please enter as MM/DD/YYYY.", "Date")

WorkingPercentage = InputPercentage / 100

'prompt user whether or not to include subcategory totals
subcat_yn = MsgBox("Would you like to include subtotals next to labor subcategories in the estimate?", vbYesNo, "Display labor subcategory subtotals?")

If subcat_yn = vbYes Then
  subcatprice = "y"
ElseIf subcat_yn = vbNo Then
  subcatprice = "n"
End If

'clear out estimate sheet
est_sht.Cells.Clear

'remove gridlines
est_sht.Activate
ActiveWindow.DisplayGridlines = False

'set fill color of cells FIND CORRECT COLOR CODE
'With est_sht.Cells.Interior
'        .Pattern = xlSolid
'        .PatternColorIndex = -4142
'        .ThemeColor = xlThemeColorAccent6
'        .TintAndShade = 0
'        .PatternTintAndShade = 0
'    End With

'set row height of top accent bar
est_sht.Rows("1:1").RowHeight = 10

'set width of left 2 columns
est_sht.Columns("A:A").columnwidth = 1
est_sht.Columns("B:B").columnwidth = 3

'set color of top accent bar
With est_sht.Range("A1:J1").Interior
.Color = vbBlack
End With

'set row 2 height
est_sht.Rows("2:2").RowHeight = 16.5

'set row 3 height
est_sht.Rows("3:3").RowHeight = 80

'set text formatting
With est_sht.Rows("3:3").Font
        .Name = "Arial"
        .Size = 15
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
    End With
est_sht.Rows("3:3").Font.Bold = True

'Date stamp the estimate based on form input
est_sht.Cells(3, 3).Value = EstimateDate

'title the estimate
est_sht.Cells(3, 5).Value = "Cost Estimate"

'Insert header row text'
est_sht.Cells(4, 3).Value = "PROJECT TASKS"
est_sht.Cells(4, 4).Value = "Cost Estimate"
est_sht.Cells(4, 5).FormulaR1C1 = InputPercentage & "% Deposit"
est_sht.Cells(4, 6).Value = "Current Costs"

'format header row
With est_sht.Rows("4:4")
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
With est_sht.Rows("4:4").Font
        .Name = "Arial"
        .Size = 9
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
    End With

est_sht.Rows("4:4").Font.Bold = True

'create variant array of worksheets
WshtNames = Array("permits", "project management", "in progress design", "site prep", "services on site", "layout", "concrete", "water management", "framing", "roofing and sheet metal", "electrical", "plumbing", "HVAC", "windows and doors", "exterior finishes", "insulation", "drywall", "painting", "cabinetry", "countertops", "interior finishes", "flooring", "tile", "deck garden", "landscaping", "appliances", "punchlist", "add-ons", "contingency")

'loop through worksheets
  For WshtNameCrnt = LBound(WshtNames) To UBound(WshtNames)
     With Worksheets(WshtNames(WshtNameCrnt))

        'find last row on estimate page
        With est_sht
            If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                EstLastRow = .Cells.Find(What:="*", _
                            After:=.Range("B1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
            Else
                EstLastRow = 1
            End If
        End With

        'format sub-header
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).Font.Bold = True
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).NumberFormat = "$#,##0.00"
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).Font
        .Name = "Arial"
        .Size = 12
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
        End With

        'Find last row on current worksheet
            If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                LastRow = .Cells.Find(What:="*", _
                            After:=.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
            Else
                LastRow = 1
            End If

        'count the number of rows filled with sub-categories'
        NumRows = LastRow - 4

        'pull sub-categories from current worksheet tab to estimate page
        est_sht.Range(est_sht.Cells(EstLastRow + 3, 3), est_sht.Cells(NumRows + EstLastRow + 3, 3)).Value = .Range(.Cells(4, 1), .Cells(LastRow, 1)).Value

        'add sheet name to table
        est_sht.Cells(EstLastRow + 2, 3).Value = .Name

        'add sequential numbers next to labor categories on estimate page
        'handle the case of a single subcategory
        If NumRows = 1 Then
            est_sht.Cells(EstLastRow + 3, 2).Value = 1
        ElseIf NumRows > 1 Then
            est_sht.Cells(EstLastRow + 3, 2).Value = 1
            est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"
        End If

        'set black fill color in sequential numbers sidebar
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Interior
        .Color = vbBlack
        End With
        'format text of sequential numbers
        With est_sht.Range(est_sht.Cells(EstLastRow + 3, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Font
            .Name = "Arial"
            .Size = 9
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
        End With
        'format sequential numbers bold
        est_sht.Range(est_sht.Cells(EstLastRow + 3, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Font.Bold = True

        'copy cost subtotal to estimate page
        est_sht.Cells(EstLastRow + 2, 4).Value = .Range("G1").Value

        'initiate do while loop for labor subcategory subtotals
        Do
            'pull subtotals from subcategory items to estimate
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 4), est_sht.Cells(NumRows + EstLastRow + 3, 4)).Value = .Range(.Cells(4, 7), .Cells(LastRow, 7)).Value
            'set formula for deposit numbers on estimate sheet
            'populate deposit formula in estimate page
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 5), est_sht.Cells(NumRows + EstLastRow + 3, 5)).FormulaR1C1 = "=RC[-1]*" & WorkingPercentage
            'populate sum formula in "current costs" for labor category
            'set formula for totals on estimate sheet
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 6), est_sht.Cells(NumRows + EstLastRow + 3, 6)).FormulaR1C1 = "=SUM(RC[-2]:RC[-1])"
            'set text formatting of subtotals, deposits, and totals
            est_sht.Range(est_sht.Cells(EstLastRow + 2, 4), est_sht.Cells(NumRows + EstLastRow + 3, 6)).NumberFormat = "$#,##0.00"
            With est_sht.Range(est_sht.Cells(EstLastRow + 2, 4), est_sht.Cells(NumRows + EstLastRow + 3, 6)).Font
            .Name = "Arial"
            .Size = 9
            .Strikethrough = False
            .Superscript = False
            .Subscript = False
            .OutlineFont = False
            .Shadow = False
            .Underline = xlUnderlineStyleNone
            .ThemeColor = xlThemeColorLight1
            .TintAndShade = 0.349986266670736
            .ThemeFont = xlThemeFontMajor
            End With
        Loop While subcat_yn = y And Not subcat_yn = n

        'populate deposit formula in estimate page
        est_sht.Cells(EstLastRow + 2, 5).FormulaR1C1 = "=RC[-1]*" & WorkingPercentage
        'populate sum formula in "current costs" for labor category
        est_sht.Cells(EstLastRow + 2, 6).FormulaR1C1 = "=SUM(RC[-2]:RC[-1])"

        'format sub-category items text
        With est_sht.Range(est_sht.Cells(EstLastRow + 3, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Font
        .Name = "Arial"
        .Size = 9
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
        End With

        'format table around sub-category items and costs
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlDiagonalDown).LineStyle = xlNone
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlDiagonalUp).LineStyle = xlNone

        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeTop)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeBottom)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeRight)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlInsideHorizontal).LineStyle = xlNone

        'repaint screen as macro works and scroll with the active line
        est_sht.Activate
        ActiveWindow.ScrollRow = EstLastRow

      End With
  Next WshtNameCrnt

'this else statement refers to the msgbox statement that initializes the macro
Else
    Exit Sub
'end of main if/else loop, and end of sub'
End If

'set typeface for entire estimate sheet
est_sht.Cells.Font.Name = "Arial"

'autofit columns in entire estimate sheet
est_sht.Cells.EntireColumn.AutoFit

'remove row column under header
est_sht.Rows("5:5").Delete Shift:=xlUp

est_sht.Activate

End Sub
</code>```

Here is my current code for the numbering:

```<code>If NumRows = 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1

ElseIf NumRows > 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"

End If
</code>```

This works fine for tables that have three or more items, but tables with 1 item have no numbers, and tables with 2 items only have the first item numbered, with no numeric value next to the second item.  Here's an example of the output I'm getting:

I've tried a couple other approaches, including using an ElseIf statement for a 2 item list:

```<code>If NumRows = 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1

ElseIf NumRows = 2 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Cells(EstLastRow + 4, 2).Value = 2

ElseIf NumRows > 2 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"

End If
</code>```

But that results in the same problem.

答:
Version for numbering lists in a sheet:

with the following main assumptions:

1) Start row of numbering range is B6

2) Header sections are always in Bold e.g. Dry Wall

Code:

```<code>Option Explicit

Public Sub AddRowNumsToListItems()

    Dim wb As Workbook
    Dim est_sht As Worksheet
    Dim numRange As Range
    Dim lastRow As Long                          'lastRow in col C
    Dim currRow As Range

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")        'change as appropriate

    lastRow = est_sht.Cells(est_sht.Rows.Count, "C").End(xlUp).Row

    Set numRange = est_sht.Range("C5:C" & lastRow)

    Dim counter As Long

    counter = 0

    For Each currRow In numRange.Rows            'loop column C

        If Not currRow.Font.Bold And Not IsEmpty(currRow) Then
            counter = counter + 1
            currRow.Offset(, -1) = counter 'adjacent column add number
        Else
           counter = 0
        End If

    Next currRow

End Sub
</code>```

Excel table version:

With the following assumptions:

Data is set up as Excel tables and you have a column called RowNum in each table that holds the sequential row numbering for the table

Row numbering starts at one for each table

Every table in est_sht will have this numbering added

In essence, there is a Function ListTables which collects all the table names in the sheet est_sht and stores them in an array tableArr.

There is a procedure AddRowNumsToTables that calls this function and loops the table names adding an active cell formula "=ROW()-ROW(" & tableArr(currTable) & ")+1" to the column RowNum which sequentially numbers the rows in each table.

Let me know if this is close to what you were after.

In a standard module put the following:

```<code>Private Sub AddRowNumsToTables()

    Dim wb As Workbook
    Dim est_sht As Worksheet

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")

    Dim tableArr() As String

    tableArr = ListTables

    Dim currTable As Long

    For currTable = LBound(tableArr) To UBound(tableArr)

        With est_sht.ListObjects(tableArr(currTable))

            est_sht.Range(tableArr(currTable) & "[RowNum]").FormulaR1C1 = "=ROW()-ROW(" & tableArr(currTable) & ")+1"

        End With

    Next currTable
End Sub

Private Function ListTables() As String()

    Dim wb As Workbook
    Dim est_sht As Worksheet
    Dim tbl As ListObject
    Dim tableArr() As String
    ReDim tableArr(0 To 100)
    Dim counter As Long

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")
    counter = 0

    For Each tbl In est_sht.ListObjects
        tableArr(counter) = tbl.Name
        counter = counter + 1
    Next tbl

    ReDim Preserve tableArr(0 To counter - 1)

    ListTables = tableArr

End Function
</code>```

Body:
I am creating a macro that builds a document from several dozen different worksheets.  It pulls lists (which can vary in length) from each of these sheets, and places them in tables on the estimate page.  The items in each table are sequentially numbered.  This sequential numbering starts over again in each table on the estimate sheet.

I have updated this question with more information because the answers have made it clear that I'm using a non-standard way of building tables.  I've included the full macro below, as well as some sample output.

Here's the full macro script for context:

'declare global variables
Dim WorkingPercentage As Variant
Dim EstimateDate As Variant
Dim LastRow As Variant
Dim EstLastRow As Variant
Dim NumRows As Integer
Dim SourceRange As Range
Dim fillrange As Range
Dim est_sht As Worksheet
Dim answer As Integer
Dim InputPercentage As Integer
Dim i As Long
Dim j As Long
Dim subcat_yn As Variant
Dim subcatprice As Variant

Sub IterateSheets()

'associate worksheet variables with job categories worksheets
Set est_sht = ActiveWorkbook.Sheets("Estimate Report")
'declare other variables

Dim WshtNameCrnt As Variant
Dim WshtNames As Variant

'prompt user whether estimate sheets are completely filled out"
answer = MsgBox("Have you completed the estimate for all relevant labor categories?", vbYesNo + vbQuestion, "Populate Estimate")

If answer = vbYes Then

'prompt user for markup percentage
InputPercentage = Application.InputBox("What deposit percentage would you like to charge?", "Enter a number", , , , , , Type:=1)

'prompt user for date to be displayed on estimate
EstimateDate = Application.InputBox("What date would you like on the estimate document?  Please enter as MM/DD/YYYY.", "Date")

WorkingPercentage = InputPercentage / 100

'prompt user whether or not to include subcategory totals
subcat_yn = MsgBox("Would you like to include subtotals next to labor subcategories in the estimate?", vbYesNo, "Display labor subcategory subtotals?")

If subcat_yn = vbYes Then
  subcatprice = "y"
ElseIf subcat_yn = vbNo Then
  subcatprice = "n"
End If

'clear out estimate sheet
est_sht.Cells.Clear

'remove gridlines
est_sht.Activate
ActiveWindow.DisplayGridlines = False

'set fill color of cells FIND CORRECT COLOR CODE
'With est_sht.Cells.Interior
'        .Pattern = xlSolid
'        .PatternColorIndex = -4142
'        .ThemeColor = xlThemeColorAccent6
'        .TintAndShade = 0
'        .PatternTintAndShade = 0
'    End With

'set row height of top accent bar
est_sht.Rows("1:1").RowHeight = 10

'set width of left 2 columns
est_sht.Columns("A:A").columnwidth = 1
est_sht.Columns("B:B").columnwidth = 3

'set color of top accent bar
With est_sht.Range("A1:J1").Interior
.Color = vbBlack
End With

'set row 2 height
est_sht.Rows("2:2").RowHeight = 16.5

'set row 3 height
est_sht.Rows("3:3").RowHeight = 80

'set text formatting
With est_sht.Rows("3:3").Font
        .Name = "Arial"
        .Size = 15
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
    End With
est_sht.Rows("3:3").Font.Bold = True

'Date stamp the estimate based on form input
est_sht.Cells(3, 3).Value = EstimateDate

'title the estimate
est_sht.Cells(3, 5).Value = "Cost Estimate"

'Insert header row text'
est_sht.Cells(4, 3).Value = "PROJECT TASKS"
est_sht.Cells(4, 4).Value = "Cost Estimate"
est_sht.Cells(4, 5).FormulaR1C1 = InputPercentage & "% Deposit"
est_sht.Cells(4, 6).Value = "Current Costs"

'format header row
With est_sht.Rows("4:4")
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
With est_sht.Rows("4:4").Font
        .Name = "Arial"
        .Size = 9
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
    End With

est_sht.Rows("4:4").Font.Bold = True

'create variant array of worksheets
WshtNames = Array("permits", "project management", "in progress design", "site prep", "services on site", "layout", "concrete", "water management", "framing", "roofing and sheet metal", "electrical", "plumbing", "HVAC", "windows and doors", "exterior finishes", "insulation", "drywall", "painting", "cabinetry", "countertops", "interior finishes", "flooring", "tile", "deck garden", "landscaping", "appliances", "punchlist", "add-ons", "contingency")

'loop through worksheets
  For WshtNameCrnt = LBound(WshtNames) To UBound(WshtNames)
     With Worksheets(WshtNames(WshtNameCrnt))

        'find last row on estimate page
        With est_sht
            If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                EstLastRow = .Cells.Find(What:="*", _
                            After:=.Range("B1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
            Else
                EstLastRow = 1
            End If
        End With

        'format sub-header
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).Font.Bold = True
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).NumberFormat = "$#,##0.00"
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + 2, 6)).Font
        .Name = "Arial"
        .Size = 12
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
        End With

        'Find last row on current worksheet
            If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                LastRow = .Cells.Find(What:="*", _
                            After:=.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
            Else
                LastRow = 1
            End If

        'count the number of rows filled with sub-categories'
        NumRows = LastRow - 4

        'pull sub-categories from current worksheet tab to estimate page
        est_sht.Range(est_sht.Cells(EstLastRow + 3, 3), est_sht.Cells(NumRows + EstLastRow + 3, 3)).Value = .Range(.Cells(4, 1), .Cells(LastRow, 1)).Value

        'add sheet name to table
        est_sht.Cells(EstLastRow + 2, 3).Value = .Name

        'add sequential numbers next to labor categories on estimate page
        'handle the case of a single subcategory
        If NumRows = 1 Then
            est_sht.Cells(EstLastRow + 3, 2).Value = 1
        ElseIf NumRows > 1 Then
            est_sht.Cells(EstLastRow + 3, 2).Value = 1
            est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"
        End If

        'set black fill color in sequential numbers sidebar
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Interior
        .Color = vbBlack
        End With
        'format text of sequential numbers
        With est_sht.Range(est_sht.Cells(EstLastRow + 3, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Font
            .Name = "Arial"
            .Size = 9
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
        End With
        'format sequential numbers bold
        est_sht.Range(est_sht.Cells(EstLastRow + 3, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).Font.Bold = True

        'copy cost subtotal to estimate page
        est_sht.Cells(EstLastRow + 2, 4).Value = .Range("G1").Value

        'initiate do while loop for labor subcategory subtotals
        Do
            'pull subtotals from subcategory items to estimate
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 4), est_sht.Cells(NumRows + EstLastRow + 3, 4)).Value = .Range(.Cells(4, 7), .Cells(LastRow, 7)).Value
            'set formula for deposit numbers on estimate sheet
            'populate deposit formula in estimate page
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 5), est_sht.Cells(NumRows + EstLastRow + 3, 5)).FormulaR1C1 = "=RC[-1]*" & WorkingPercentage
            'populate sum formula in "current costs" for labor category
            'set formula for totals on estimate sheet
            est_sht.Range(est_sht.Cells(EstLastRow + 3, 6), est_sht.Cells(NumRows + EstLastRow + 3, 6)).FormulaR1C1 = "=SUM(RC[-2]:RC[-1])"
            'set text formatting of subtotals, deposits, and totals
            est_sht.Range(est_sht.Cells(EstLastRow + 2, 4), est_sht.Cells(NumRows + EstLastRow + 3, 6)).NumberFormat = "$#,##0.00"
            With est_sht.Range(est_sht.Cells(EstLastRow + 2, 4), est_sht.Cells(NumRows + EstLastRow + 3, 6)).Font
            .Name = "Arial"
            .Size = 9
            .Strikethrough = False
            .Superscript = False
            .Subscript = False
            .OutlineFont = False
            .Shadow = False
            .Underline = xlUnderlineStyleNone
            .ThemeColor = xlThemeColorLight1
            .TintAndShade = 0.349986266670736
            .ThemeFont = xlThemeFontMajor
            End With
        Loop While subcat_yn = y And Not subcat_yn = n

        'populate deposit formula in estimate page
        est_sht.Cells(EstLastRow + 2, 5).FormulaR1C1 = "=RC[-1]*" & WorkingPercentage
        'populate sum formula in "current costs" for labor category
        est_sht.Cells(EstLastRow + 2, 6).FormulaR1C1 = "=SUM(RC[-2]:RC[-1])"

        'format sub-category items text
        With est_sht.Range(est_sht.Cells(EstLastRow + 3, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Font
        .Name = "Arial"
        .Size = 9
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0.349986266670736
        .ThemeFont = xlThemeFontMajor
        End With

        'format table around sub-category items and costs
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlDiagonalDown).LineStyle = xlNone
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlDiagonalUp).LineStyle = xlNone

        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeTop)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeBottom)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlEdgeRight)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        With est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .Weight = xlMedium
        End With
        est_sht.Range(est_sht.Cells(EstLastRow + 2, 3), est_sht.Cells(EstLastRow + NumRows + 3, 6)).Borders(xlInsideHorizontal).LineStyle = xlNone

        'repaint screen as macro works and scroll with the active line
        est_sht.Activate
        ActiveWindow.ScrollRow = EstLastRow

      End With
  Next WshtNameCrnt

'this else statement refers to the msgbox statement that initializes the macro
Else
    Exit Sub
'end of main if/else loop, and end of sub'
End If

'set typeface for entire estimate sheet
est_sht.Cells.Font.Name = "Arial"

'autofit columns in entire estimate sheet
est_sht.Cells.EntireColumn.AutoFit

'remove row column under header
est_sht.Rows("5:5").Delete Shift:=xlUp

est_sht.Activate

End Sub

Here is my current code for the numbering:

If NumRows = 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1

ElseIf NumRows > 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"

End If

This works fine for tables that have three or more items, but tables with 1 item have no numbers, and tables with 2 items only have the first item numbered, with no numeric value next to the second item.  Here's an example of the output I'm getting:

I've tried a couple other approaches, including using an ElseIf statement for a 2 item list:

If NumRows = 1 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1

ElseIf NumRows = 2 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Cells(EstLastRow + 4, 2).Value = 2

ElseIf NumRows > 2 Then
    est_sht.Cells(EstLastRow + 3, 2).Value = 1
    est_sht.Range(est_sht.Cells(EstLastRow + 4, 2), est_sht.Cells(EstLastRow + NumRows + 3, 2)).FormulaR1C1 = "=R[-1]C+1"

End If

But that results in the same problem.

Body:
Version for numbering lists in a sheet:

with the following main assumptions:

1) Start row of numbering range is B6

2) Header sections are always in Bold e.g. Dry Wall

Code:

Option Explicit

Public Sub AddRowNumsToListItems()

    Dim wb As Workbook
    Dim est_sht As Worksheet
    Dim numRange As Range
    Dim lastRow As Long                          'lastRow in col C
    Dim currRow As Range

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")        'change as appropriate

    lastRow = est_sht.Cells(est_sht.Rows.Count, "C").End(xlUp).Row

    Set numRange = est_sht.Range("C5:C" & lastRow)

    Dim counter As Long

    counter = 0

    For Each currRow In numRange.Rows            'loop column C

        If Not currRow.Font.Bold And Not IsEmpty(currRow) Then
            counter = counter + 1
            currRow.Offset(, -1) = counter 'adjacent column add number
        Else
           counter = 0
        End If

    Next currRow

End Sub

Excel table version:

With the following assumptions:

Data is set up as Excel tables and you have a column called RowNum in each table that holds the sequential row numbering for the table

Row numbering starts at one for each table

Every table in est_sht will have this numbering added

In essence, there is a Function ListTables which collects all the table names in the sheet est_sht and stores them in an array tableArr.

There is a procedure AddRowNumsToTables that calls this function and loops the table names adding an active cell formula "=ROW()-ROW(" & tableArr(currTable) & ")+1" to the column RowNum which sequentially numbers the rows in each table.

Let me know if this is close to what you were after.

In a standard module put the following:

Private Sub AddRowNumsToTables()

    Dim wb As Workbook
    Dim est_sht As Worksheet

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")

    Dim tableArr() As String

    tableArr = ListTables

    Dim currTable As Long

    For currTable = LBound(tableArr) To UBound(tableArr)

        With est_sht.ListObjects(tableArr(currTable))

            est_sht.Range(tableArr(currTable) & "[RowNum]").FormulaR1C1 = "=ROW()-ROW(" & tableArr(currTable) & ")+1"

        End With

    Next currTable
End Sub

Private Function ListTables() As String()

    Dim wb As Workbook
    Dim est_sht As Worksheet
    Dim tbl As ListObject
    Dim tableArr() As String
    ReDim tableArr(0 To 100)
    Dim counter As Long

    Set wb = ThisWorkbook
    Set est_sht = wb.Worksheets("Sheet1")
    counter = 0

    For Each tbl In est_sht.ListObjects
        tableArr(counter) = tbl.Name
        counter = counter + 1
    Next tbl

    ReDim Preserve tableArr(0 To counter - 1)

    ListTables = tableArr

End Function


问:
Splitting string with comma, issue with money
I have string like below which i'd like to split by comma's. But there's an issue with the money which is also has comma in it.
What i like to achieve; if there's a number after comma do not seperate from that one. I'd like to do the job with javascript.

025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,

What i've tried so far with thousand combinations;

[^\,!\?]+

What i expect as a result;

```<code>025056-03110
245056030
1
Standart Discount
Standart Discount
*15,940.00USD*
29/11/2017
1
</code>```

答:
Maybe you could do it like this:

(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)

var pattern = /(?:\d+,(?=\d+\.).+?(?=,)|[\w-\/.\s]+)/g;
var str = "025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,";
var matches = str.match(pattern);
for (var i = 0; i < matches.length; i++) {
    if (matches[i].indexOf('USD') !== -1) {
        matches[i] = "*" + matches[i] + "*";
    }
}
console.log(matches.join('\n'));```

Body:
I have string like below which i'd like to split by comma's. But there's an issue with the money which is also has comma in it.
What i like to achieve; if there's a number after comma do not seperate from that one. I'd like to do the job with javascript.

025056-03110,245056030,1,Standart Discount,Standart Discount,15,940.00USD,29/11/2017,1,

What i've tried so far with thousand combinations;

[^\,!\?]+

What i expect as a result;

025056-03110
245056030
1
Standart Discount
Standart Discount
*15,940.00USD*
29/11/2017
1


问:
Zappa Certify Issue
I've been having issues with deploying a domain I recently transferred from godaddy to AWS.

Here's the zappa settings:

```<code>{
"staging": {
    "app_function": "__init__.app",
    "aws_region": "ap-southeast-2",
    "profile_name": "default",
    "s3_bucket": "zappa-flowersapp",
    "domain": "minnidesign.com",
    "certificate_arn": "arn:aws:acm:us-east-1:985294012425:certificate/a8740ef0-0d99-4355-ac99-210ead89b743"
    }
}
</code>```

On running zappa certify the first time I get this error:

```<code>params[name] = orig_value.split('/')[-1]
AttributeError: 'NoneType' object has no attribute 'split'
</code>```

The second time I am getting this error:

```<code>raise error_class(parsed_response, operation_name)
BadRequestException: An error occurred (BadRequestException) when calling the CreateDomainName operation: The domain name you provided already exists.
</code>```

I have no idea why this is happening, I have never had this kind of issue with Zappa. (When I go to minnidesign.com there is a server not found error).

Does anyone know a solution to this problem? Many thanks in advance!

答: I just had to create a hosted zone then update the NS records of the registered domain with the new hosted zone's NS records, then created new certificate and worked a charm!</p>

Title: Zappa Certify Issue

Body:
I've been having issues with deploying a domain I recently transferred from godaddy to AWS.

Here's the zappa settings:

{
"staging": {
    "app_function": "__init__.app",
    "aws_region": "ap-southeast-2",
    "profile_name": "default",
    "s3_bucket": "zappa-flowersapp",
    "domain": "minnidesign.com",
    "certificate_arn": "arn:aws:acm:us-east-1:985294012425:certificate/a8740ef0-0d99-4355-ac99-210ead89b743"
    }
}

On running zappa certify the first time I get this error:

params[name] = orig_value.split('/')[-1]
AttributeError: 'NoneType' object has no attribute 'split'

The second time I am getting this error:

raise error_class(parsed_response, operation_name)
BadRequestException: An error occurred (BadRequestException) when calling the CreateDomainName operation: The domain name you provided already exists.

I have no idea why this is happening, I have never had this kind of issue with Zappa. (When I go to minnidesign.com there is a server not found error).

Does anyone know a solution to this problem? Many thanks in advance!


问:
Run javascript on server and send DOM results to client
I've been stuck on this one for a while, so it's time to consult the pros.  I've created a charting application that uses javascript to do heavy DOM manipulation/generation on the client (creating barcharts made of colored divs, etc).

Long story short, I want to avoid sending my js library to the client.  Is there any way to create the content on the server, using my existing javascript library, and only send the javascript-generated HTML to the client?

Thanks for taking the time!

答: Try to convert your JavaScript DOM code to Java W3C DOM on ItsNat, for instance, take a look to this example. Umm is based on Java not .Net. </p>


问:
Get position of UIAlertAction?
I like to do a tutorial that ask user have to press the 'Always Allow' button in the Location Permission request.

In my opinion, use a ViewController and add a UIAlertController as a subView in it, and then add another CAShapeLayer to create a white rectangle to highlight the 'Always Allow' UIAlertAction.

My problem is that I can't locate the 'Always Allow' UIAlertAction.
I need the CGPoint of this UIAlertAction. How to get it?

Update:This is not a real permission alert, I think many people misunderstanding it. In iOS, when a permission alert popup, user sometimes choose any one without reading the message on it. Because our hardware product needs location update in background, we hope user have to choose 'Always' location option, this is why do that. We want to do a guide to teach people that a alert page will display at next step and please choose the correct one. After pressing the upper right corner button, the real permission will popup. I think it's a good way to guide user.

The Right Way To Ask Users For iOS Permissions

Any suggestions for it? Thanks.

答:
The "Allow to use location" alert is provided by the system which displays the UI in another process.

This is bad UX.

Apple will reject your app for doing this.

Title: Get position of UIAlertAction?


问:
Get number of years between two timestamp objects in Java
I am having two timestamp objects.

```<code>java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
System.out.println(timestamp);

Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
System.out.println(ctimestamp);
System.out.println(ctimestamp.getYear() - timestamp.getYear());
</code>```

Output :

```<code>1800-01-01 00:00:00.0
2017-11-13 11:42:44.56
217
</code>```

It works and gives proper value of 217. The problem here is getYear() is deprecated.

Is there any other way to get it, so that I don't get any deprecation warnings?

答:
Use Calendarclass :

```<code>    Timestamp timestamp = Timestamp.valueOf("1800-01-01 00:00:00.0");

    Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(timestamp);

    int firstYearValue = calendar.get(Calendar.YEAR);

    calendar.setTime(ctimestamp);
    int secondYearValue = calendar.get(Calendar.YEAR);

    int diff = secondYearValue - firstYearValue;
    System.out.println(diff);
</code>```

Body:
I am having two timestamp objects.

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("1800-01-01 00:00:00.0");
System.out.println(timestamp);

Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
System.out.println(ctimestamp);
System.out.println(ctimestamp.getYear() - timestamp.getYear());

Output :

1800-01-01 00:00:00.0
2017-11-13 11:42:44.56
217

It works and gives proper value of 217. The problem here is getYear() is deprecated.

Is there any other way to get it, so that I don't get any deprecation warnings?

Body:
Use Calendarclass :

    Timestamp timestamp = Timestamp.valueOf("1800-01-01 00:00:00.0");

    Timestamp ctimestamp = new Timestamp(System.currentTimeMillis());
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(timestamp);

    int firstYearValue = calendar.get(Calendar.YEAR);

    calendar.setTime(ctimestamp);
    int secondYearValue = calendar.get(Calendar.YEAR);

    int diff = secondYearValue - firstYearValue;
    System.out.println(diff);


问:
Keystrokes In Applescript
I'm trying to run an applescript application on Mac OSX that automatically takes a picture with photobooth.  It isn't working.  The keystroke for taking a picture is "command" and "return".

Here is my script so far:

```<code>tell application "Photo Booth"
    activate
end tell
tell application "System Events"
    delay 3
    keystroke "return" using command down
end tell
</code>```

答:
If you wanted an instant photo you could use this instead:

tell application "Photo Booth"

activate

end tell

tell application "System Events"

delay 3

keystroke return using {command down, option down}

end tell

Title: Keystrokes In Applescript

Body:
I'm trying to run an applescript application on Mac OSX that automatically takes a picture with photobooth.  It isn't working.  The keystroke for taking a picture is "command" and "return".

Here is my script so far:

tell application "Photo Booth"
    activate
end tell
tell application "System Events"
    delay 3
    keystroke "return" using command down
end tell


问:
"connection refused" when attempting to run Selenium with Headless Firefox
The versions of each item I am using are as follows: Selenium 3.4.0, GeckoDriver v0.19.0 for Linux 64 and Firefox 52.4.0.

First question I've ever asked on this site. I am normally able to figure stuff out by simple lurking, but this problem has been giving me a real run for my money.

I am attempting to set up Jenkins to "mvn clean test" a project that will run Selenium (using version 3.4.0) tests on "test". Essentially, the project is a collection of classes that use Selenium to interact with another project. I have attached JUnit tests to this project so that by building it, I can use the testing suite I created.

I was able to do this on my local machine using either Chrome or Firefox, but I want to have Jenkins do it automatically on a nightly basis. I have Jenkins on a Centos 7 server, and I am attempting to get the project to work with a headless browser. I have had some separate problems with PhantomJS (the DOM is blank in Phantom), so I am also attempting to use headless Firefox (using version 52.4.0). Here are the general steps I took:

Install Xvfb on CentOS.

Install Firefox (52.4.0) on CentOS.

Run "Xvfb :99 -ac &"

Run "export DISPLAY=:99"

Run the project with "mvn clean test".

(I have, and I will, attempt steps 3-5 on Jenkins, but am stuck at just getting it to work on CentOS alone.)

The project starts alright with:

T E S T S

. . . . . .

  Running com.*****.*****.workflows.HappyPathTest

  . . . . . .

  1510266036943   Marionette      INFO    Listening on port 2828

It then sits at this point for a moment before the following happens:

org.openqa.selenium.WebDriverException: connection refused

  Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'

  System info: host: 'localhost.localdomain', ip: '0:0:0:0:0:0:0:1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-327.36.3.el7.x8  6_64', java.version: '1.8.0_111'

  Driver info: driver.version: FirefoxDriver

  remote stacktrace: stack backtrace:

                  0:           0x4f388c - backtrace::backtrace::trace:

and so on.

The line that the error occurs on is a simple: "methodDriver = new FirefoxDriver();"

I initially took the "connection refused" to mean that the firewall was somehow blocking it, but, of course, everything is on the same server and the "firewalld" process is not running as it is.

Any help would be greatly appreciated.

Edit: The suggested thread involved an apparently similar issue, but the suggestions in there were different from what I used to solve the problem here. I did, however, manage to get past this issue by updating my version of Firefox.

答:
Please check if the disk is full of the core dump files. It could be in your working directory or the user directory.
In my environment, we only get first 20 test passed since our user directory only has less than 1G free space.</p>


问:
Angular httpClient: Reformat date in json
I have an object with a property of kind date. If I post it with httpClient.post(...) the date property has it's natural string representation. How can I adopt it to a format that the server understands?</p>

答:
you can make use of this to convert it into the format you need and send it over to the server.

Angular Date Pipes

Try this,

Import the {DatePipe} from '@angular/common' and include this in your main module.

Use DatePipe in your ts code where you wish to convert the date into a format that you want to change and use transform method and change it in the form you want.

Also do not forget to initialize the DatePipe in your constructor,

Try this code

```<code>let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));
</code>```

Body:
you can make use of this to convert it into the format you need and send it over to the server.

Angular Date Pipes

Try this,

Import the {DatePipe} from '@angular/common' and include this in your main module.

Use DatePipe in your ts code where you wish to convert the date into a format that you want to change and use transform method and change it in the form you want.

Also do not forget to initialize the DatePipe in your constructor,

Try this code

let myDate = new Date();
console.log(this.datepipe.transform(myDate, 'yyyy-mm-dd'));


问:
Inserting duplicates with nhibernate
I need to duplicate an object and all of its children, what I'm doing now is retrieve the object, make a deep clone and put all ids to 0 (parent and children) and save it back to the DB, but the original object gets modified in the DB. Is there a way to make it simpler?

Thanks in advance for the help.
Ariel.

EDIT

I'm using serialization to get a deep copy of the object, but the strangest thing is this. I'm serializing the object and I save it in a file, then I deserialize the object and put ids to 0, then I make some operations for some values of the parent and children to change the original values, I save everything fine, but the problem is when I flush the session. for example I have this:

ORIGINAL:

```<code>Parent
  IdParent = 1
  Name = "Parent"
Child 1
  IdChild = 1
  IdParent = 1
  Name = "Child 1"
</code>```

MODIFIED:

```<code>Parent = 0
  Name = "Parent"
Child 1
  IdChild = 0
  IdParent = null
  Name = "Child 1 modified"
</code>```

The parent has a collection of type IList When I save the values everythings's fine, but when the flush is called this extra statement is executed:

UPDATE Child SET IdParent = null WHERE IdParent = 1

And the original data in the DB is modified like this

CHILD TABLE:

```<code>IdChild     | IdParent    | Name
--------------------------------------
1           | Null        | "Child 1"
2           | 2           | "Child 1 modified"
</code>```

Any idea???

Thanks a lot for any help.
Ariel

EDIT 2

The methods I'm using

SERIALIZE:

```<code>Stream archivo = File.Create(rutaArchivo);
BinaryFormatter serializador = new BinaryFormatter();
serializador.Serialize(archivo, objetoASerializar);
archivo.Close();
</code>```

DESERIALIZE:

```<code>Stream archivo = File.OpenRead(rutaArchivo);
BinaryFormatter serializador = new BinaryFormatter();
T objetoDeserializado = (T)serializador.Deserialize(archivo);
archivo.Close();
</code>```

答:
Hmm, I think if original object gets modified, you "deep copy" is not so deep, I guess you copy collections from original object. There are 2 general way's i think you can make this:

Create .NET object copy this can be done in different ways, modify you clone code to make it really deep copy clone, serialize you object and deserialize it to make a clone, try to use AutoMapper to create clone (not sure if it can map object to itself thus creating copy) but if it can it will copy you collections the proper way.

Do it the DB SQL style: INSERT INTO Table (SELECT * FROM TABLE where Id=@id)

Title: Inserting duplicates with nhibernate

Body:
I need to duplicate an object and all of its children, what I'm doing now is retrieve the object, make a deep clone and put all ids to 0 (parent and children) and save it back to the DB, but the original object gets modified in the DB. Is there a way to make it simpler?

Thanks in advance for the help.
Ariel.

EDIT

I'm using serialization to get a deep copy of the object, but the strangest thing is this. I'm serializing the object and I save it in a file, then I deserialize the object and put ids to 0, then I make some operations for some values of the parent and children to change the original values, I save everything fine, but the problem is when I flush the session. for example I have this:

ORIGINAL:

Parent
  IdParent = 1
  Name = "Parent"
Child 1
  IdChild = 1
  IdParent = 1
  Name = "Child 1"

MODIFIED:

Parent = 0
  Name = "Parent"
Child 1
  IdChild = 0
  IdParent = null
  Name = "Child 1 modified"

The parent has a collection of type IList When I save the values everythings's fine, but when the flush is called this extra statement is executed:

UPDATE Child SET IdParent = null WHERE IdParent = 1

And the original data in the DB is modified like this

CHILD TABLE:

IdChild     | IdParent    | Name
--------------------------------------
1           | Null        | "Child 1"
2           | 2           | "Child 1 modified"

Any idea???

Thanks a lot for any help.
Ariel

EDIT 2

The methods I'm using

SERIALIZE:

Stream archivo = File.Create(rutaArchivo);
BinaryFormatter serializador = new BinaryFormatter();
serializador.Serialize(archivo, objetoASerializar);
archivo.Close();

DESERIALIZE:

Stream archivo = File.OpenRead(rutaArchivo);
BinaryFormatter serializador = new BinaryFormatter();
T objetoDeserializado = (T)serializador.Deserialize(archivo);
archivo.Close();


问:
If Attribute value is not empty in given xml, get the attribute value
In the below XML I need attribute value (ID="5682094") if Type="CARMENT"  from IdealId element

```<code><ns0:doingRS xmlns:ns0="http://myorg.com" xmlns:ns2="http://commonOrg">
    <ns2:Pass/>
    <ns0:something>
        <ns0:some abc="false" xyz="false" prq="track" str="RACK" fdg="true" fgdg="true" fdfd="false" ewe="false" ytyt="false" trtrt="false" ewew="false" fdfdf="false" bgn="false" ujm="false" qa="false" qws="false" qwe="false" wqwqwqw="false">
            <ns2:SomeRates>
                <ns2:SomeRate CodeH="track" someCode="RACK">
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5033095"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID=""/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5043839"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID=""/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5682094"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID="5682094"/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                </ns2:SomeRate>
            </ns2:SomeRates>
        </ns0:some>
    </ns0:something>
</ns0:doingRS>
</code>```

So in summary i need attribute value if and only if attribute is not empty.
If there exists xpath/xquery to extract the attribute Id, please help me out

答:
Select item with @Type="CARMENT" and then it's not-empty ID</p>

```<code>//*[@Type="CARMENT"]/@ID[not(.="")]
</code>```

Body:
In the below XML I need attribute value (ID="5682094") if Type="CARMENT"  from IdealId element

<ns0:doingRS xmlns:ns0="http://myorg.com" xmlns:ns2="http://commonOrg">
    <ns2:Pass/>
    <ns0:something>
        <ns0:some abc="false" xyz="false" prq="track" str="RACK" fdg="true" fgdg="true" fdfd="false" ewe="false" ytyt="false" trtrt="false" ewew="false" fdfdf="false" bgn="false" ujm="false" qa="false" qws="false" qwe="false" wqwqwqw="false">
            <ns2:SomeRates>
                <ns2:SomeRate CodeH="track" someCode="RACK">
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5033095"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID=""/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5043839"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID=""/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                    <ns2:SomeProfile>
                        <ns2:SomeProfileList>
                            <ns2:IdealID Type="Prr" Ideal_CTX="ABC" ID="5682094"/>
                            <ns2:IdealID Type="CARMENT" Ideal_CTX="ABC" ID="5682094"/>
                        </ns2:SomeProfileList>
                    </ns2:SomeProfile>
                </ns2:SomeRate>
            </ns2:SomeRates>
        </ns0:some>
    </ns0:something>
</ns0:doingRS>

So in summary i need attribute value if and only if attribute is not empty.
If there exists xpath/xquery to extract the attribute Id, please help me out

Body:
Select item with @Type="CARMENT" and then it's not-empty ID

//*[@Type="CARMENT"]/@ID[not(.="")]


问:
MathJax plugin default font should be same as that of CKEditor
We are using MathJax plugin as part of CKEditor. The font for MathJax is different from the default font of CKEditor. We would like to change the default font of MathJax plugin to match CKeditor font.</p>

答:
As math formulas are rendered directly by MathJax plugin, you should check how to change font for MathJax itself (see MathJax docs on Font Support).

There is already an answer covering this here - https://stackoverflow.com/a/41475014/646871.

Remember to include proper MathJax config on the same page were CKEditor is used, like:

```<code><script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        "HTML-CSS" : {
            availableFonts : ["STIX"],
            preferredFont : "STIX",
            webFont : "STIX-Web",
            imageFont : null
        }
    } );
</script>

<script src="https://cdn.ckeditor.com/4.7.3/full-all/ckeditor.js"></script>

<textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>
</code>```

with JS like:

```<code>CKEDITOR.replace( 'editor1', {
    extraPlugins: 'mathjax',
    mathJaxLib: '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=AM_HTMLorMML'
} );
</code>```

Body:
As math formulas are rendered directly by MathJax plugin, you should check how to change font for MathJax itself (see MathJax docs on Font Support).

There is already an answer covering this here - https://stackoverflow.com/a/41475014/646871.

Remember to include proper MathJax config on the same page were CKEditor is used, like:

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        "HTML-CSS" : {
            availableFonts : ["STIX"],
            preferredFont : "STIX",
            webFont : "STIX-Web",
            imageFont : null
        }
    } );
</script>

<script src="https://cdn.ckeditor.com/4.7.3/full-all/ckeditor.js"></script>

<textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>

with JS like:

CKEDITOR.replace( 'editor1', {
    extraPlugins: 'mathjax',
    mathJaxLib: '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=AM_HTMLorMML'
} );


问:
Microsoft Bot Framework WebChat: Add bot image
How to add image of the bot with some welcome text in the middle in Microsoft Bot Framework Web Chat. Seems like quite common functionality and I see images which indicates that is possible.

Anyone knows how to add it?

答:
you can use the below code and replace your image path to give response from bot to user including text and image.

```<code>await context.PostAsync("Here we go with the welcome message\n"+"![AN IMAGE!](Your_Image_URL)");
</code>```

Another way is, you can also use Card functionality:

```<code>private async Task Greeting(IDialogContext context, IAwaitable<IMessageActivity> argument)
        {
            var message = await argument;
            if (string.IsNullOrEmpty(message.Text))
            {

                // Hero Card
                var cardMsg = context.MakeMessage();
                var attachment = BotWelcomeCard("Hello,I am a bot.", "");
                cardMsg.Attachments.Add(attachment);
                await context.PostAsync(cardMsg);

            }
            else
            {
               // else code
            }
        }

 private static Attachment BotWelcomeCard(string responseFromQNAMaker, string userQuery)
        {
            var heroCard = new HeroCard
            {
                Title = userQuery,
                Subtitle = "",
                Text = responseFromQNAMaker,
                Images = new List<CardImage> { new CardImage("../img/bot.gif") },
                Buttons = new List<CardAction> { new CardAction(ActionTypes.ImBack, "Show Menu", value: "Show Bot Menu") }
            };

            return heroCard.ToAttachment();
        }
</code>```

Body:
you can use the below code and replace your image path to give response from bot to user including text and image.

await context.PostAsync("Here we go with the welcome message\n"+"![AN IMAGE!](Your_Image_URL)");

Another way is, you can also use Card functionality:

private async Task Greeting(IDialogContext context, IAwaitable<IMessageActivity> argument)
        {
            var message = await argument;
            if (string.IsNullOrEmpty(message.Text))
            {

                // Hero Card
                var cardMsg = context.MakeMessage();
                var attachment = BotWelcomeCard("Hello,I am a bot.", "");
                cardMsg.Attachments.Add(attachment);
                await context.PostAsync(cardMsg);

            }
            else
            {
               // else code
            }
        }

 private static Attachment BotWelcomeCard(string responseFromQNAMaker, string userQuery)
        {
            var heroCard = new HeroCard
            {
                Title = userQuery,
                Subtitle = "",
                Text = responseFromQNAMaker,
                Images = new List<CardImage> { new CardImage("../img/bot.gif") },
                Buttons = new List<CardAction> { new CardAction(ActionTypes.ImBack, "Show Menu", value: "Show Bot Menu") }
            };

            return heroCard.ToAttachment();
        }


问:
jQuery show hide parent item on click by class
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

```<code><div class="list-item">
    <div class="list-content">
        <div class="list-updates">
            <a href="#" class="list-avatar"><img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40"></a>
            <a href="#"><i class="material-icons"><?php echo get_icon( $update[ $i ] ) ?></i></a>
        </div>
        <div class="item-title"><a href="#"><?php echo $questions[ $i ] ?></a>
        </div>
        <div class="ans-box">
            <div class="ans-count"><?php echo $ans[ $i ] ?></div>
            <span><i class="material-icons meta-info-btn">keyboard_arrow_down</i></span>
        </div>
    </div>

    <div class="metas">
        <div class="update-info"><a href="#">commented</a> 1 hour ago in <a href="#">Plugins</a> by
            <a href="#">gurjyot</a>
        </div>
        <div class="counters">
            <span class="votes"><i class="material-icons">arrow_upward</i> +1245</span>
            <span class="views"><i class="material-icons">remove_red_eye</i> 50.2k</span>
        </div>
    </div>
</div><!-- list-item -->

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});
</code>```

答:
you do seperate click events for .meta-info-btn and .list-content as below</p>

```<code>    $('.meta-info-btn').click(function () {
        $(this).closest('.list-content').closest('.metas').slideToggle();
    });

    $('.list-content').click(function () {

        $(this).closest('.metas').slideToggle();
    });
</code>```

Body:
I am having trouble to toggle (show/hide) div based on button clicked to the list item.

When I tried, it affects to all divs at once. Here is my code. I want toggole per item bases.

            <img
                        src="images/avatar/avatar_<?php echo ( $i <= 8 ? '0' : NULL ) . $avatars[ $i ] ?>.jpg"
                        alt="user-avatar" width="40"
                        height="40">
            <?php echo get_icon( $update[ $i ] ) ?>

<?php echo $questions[ $i ] ?>

<?php echo $ans[ $i ] ?>

            keyboard_arrow_down

commented 1 hour ago in Plugins by
            gurjyot

            arrow_upward +1245
            remove_red_eye 50.2k

$('.list-content .meta-info-btn').click(function () {
    alert('Clicked and found!');
    $(this).closest('.metas').slideToggle();
});

Body:
you do seperate click events for .meta-info-btn and .list-content as below

    $('.meta-info-btn').click(function () {
        $(this).closest('.list-content').closest('.metas').slideToggle();
    });

    $('.list-content').click(function () {

        $(this).closest('.metas').slideToggle();
    });


答:
Remove class from all .payment and add class for current element:

$(".payment").on("click", function() {
    $(".payment").removeClass("selected");
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
background: #eaeaea;
}</code>```

 <input type="radio" name="myRadio"/> example

 <input type="radio" name="myRadio"/> of my

 <input type="radio" name="myRadio"/> problem

```

Title: jQuery doesn't removing class before .each function

Body:
I got small problem with my script.

The script looks like it works, but each time it adds the selected class. It resets it before the onclick, but the class does not remove it. What could be a problem?

Only one element of the .payment class from the collection should have a .selected class

$(".payment").each(function() {
    $(".payment").removeClass("selected");
    $(this).on("click", function() {
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true);
   });
});

.selected {
background: #eaeaea;
}

 <input type="radio" /> example

 <input type="radio" /> of my

 <input type="radio" /> problem

Body:
Remove class from all .payment and add class for current element:

$(".payment").on("click", function() {
    $(".payment").removeClass("selected");
    $(this).addClass("selected");
    $(this).find('input[type="radio"]').prop("checked", true)
});

.selected {
background: #eaeaea;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="payment">
 <input type="radio" name="myRadio"/> example
</div>

<div class="payment">
 <input type="radio" name="myRadio"/> of my
</div>

<div class="payment">
 <input type="radio" name="myRadio"/> problem
</div>


问:
Forward slash in assetTitle causes error
While testing (on real device) AVAssetDownloadURLSession I noticed when I put slash "/" into assetTitle as result I receive error:

```<code>Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo={NSLocalizedDescription=The operation could
not be completed, NSLocalizedFailureReason=An unknown error occurred
(-12780)}
</code>```

Example code:

```<code>AVAssetDownloadTask * assetDownloadTask = [urlSession
assetDownloadTaskWithURLAsset:urlAsset assetTitle:@"One two three
(open/close)" assetArtworkData:nil options:nil];
</code>```

From Apple's documentation (https://developer.apple.com/documentation/avfoundation/avassetdownloadurlsession/1650938-assetdownloadtaskwithurlasset):

```<code>title
A human readable title for this asset in the user's preferred language.
This value will be displayed in the usage pane of the Settings app.
</code>```

I think above example is quite human readable. Do I need to treat slash as a special character and escape it somehow to assign it properly?

答:
Yes currently I need to do this on my titles:</p>

```<code> NSCharacterSet *setToRemove = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "];
 NSCharacterSet *setToKeep = [setToRemove invertedSet];
 NSString *downloadTitle = [[[item getTitle] componentsSeparatedByCharactersInSet:setToKeep] componentsJoinedByString:@""];
</code>```

Body:
While testing (on real device) AVAssetDownloadURLSession I noticed when I put slash "/" into assetTitle as result I receive error:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo={NSLocalizedDescription=The operation could
not be completed, NSLocalizedFailureReason=An unknown error occurred
(-12780)}

Example code:

AVAssetDownloadTask * assetDownloadTask = [urlSession
assetDownloadTaskWithURLAsset:urlAsset assetTitle:@"One two three
(open/close)" assetArtworkData:nil options:nil];

From Apple's documentation (https://developer.apple.com/documentation/avfoundation/avassetdownloadurlsession/1650938-assetdownloadtaskwithurlasset):

title
A human readable title for this asset in the user's preferred language.
This value will be displayed in the usage pane of the Settings app.

I think above example is quite human readable. Do I need to treat slash as a special character and escape it somehow to assign it properly?

Body:
Yes currently I need to do this on my titles:

 NSCharacterSet *setToRemove = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "];
 NSCharacterSet *setToKeep = [setToRemove invertedSet];
 NSString *downloadTitle = [[[item getTitle] componentsSeparatedByCharactersInSet:setToKeep] componentsJoinedByString:@""];


问:
Reactjs POST request through axios
Hi i am trying reactjs POST request through axios but getting error, I went through all docs but error is not solved.

Here is my error:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (eval at  (bundle.js:4621), :15:15)
    at settle (eval at  (bundle.js:4615), :18:12)
    at XMLHttpRequest.handleLoad (eval at  (bundle.js:4609), :77:7)

Here is my Reactjs code:

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />

     </div>
         </form>

   );
 }

}
</code>```

答:
There is no need of sending form data

```<code>var data = new FormData();
</code>```

Just pass json to via axios ,

```<code>axios('http://localhost:8083/students',{
   method: 'POST',
   data : payload,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
})
</code>```

Simple way to do :

```<code>axios.post('http://localhost:8083/students',payload).then(...)
</code>```

Title: Reactjs POST request through axios

Body:
Hi i am trying reactjs POST request through axios but getting error, I went through all docs but error is not solved.

Here is my error:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (eval at  (bundle.js:4621), :15:15)
    at settle (eval at  (bundle.js:4615), :18:12)
    at XMLHttpRequest.handleLoad (eval at  (bundle.js:4609), :77:7)

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}

handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>

     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />

     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />

     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />

     <input type="submit" />

         </form>

   );
 }

}

Body:
There is no need of sending form data

var data = new FormData();

Just pass json to via axios ,

axios('http://localhost:8083/students',{
   method: 'POST',
   data : payload,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
})

Simple way to do :

axios.post('http://localhost:8083/students',payload).then(...)