问:
Spatial network based on maximum distance in ggplot2
I would like to plot network matrix of regions in ggplot - I know that for ggplot we need data.frame in tidy format in order to plot it.

I am able to plot network based on number of neighbours in ggplot however when I need spatial network based on maximum distance I get an error when creating data frame for ggplot.

I provided example down bellow:

```<code>library(ggplot2)
library(sf)
library(spdep)

# Polygon data
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_DEU_1_sp.rds"
data <- readRDS(url(URL))

CORD <- rbind(
  coordinates(data)
)
rownames(CORD) <- NULL

# Spatial Network based on number of neighbours
cns <- knearneigh(CORD, k = 5, longlat=T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cS <- nb2listw(scnsn)

data_df <- data.frame(CORD)
colnames(data_df) <- c("long", "lat")

# Creating dataframe  from spatail network (neiresth neighbours) for ggplot plot
n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS$neighbours,length)),
  to = unlist(cS$neighbours),
  weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

# ggplot of spatial network
ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "red", fill = FALSE) +
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "royalblue") +
  coord_map()

### Another type of network matrix - Maximum distance

nb200km <- dnearneigh(CORD, d1=0, d2=100, longlat=T)
summary(nb200km)
cS_distance <- nb2listw(nb200km, zero.policy = T)

# I need to recreate this plot in ggplot
plot(data)
plot(W, coordinates(data), add = T)

data_df <- data.frame(CORD)
colnames(data_df) <- c("long", "lat")

n = length(attributes(cS_distance$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS_distance$neighboaurs,length)),
  to = unlist(cS_distance$neighbours),
  weight = unlist(cS_distance$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")
</code>```

creating dataframe from cS object works, however creating a dataframe from cS_distance object returns an error.

I would like to ask how to solve the error and plot distance spatial network in ggplot.

答:
I'm not sure if this is what you're looking for, but the problem seems to be that you have some regions with no neighbours in cS_distance, so DA$to contains some zero values. This means when you do data_df[DA$from,] it has more rows than data_df[DA$to,], and your code throws an error when you try to cbind them.

If you filter out the rows where DA$to is zero, you get this:

```<code>n = length(attributes(cS_distance$neighbours)$region.id)
from <- rep(1:n,sapply(cS_distance$neighbours,length))
to <- unlist(cS_distance$neighbours)[]
weight <- numeric(length(to))
weight[which(to != 0)] <- unlist(cS_distance$weights)
DA = data.frame(from = from, to = to, weight = weight)
DA <- DA[DA$to != 0,]
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])

colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

# ggplot of spatial network
ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "red", fill = NA) +
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "royalblue") +
  coord_map()
</code>```

Body:
I would like to plot network matrix of regions in ggplot - I know that for ggplot we need data.frame in tidy format in order to plot it.

I am able to plot network based on number of neighbours in ggplot however when I need spatial network based on maximum distance I get an error when creating data frame for ggplot.

I provided example down bellow:

library(ggplot2)
library(sf)
library(spdep)

# Polygon data
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_DEU_1_sp.rds"
data <- readRDS(url(URL))

CORD <- rbind(
  coordinates(data)
)
rownames(CORD) <- NULL

# Spatial Network based on number of neighbours
cns <- knearneigh(CORD, k = 5, longlat=T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cS <- nb2listw(scnsn)

data_df <- data.frame(CORD)
colnames(data_df) <- c("long", "lat")

# Creating dataframe  from spatail network (neiresth neighbours) for ggplot plot
n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS$neighbours,length)),
  to = unlist(cS$neighbours),
  weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

# ggplot of spatial network
ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "red", fill = FALSE) +
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "royalblue") +
  coord_map()

### Another type of network matrix - Maximum distance

nb200km <- dnearneigh(CORD, d1=0, d2=100, longlat=T)
summary(nb200km)
cS_distance <- nb2listw(nb200km, zero.policy = T)

# I need to recreate this plot in ggplot
plot(data)
plot(W, coordinates(data), add = T)

data_df <- data.frame(CORD)
colnames(data_df) <- c("long", "lat")

n = length(attributes(cS_distance$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS_distance$neighboaurs,length)),
  to = unlist(cS_distance$neighbours),
  weight = unlist(cS_distance$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

creating dataframe from cS object works, however creating a dataframe from cS_distance object returns an error.

I would like to ask how to solve the error and plot distance spatial network in ggplot.

Body:
I'm not sure if this is what you're looking for, but the problem seems to be that you have some regions with no neighbours in cS_distance, so DA$to contains some zero values. This means when you do data_df[DA$from,] it has more rows than data_df[DA$to,], and your code throws an error when you try to cbind them.

If you filter out the rows where DA$to is zero, you get this:

n = length(attributes(cS_distance$neighbours)$region.id)
from <- rep(1:n,sapply(cS_distance$neighbours,length))
to <- unlist(cS_distance$neighbours)[]
weight <- numeric(length(to))
weight[which(to != 0)] <- unlist(cS_distance$weights)
DA = data.frame(from = from, to = to, weight = weight)
DA <- DA[DA$to != 0,]
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])

colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

# ggplot of spatial network
ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "red", fill = NA) +
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5, color = "royalblue") +
  coord_map()


来源: stackexchange

问:
Regex with multiple square brackets
I'm working with some transcriptions and I've struggled with their normalization. Some of them have square brackets within other square brackets to specify the different noises / sound events that can be found when listening to the corresponding audio file. This is an example of one file's line:

```<code>U012_W038 [other_speech_adult: [laughter] yeah you can you can read [undefined] tomorrow] [other_speech_adult: are you recording me now] this is annoying eh [noise] [noise_bkgspeech/]
</code>```

In every line the format corresponds to

```<code><audio file reference> <transcription>
</code>```

My ideal output would be:

Get the text that is not enclosed by any square brackets: e.g: "this is annoying eh"

Extract the text that's inside of square brackets only if ":" is found. The text to catch would be the one after the colon. e.g: yeah you can you can read

The output should look something similar to this:

```<code>U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh
</code>```

I tried to solve this problem using sed, but I wouldn't mind trying perl or any other text processing tool. My closest attempt so far is:

```<code>sed 's/\[[^]]*]//g'
</code>```

Do you think there's a way to solve this out by coding or it's to be by a manual checking?

Thanks in advance!

ContentLicense: CC BY-SA 4.0

Title: Regex with multiple square brackets

Body:
I'm working with some transcriptions and I've struggled with their normalization. Some of them have square brackets within other square brackets to specify the different noises / sound events that can be found when listening to the corresponding audio file. This is an example of one file's line:

U012_W038 [other_speech_adult: [laughter] yeah you can you can read [undefined] tomorrow] [other_speech_adult: are you recording me now] this is annoying eh [noise] [noise_bkgspeech/]

In every line the format corresponds to

<audio file reference> <transcription>

My ideal output would be:

Get the text that is not enclosed by any square brackets: e.g: "this is annoying eh"

Extract the text that's inside of square brackets only if ":" is found. The text to catch would be the one after the colon. e.g: yeah you can you can read

The output should look something similar to this:

U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh

I tried to solve this problem using sed, but I wouldn't mind trying perl or any other text processing tool. My closest attempt so far is:

sed 's/\[[^]]*]//g'

Do you think there's a way to solve this out by coding or it's to be by a manual checking?

Thanks in advance!

Body:
This version

perl -pe 's/\[[^]:]+\]//g;s/\[[^]:]*:([^]:]+)*\]/\1/g;s/ +/ /g' file

detects non-paired brackets.


问:
Julia - dataframe - How to force cast as a vector/multiple line value a scalar results using by()
Long and winding road, exploring DataFrames.jl and one more question.

I am trying to force cast a function returning a scalar to map back to the entire vector.
I am not sure this is entirely clear so let me exemplify :

Lets say I am running the following  (and now canonical) example

```<code>df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100));
by(df, :grp,result= (:x) => (x) -> sum(x))
</code>```

```<code>2×2 DataFrame
│ Row │ grp    │ result  │
│     │ String │ Float64 │
├─────┼────────┼─────────┤
│ 1   │ b      │ 30.431  │
│ 2   │ a      │ 19.9667 │
</code>```

I get the sum of x, for each of the group. All good. But for some reason I want to have this sum of each group casted for each of the line in the dataset

I found the following hack

```<code>by(df, :grp,result= (:x) => (x) -> x.-x.+sum(x))
</code>```

Giving exactly what I expect

```<code>│ Row │ grp    │ result  │
│     │ String │ Float64 │
├─────┼────────┼─────────┤
│ 1   │ b      │ 30.431  │
│ 2   │ b      │ 30.431  │
│ 3   │ b      │ 30.431  │
⋮
│ 98  │ a      │ 19.9667 │
│ 99  │ a      │ 19.9667 │
│ 100 │ a      │ 19.9667 │
</code>```

Now, I essentially force a vector aspect in the function to make it happen, (I also do it in the most inelegant way).

My question is : Is there with by() a correct/nicer way to force a function returning a scalar to map back to the original vector ?

In my opinion this would be very helpful and also help to address the following situations.

```<code>by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> mean(x)) # works returns 2 lines
by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> x.-5) # doesnt work (scalar vs vector)
by(df, :grp,result= (:x) => (x) -> x.-x.+sum(x),result2= (:x) => (x) -> x.-5) # works returns 100 lines
</code>```

I am sure I am missing something any help would be great.

答:
Currently by does not make restrictions on the number of rows a transforming function should return. The only restriction is that if there are multiple functions passed they must return the same number of rows.

Here is what you could alternatively do:

```<code>by(df, :grp,result= :x => x -> fill(sum(x), length(x)))
</code>```

A general approach you can use, which is a bit slower, but more flexible is to use by in the following way (I am rewriting your example by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> x.-5) that does not work):

```<code>by(df, :grp) do sdf
    DataFrame(result = sum(sdf.x), result2 = sdf.x .- 5)
end
</code>```

Here you are passing a whole SubDataFrame to a grouping function and use the implicit broadcasting functionality of DataFrame constructor.

Your specific example also could be written as:

```<code>by(df, :grp, :x => x -> DataFrame(result = sum(x), result2 = x .- 5))
</code>```

which is a specific solution using the fact that in both generated columns you use the same column from source data frame for computations.

Body:
Long and winding road, exploring DataFrames.jl and one more question.

I am trying to force cast a function returning a scalar to map back to the entire vector.
I am not sure this is entirely clear so let me exemplify :

Lets say I am running the following  (and now canonical) example

df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100));
by(df, :grp,result= (:x) => (x) -> sum(x))

2×2 DataFrame
│ Row │ grp    │ result  │
│     │ String │ Float64 │
├─────┼────────┼─────────┤
│ 1   │ b      │ 30.431  │
│ 2   │ a      │ 19.9667 │

I get the sum of x, for each of the group. All good. But for some reason I want to have this sum of each group casted for each of the line in the dataset

I found the following hack

by(df, :grp,result= (:x) => (x) -> x.-x.+sum(x))

Giving exactly what I expect

│ Row │ grp    │ result  │
│     │ String │ Float64 │
├─────┼────────┼─────────┤
│ 1   │ b      │ 30.431  │
│ 2   │ b      │ 30.431  │
│ 3   │ b      │ 30.431  │
⋮
│ 98  │ a      │ 19.9667 │
│ 99  │ a      │ 19.9667 │
│ 100 │ a      │ 19.9667 │

Now, I essentially force a vector aspect in the function to make it happen, (I also do it in the most inelegant way).

My question is : Is there with by() a correct/nicer way to force a function returning a scalar to map back to the original vector ?

In my opinion this would be very helpful and also help to address the following situations.

by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> mean(x)) # works returns 2 lines
by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> x.-5) # doesnt work (scalar vs vector)
by(df, :grp,result= (:x) => (x) -> x.-x.+sum(x),result2= (:x) => (x) -> x.-5) # works returns 100 lines

I am sure I am missing something any help would be great.

Body:
Currently by does not make restrictions on the number of rows a transforming function should return. The only restriction is that if there are multiple functions passed they must return the same number of rows.

Here is what you could alternatively do:

by(df, :grp,result= :x => x -> fill(sum(x), length(x)))

A general approach you can use, which is a bit slower, but more flexible is to use by in the following way (I am rewriting your example by(df, :grp,result= (:x) => (x) -> sum(x),result2= (:x) => (x) -> x.-5) that does not work):

by(df, :grp) do sdf
    DataFrame(result = sum(sdf.x), result2 = sdf.x .- 5)
end

Here you are passing a whole SubDataFrame to a grouping function and use the implicit broadcasting functionality of DataFrame constructor.

Your specific example also could be written as:

by(df, :grp, :x => x -> DataFrame(result = sum(x), result2 = x .- 5))

which is a specific solution using the fact that in both generated columns you use the same column from source data frame for computations.


问:
jpa hibernate one-to-many bidirectional
I have an issue with one of my One-To-Many relationships.
My problem is when I add a Tenant into an Apartment it doesn't set the column value in the Tenant to the ApartmentID. The thing is I have the exact same relationship with other classes and they are working fine... Does anyone have an idea why it's not wotking?
Thanks

Apartment :

```<code>@Entity
public class Apartment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ApartmentID",unique = true, nullable = false)
    public int apartmentID;

    @OneToMany(mappedBy = "apartment", cascade = CascadeType.ALL)
    private List<Tenant> tenants;
}
</code>```

Tenant :

```<code>@Entity
public class Tenant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="TenantID",unique = true, nullable = false)
    public int tenantID;

    @ManyToOne
    @JoinColumn(name = "ApartmentID")
    private Apartment apartment;
}
</code>```

答:
```<code>**please refer the example you will get an idea**

--------------------------------------------------------

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private List<Address> addresses;
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String street;
    private int houseNumber;
    private String city;
    private int zipCode;
    @ManyToOne(fetch = FetchType.LAZY)
    private Person person;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: jpa hibernate one-to-many bidirectional

Body:
I have an issue with one of my One-To-Many relationships.
My problem is when I add a Tenant into an Apartment it doesn't set the column value in the Tenant to the ApartmentID. The thing is I have the exact same relationship with other classes and they are working fine... Does anyone have an idea why it's not wotking?
Thanks

Apartment :

@Entity
public class Apartment {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ApartmentID",unique = true, nullable = false)
    public int apartmentID;

    @OneToMany(mappedBy = "apartment", cascade = CascadeType.ALL)
    private List<Tenant> tenants;
}

Tenant :

@Entity
public class Tenant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="TenantID",unique = true, nullable = false)
    public int tenantID;

    @ManyToOne
    @JoinColumn(name = "ApartmentID")
    private Apartment apartment;
}


问:
How to sort a mysql table in a specific way
I have the following table as a result of a query:

```<code>    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;
</code>```

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
</code>```

The table is sorted by

```<code>ORDER BY fullpath ASC, name ASC
</code>```

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
</code>```

答:
If you have MySql 8.0 or greater than:

```<code>WITH RECURSIVE folders_path (id, name, path) AS
(
  SELECT id, name, name as path
    FROM folders
    WHERE parent_id IS NULL
  UNION ALL
  SELECT f.id, f.name, CONCAT(fp.path, '/', f.name)
    FROM folders_path fp JOIN folders AS f
      ON fp.id = f.parent_id
)
SELECT f.id, f.parent_id, f.name, fp.path
    FROM folders f JOIN folders_path fp on f.id = fp.id
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fp.path;
</code>```

See DB Fiddle

Note: In the above DB Fiddle I did not bother to add the fullpath column since as the sample data added already satisfied the WHERE clause.

Body:
I have the following table as a result of a query:

    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4

The table is sorted by

ORDER BY fullpath ASC, name ASC

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s

Body:
If you have MySql 8.0 or greater than:

WITH RECURSIVE folders_path (id, name, path) AS
(
  SELECT id, name, name as path
    FROM folders
    WHERE parent_id IS NULL
  UNION ALL
  SELECT f.id, f.name, CONCAT(fp.path, '/', f.name)
    FROM folders_path fp JOIN folders AS f
      ON fp.id = f.parent_id
)
SELECT f.id, f.parent_id, f.name, fp.path
    FROM folders f JOIN folders_path fp on f.id = fp.id
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fp.path;

See DB Fiddle

Note: In the above DB Fiddle I did not bother to add the fullpath column since as the sample data added already satisfied the WHERE clause.


问:
How to get value of translateX and translateY?
I want to get translateY value from the in-line css with the JavaScript.

Here is the in-line value:

```<code>style ="transition-property: transform; transform-origin: 0px 0px 0px; transform: translate(0px, -13361.5px) scale(1) translateZ(0px);"
</code>```

These code give to me the total list in to variable:

```<code>var tabletParent = document.getElementById("scroller");
var toTop = tabletParent.style.transform;
console.log(toTop);
</code>```

console.log

```<code>translate(0px, -12358.8px) scale(1) translateZ(0px)
</code>```

Expecting toTop as -12358.8px.

答:
You may have to work out x and y of  .slice(x,y)  if you have more than one translate property</p>

```<code>  const trsString = element.style.transform; //eg "translateY(36px)"
  let num = trsString.slice(11, trsString.length - 3)
  num = num.length == 0 ? 0 : parseInt(num) // will be 36
</code>```

Body:
I want to get translateY value from the in-line css with the JavaScript.

Here is the in-line value:

style ="transition-property: transform; transform-origin: 0px 0px 0px; transform: translate(0px, -13361.5px) scale(1) translateZ(0px);"

These code give to me the total list in to variable:

var tabletParent = document.getElementById("scroller");
var toTop = tabletParent.style.transform;
console.log(toTop);

console.log

translate(0px, -12358.8px) scale(1) translateZ(0px)

Expecting toTop as -12358.8px.

Body:
You may have to work out x and y of  .slice(x,y)  if you have more than one translate property

  const trsString = element.style.transform; //eg "translateY(36px)"
  let num = trsString.slice(11, trsString.length - 3)
  num = num.length == 0 ? 0 : parseInt(num) // will be 36


问:
How do I change arraylist of ids into arraylist of other column values SQLite?
I have a backend-filtered Arraylist of Students Ids which I display in a listview. Instead of Ids I want to write the names which are stored in another table. Right now I filter the Ids like this:

```<code>public Cursor getAllSlots(String TimeId) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_SLOTS + " WHERE timeid = '" + TimeId +"'", null);
    return res;
}
</code>```

Then I use this to display the Student IDs I got back from my database like so:

```<code>Cursor cursormo = myDb.getAllSlots(TimeId);
while(cursormo.moveToNext()){
                    HashMap<String, String> resultMap = new HashMap<>();
                    resultMap.put("Name", cursormo.getString(1));
                    listItems.add(resultMap);
                    arrayListStudentsTime.add(cursormo.getString(1));
                }
</code>```

And now I need to get the names of the Student IDs from another table. So I tried to transfer the Arraylist "arrayListStudentsTime" to my database and try this:

```<code>public Cursor getNamesbyIDs(ArrayList StudentIds) {
    Log.d("CREATION", "getNamebyID() called");
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);
    return res;
}
</code>```

But it doesn't work... Does anybody have an idea? Thanks in advance!!

答:
change this:

```<code>Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);
</code>```

to:

```<code>String commaSeperatedIds= String.join(",", StudentIds);

Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id in (" + commaSeperatedIds+")", null);
</code>```

Body:
I have a backend-filtered Arraylist of Students Ids which I display in a listview. Instead of Ids I want to write the names which are stored in another table. Right now I filter the Ids like this:

public Cursor getAllSlots(String TimeId) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_SLOTS + " WHERE timeid = '" + TimeId +"'", null);
    return res;
}

Then I use this to display the Student IDs I got back from my database like so:

Cursor cursormo = myDb.getAllSlots(TimeId);
while(cursormo.moveToNext()){
                    HashMap<String, String> resultMap = new HashMap<>();
                    resultMap.put("Name", cursormo.getString(1));
                    listItems.add(resultMap);
                    arrayListStudentsTime.add(cursormo.getString(1));
                }

And now I need to get the names of the Student IDs from another table. So I tried to transfer the Arraylist "arrayListStudentsTime" to my database and try this:

public Cursor getNamesbyIDs(ArrayList StudentIds) {
    Log.d("CREATION", "getNamebyID() called");
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);
    return res;
}

But it doesn't work... Does anybody have an idea? Thanks in advance!!

Body:
change this:

Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id = '" + StudentIds +"'", null);

to:

String commaSeperatedIds= String.join(",", StudentIds);

Cursor res = db.rawQuery("select * from " + TABLE_NAME + " WHERE id in (" + commaSeperatedIds+")", null);


问:
How to fix "Detailed Accuracy By Class"? It displays question marks
Trainingsset: https://www.dropbox.com/s/ohc48uo2169zdi0/200214%20AlleJaren2012-2020%20THUISv1.arff?dl=0
Testset: https://www.dropbox.com/s/5tkhbyevf6msvce/200214%20Testbestand%20ATP%20Rotterdam.arff?dl=0

Hi everybody,

Can someone tell me what I'm doing wrong with those .arff-files? What is the reason that the output gives question marks instead of figures?

Thanks in advance,

Regards,

Cor

答:
In your test set, you do not have a winner.  So, you only have predictions of the winner, but "?" for the actuals.

Some options:
1. Just analyze the training set, but let Weka do a training / test split, so you can get a measure of accuracy.
2. Just analyze the training set, but let Weka do 10-fold crossvalidation.

Here's what I get using J48 with standard parameters and 10-fold crossvalidation:

```<code>Number of Leaves  :     1915

Size of the tree :  1992

Time taken to build model: 2.47 seconds

=== Stratified cross-validation ===
=== Summary ===

Correctly Classified Instances       14504               64.1543 %
Incorrectly Classified Instances      8104               35.8457 %
Kappa statistic                          0.2832
Mean absolute error                      0.444
Root mean squared error                  0.477
Relative absolute error                 88.7915 %
Root relative squared error             95.3947 %
Total Number of Instances            22608

=== Detailed Accuracy By Class ===

                 TP Rate  FP Rate  Precision  Recall   F-Measure  MCC      ROC Area  PRC Area  Class
                 0.672    0.389    0.632      0.672    0.651      0.284    0.679     0.654     0
                 0.611    0.328    0.652      0.611    0.631      0.284    0.679     0.643     1
Weighted Avg.    0.642    0.358    0.642      0.642    0.641      0.284    0.679     0.649

=== Confusion Matrix ===

    a    b   <-- classified as
 7572 3694 |    a = 0
 4410 6932 |    b = 1
</code>```

I'm not saying that's a good model; I'm just using that as an illustration.

Body:
In your test set, you do not have a winner.  So, you only have predictions of the winner, but "?" for the actuals.

Some options:
1. Just analyze the training set, but let Weka do a training / test split, so you can get a measure of accuracy.
2. Just analyze the training set, but let Weka do 10-fold crossvalidation.

Here's what I get using J48 with standard parameters and 10-fold crossvalidation:

Number of Leaves  :     1915

Size of the tree :  1992

Time taken to build model: 2.47 seconds

=== Stratified cross-validation ===
=== Summary ===

Correctly Classified Instances       14504               64.1543 %
Incorrectly Classified Instances      8104               35.8457 %
Kappa statistic                          0.2832
Mean absolute error                      0.444
Root mean squared error                  0.477
Relative absolute error                 88.7915 %
Root relative squared error             95.3947 %
Total Number of Instances            22608

=== Detailed Accuracy By Class ===

                 TP Rate  FP Rate  Precision  Recall   F-Measure  MCC      ROC Area  PRC Area  Class
                 0.672    0.389    0.632      0.672    0.651      0.284    0.679     0.654     0
                 0.611    0.328    0.652      0.611    0.631      0.284    0.679     0.643     1
Weighted Avg.    0.642    0.358    0.642      0.642    0.641      0.284    0.679     0.649

=== Confusion Matrix ===

    a    b   <-- classified as
 7572 3694 |    a = 0
 4410 6932 |    b = 1

I'm not saying that's a good model; I'm just using that as an illustration.


问:
Meaning of clock icon in VS Code source control
What does it mean when a blue clock icon is displayed over the VS Code source control icon? When I run the git status command, I get the message: "nothing to commit, working tree clean." I checked the VS Studio documentation, but I couldn't find anything on this topic.

答:
The way I fixed this was to rename my existing git project and clone a new copy from GitHub. Then I used a compare utility (WinMerge in my case) to compare old broken project vs new cloned project. I moved changes from old to new slowly and updated GitHub with commits & pushes frequently.

At one point, I moved over a recently created temp directory tree with thousands of files and the new project became borked just like the old. As I didn't want the temp files in git anyway, I updated my .gitignore files properly and the problem was resolved.

In my case, the problem was way too many untracked files.


问:
Calling a function out of several other functions?
So I have several functions written and I want to call one of them for use, my input code I used at the bottom asks for the function name but doesn't do much of anything with it. I'm a newbie so I might have missed something here, thanks.</p>

```<code>    def summ(num1 = 0, num2 = 0):
        num1 = int(input('första num: '))
        num2 = int(input('andra num: '))
        total = num1 + num2
        print(total)
        return num1 + num2

    def kvad(num = 0):
        num = int(input('kvadrerat nummer..'))
        power = num**2
        print(power)
        return power

    def udda(udd = 0):
        udd = int(input('jämnt eller udda?'))
        if udd % 2 != 0:
                print('Udda..')
        elif udd % 2:
            print('jämnt')
        return udda

    import operator
    def kalkylera(num1 = 0, num2 = 0):

        num1 = int(input('first num'))
        num2 = int(input('second num'))
        #operators
        subb = operator.sub(num1, num2)
        addd = operator.add(num1,num2)
        mull = operator.mul(num1,num2)
        divv = operator.truediv(num1,num2)

        oper8 = input('Vilket operation ska tillämpas?')
        if oper8 == '-':
            print(subb)
        elif oper8 == '+':
            print(addd)
        elif oper8 == '*':
            print(mull)
        elif oper8 == '/':
            print(divv)

call = input('vilket funktion?')

if call == summ:
    summ()
elif call == kvad:
    kvad()
elif call == udda:
    udda()
elif call == kalkylera:
    kalkylera()
</code>```

答:
```<code>functions = {
    "summ": summ,
    "kvad": kvad,
    "udda": udda,
    "kalkylera": kalkylera,
}
call = input('vilket funktion?')

function = functions.get(call)
if function is None:
    raise RuntimeError('Unknown function to call')
function()
</code>```

This is a more explicit approach. It also allows you to specify a different code name for each function.

Alternatively you could use:

```<code>function = globals().get(call)
</code>```

But this smells. Explicit is better than implicit (Zen of Python).

Body:
So I have several functions written and I want to call one of them for use, my input code I used at the bottom asks for the function name but doesn't do much of anything with it. I'm a newbie so I might have missed something here, thanks.

    def summ(num1 = 0, num2 = 0):
        num1 = int(input('första num: '))
        num2 = int(input('andra num: '))
        total = num1 + num2
        print(total)
        return num1 + num2

    def kvad(num = 0):
        num = int(input('kvadrerat nummer..'))
        power = num**2
        print(power)
        return power

    def udda(udd = 0):
        udd = int(input('jämnt eller udda?'))
        if udd % 2 != 0:
                print('Udda..')
        elif udd % 2:
            print('jämnt')
        return udda

    import operator
    def kalkylera(num1 = 0, num2 = 0):

        num1 = int(input('first num'))
        num2 = int(input('second num'))
        #operators
        subb = operator.sub(num1, num2)
        addd = operator.add(num1,num2)
        mull = operator.mul(num1,num2)
        divv = operator.truediv(num1,num2)

        oper8 = input('Vilket operation ska tillämpas?')
        if oper8 == '-':
            print(subb)
        elif oper8 == '+':
            print(addd)
        elif oper8 == '*':
            print(mull)
        elif oper8 == '/':
            print(divv)

call = input('vilket funktion?')

if call == summ:
    summ()
elif call == kvad:
    kvad()
elif call == udda:
    udda()
elif call == kalkylera:
    kalkylera()

Body:
functions = {
    "summ": summ,
    "kvad": kvad,
    "udda": udda,
    "kalkylera": kalkylera,
}
call = input('vilket funktion?')

function = functions.get(call)
if function is None:
    raise RuntimeError('Unknown function to call')
function()

This is a more explicit approach. It also allows you to specify a different code name for each function.

Alternatively you could use:

function = globals().get(call)

But this smells. Explicit is better than implicit (Zen of Python).


问:
When t run my code with @test annotation, my code returns following error message
```<code>[RemoteTestNG] detected TestNG version 7.0.1
</code>```

Exception in thread "main" java.lang.NoClassDefFoundError:
  com/google/inject/Stage

答:
There is an open issue that is tracking this discrepancy.

See here: https://github.com/cbeust/testng/issues/2223

As an alternate, what you can consider doing is, to switch over to using IntelliJ because this problem is perhaps specific to the eclipse testng plugin.

Body:
[RemoteTestNG] detected TestNG version 7.0.1

Exception in thread "main" java.lang.NoClassDefFoundError:
  com/google/inject/Stage


问:
latlng cannot be null - a position is required in Autocomplete
i am using Autocomplete search places that  get the address but not working on some addresses giving error of

Failure delivering result ResultInfo{who=null, request=131190, result=-1, data=Intent { (has extras) }} to activity  java.lang.IllegalArgumentException: latlng cannot be null - a position is required.

here is my code

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 116) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);

            if(priviuos.contains("new")){
                loc_txt.setText(place.getName());
                pickmarkets =  getLocationFromAddress(getContext(),place.getName());
                latlngdata ="1";
                priviuos = "old";
            }
            else{
                loc_txt.setText(place.getName());
                pickmarkets =  getLocationFromAddress(getContext(),place.getName());
                latlngdata ="1";
                priviuos = "old";
                bothgetmarkers(markets,pickmarkets);
            }

        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);

            Log.i("mmm", status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }

    }
}
</code>```

答:
The autocomplete fragment is initialixed and the data that you would want to extract from the selected place is specified here.

autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));

if you want to use the placeID specify

Place.Field.ID

and so on.
You are trying to use the place LAT_LNG but havent specified it as

Place.Field.LAT_LNG

as above

Body:
i am using Autocomplete search places that  get the address but not working on some addresses giving error of

Failure delivering result ResultInfo{who=null, request=131190, result=-1, data=Intent { (has extras) }} to activity  java.lang.IllegalArgumentException: latlng cannot be null - a position is required.

here is my code

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 116) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);

            if(priviuos.contains("new")){
                loc_txt.setText(place.getName());
                pickmarkets =  getLocationFromAddress(getContext(),place.getName());
                latlngdata ="1";
                priviuos = "old";
            }
            else{
                loc_txt.setText(place.getName());
                pickmarkets =  getLocationFromAddress(getContext(),place.getName());
                latlngdata ="1";
                priviuos = "old";
                bothgetmarkers(markets,pickmarkets);
            }

        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);

            Log.i("mmm", status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }

    }
}


问:
LOAD DATA INFILE not working in mariadb
Iam trying to migrate from mysql to mariadb. On this time I can face an issue with mariadb.

When I can trying to load a data file into a table, it shows an error like :

SQL Error (29): File 'C:/Documents and Settings/Administrator/Local Settings/Temp/SAMPLE/DATA_TEMP1351761841668/SampleFile0' not found (Errcode: 2)

But the file already exists in the path....

Another one point is that the same command successfully works with MySQL.
Is MariaDB has any permission issue?

See below my query :

```<code>load data infile "'C:/Documents and Settings/Administrator/Local Settings/Temp/SAMPLE/DATA_TEMP1351761841668/SampleFile0" into table SAMPLETABLE;
</code>```

When changing the path like "C:/SampleFile0", its working properly. Path from Administrator folder it doesn't working.

Can anyone help me in this regard??? Iam a newone in MariaDB.

答: There is an unwanted single quote in your command.</p>

Title: LOAD DATA INFILE not working in mariadb

Body:
Iam trying to migrate from mysql to mariadb. On this time I can face an issue with mariadb.

When I can trying to load a data file into a table, it shows an error like :

SQL Error (29): File 'C:/Documents and Settings/Administrator/Local Settings/Temp/SAMPLE/DATA_TEMP1351761841668/SampleFile0' not found (Errcode: 2)

But the file already exists in the path....

Another one point is that the same command successfully works with MySQL.
Is MariaDB has any permission issue?

See below my query :

load data infile "'C:/Documents and Settings/Administrator/Local Settings/Temp/SAMPLE/DATA_TEMP1351761841668/SampleFile0" into table SAMPLETABLE;

When changing the path like "C:/SampleFile0", its working properly. Path from Administrator folder it doesn't working.

Can anyone help me in this regard??? Iam a newone in MariaDB.


问:
Play Framework returning 404 with play.http.context and trailing slash
I have a Play Framework application that serves an SPA. The routes file contains the following routes:

```<code>GET      /            controllers.Home.index
GET      /index.html  controllers.Home.index

# /api/* routes

GET      /*file       controllers.Assets.at(file)
</code>```

controllers.Home.index serves the SPA's index after performing SSO routines.

When I run the application without any additional configuration, upon visiting localhost:3000 and localhost:3000/, the index action in Home controller is invoked as expected.

The problems start when I configure play.http.context:

When set to /my-app, requests to localhost:3000/my-app succeed; to localhost:3000/my-app/ return 404.

When set to /my-app/, requests to localhost:3000/my-app return 404; to localhost:3000/my-app/ succeed.

Is there a way to configure Play such that requests to both URLs succeed with controllers.Home.index?

答:
I was looking for the same, but there is no good answer. For Play/Akka those are 2 different URLs,

Option 1)
is to define it 2x

```<code>GET     /about                     controllers.HomeController.about
GET     /about/                     controllers.HomeController.about
</code>```

Option 2)
redirect one url to another

```<code>GET /a                              controllers.HomeController.about
GET /a/                             controllers.Default.redirect(to = "/a")
</code>```

Option 3)
more advanced ways, but I did not testd it

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/ignoreTrailingSlash.html

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/redirectToNoTrailingSlashIfPresent.html

https://github.com/akka/akka-http/issues/880

Body:
I have a Play Framework application that serves an SPA. The routes file contains the following routes:

GET      /            controllers.Home.index
GET      /index.html  controllers.Home.index

# /api/* routes

GET      /*file       controllers.Assets.at(file)

controllers.Home.index serves the SPA's index after performing SSO routines.

When I run the application without any additional configuration, upon visiting localhost:3000 and localhost:3000/, the index action in Home controller is invoked as expected.

The problems start when I configure play.http.context:

When set to /my-app, requests to localhost:3000/my-app succeed; to localhost:3000/my-app/ return 404.

When set to /my-app/, requests to localhost:3000/my-app return 404; to localhost:3000/my-app/ succeed.

Is there a way to configure Play such that requests to both URLs succeed with controllers.Home.index?

Body:
I was looking for the same, but there is no good answer. For Play/Akka those are 2 different URLs,

Option 1)
is to define it 2x

GET     /about                     controllers.HomeController.about
GET     /about/                     controllers.HomeController.about

Option 2)
redirect one url to another

GET /a                              controllers.HomeController.about
GET /a/                             controllers.Default.redirect(to = "/a")

Option 3)
more advanced ways, but I did not testd it

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/ignoreTrailingSlash.html

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/redirectToNoTrailingSlashIfPresent.html

https://github.com/akka/akka-http/issues/880


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答:
Do you have control of the file being passed in? If so, might I suggest formatting it using XML and then parsing it using JDOM? It would make your life easier in terms of parsing. For example, you could format all vehicle entries like this:

```<code>

    <node type="vehicle>
       <attributes location="detroit" color="red" />
    </node>
</code>```

Or whatever format you come up with. The benefit of this is you can then read in only the vehicles (or whatever you want), or use XPath or some other technology to efficiently get the info you want/need and load it to the proper datatype.

Disregard this advice if you have no control over file formatting.

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

Body:
Do you have control of the file being passed in? If so, might I suggest formatting it using XML and then parsing it using JDOM? It would make your life easier in terms of parsing. For example, you could format all vehicle entries like this:

    <node type="vehicle>
       <attributes location="detroit" color="red" />
    </node>

Or whatever format you come up with. The benefit of this is you can then read in only the vehicles (or whatever you want), or use XPath or some other technology to efficiently get the info you want/need and load it to the proper datatype.

Disregard this advice if you have no control over file formatting.

OwnerDisplayName: kgrad


问:
How to scrape a word press based page? Respectively how to login to a page requesting username and Password
So im quite unsure how to explain my issue. So - I try to scrape a schedule page (of my school) to make It easier to read. Unfortunately i couldnt figure how to pass the creditals to the login prompt with python.

url = "https://www.diltheyschule.de/vertretungsplan/

or rather this one due to it contains the actual data.

url = https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm

I do know the password and username.

Login prompt looks like this :

As you might have guessed - i want to pass password and username to this prompt.
This code doesnt work for me - it returns unauthorized error.
```<code>import requests
session = requests.Session()
r = session.post("https://www.diltheyschule.de/vertretungsplan/",data={"log":"xxx","pwd":"xxx"})
#or
r = session.post("https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm",data={"log":"xxx","pwd":"xxx"})
print(r.content)
</code>```

output

```<code><!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache Server at www.diltheyschule.de Port 443</address>
</body></html>
</code>```

prolly essential information :

 the goal is to scrape 'https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm'

passing pwd and log to the prompt (most likely without gui support (e.g. selenium))

答:
This directory is secured by basic auth authentication. This is the easiest method of authentication where you can log in with the appropriate headers.

Are you also sure that you want to use POST method for see what is in .html page?

Please, try this:

```<code>import requests
session = requests.Session()

r = session.get("https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm",auth=requests.auth.HTTPBasicAuth('user', 'pass'))
print(r.content)
</code>```

Body:
So im quite unsure how to explain my issue. So - I try to scrape a schedule page (of my school) to make It easier to read. Unfortunately i couldnt figure how to pass the creditals to the login prompt with python.

url = "https://www.diltheyschule.de/vertretungsplan/

or rather this one due to it contains the actual data.

url = https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm

I do know the password and username.

Login prompt looks like this :

As you might have guessed - i want to pass password and username to this prompt.
This code doesnt work for me - it returns unauthorized error.

import requests
session = requests.Session()
r = session.post("https://www.diltheyschule.de/vertretungsplan/",data={"log":"xxx","pwd":"xxx"})
#or
r = session.post("https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm",data={"log":"xxx","pwd":"xxx"})
print(r.content)

output

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>401 Unauthorized</title>

Unauthorized

This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.

<address>Apache Server at www.diltheyschule.de Port 443</address>

prolly essential information :

 the goal is to scrape 'https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm'

passing pwd and log to the prompt (most likely without gui support (e.g. selenium))

Body:
This directory is secured by basic auth authentication. This is the easiest method of authentication where you can log in with the appropriate headers.

Are you also sure that you want to use POST method for see what is in .html page?

Please, try this:

import requests
session = requests.Session()

r = session.get("https://www.diltheyschule.de/vertretungsplan/f1/subst_001.htm",auth=requests.auth.HTTPBasicAuth('user', 'pass'))
print(r.content)


问:
Unable to generate allure report using testng and maven

TestNG Version

7.1.0

Expected behavior

mvn test command should execute the test normally, knowing that same POM was working fine before until I update testNG and some other dependencies, I'm using allure with testNG and maven as well, now if I disabled allure-TestNG test will be executed but allure won't generate any report

Actual behavior

I'm getting this error
      Please refer to C:\Users\warrior\Desktop\MobileAutomationTest\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked processorg/testng/IInvokedMethodListener2
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked processorg/testng/IInvokedMethodL
istener2

Is the issue reproducible on a runner?

[x] Maven

[x] IntelliJ

Test case sample

POM file

```<code>         <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
   4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MobileAutomationTest</groupId>
    <artifactId>SafeApp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <jre.level>1.8</jre.level>
        <jdk.level>1.8</jdk.level>
        <aspectj.version>1.9.5</aspectj.version>
    </properties>

    <build>
        <plugins>
            <!-- Compiler plug-in -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${jdk.level}</source>
                    <target>${jdk.level}</target>
                </configuration>
            </plugin>
            <!-- Added Surefire Plugin configuration to execute tests -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    </argLine>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/java/TestNG.xml/</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.1.0</version>
        </dependency>
<!--        <!– https://mvnrepository.com/artifact/io.qameta.allure/allure-testng –>-->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-testng</artifactId>
            <version>2.13.0</version>
        </dependency>
        <!--https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server-->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.141.59</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/io.appium/java-client -->
            <dependency>
                <groupId>io.appium</groupId>
                <artifactId>java-client</artifactId>
                <version>7.3.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.relevantcodes/extentreports -->
            <dependency>
                <groupId>com.relevantcodes</groupId>
                <artifactId>extentreports</artifactId>
                <version>2.41.2</version>
            </dependency>
            <!-- log4j2 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.29</version>
            </dependency>
        </dependencies>
        <reporting>
            <excludeDefaults>true</excludeDefaults>
            <plugins>
                <plugin>
                    <groupId>io.qameta.allure</groupId>
                    <artifactId>allure-maven</artifactId>
                    <version>2.10.0</version>
                    <configuration>
                        <reportDirectory>${basedir}\target\allure-report</reportDirectory>
                    </configuration>
                </plugin>
            </plugins>
        </reporting>

    </project>
</code>```

答:
The problem here is with Allure reports which is NOT compatible with TestNG 7.1.0.

TestNG 7.1.0 removed the listener IInvokedMethodListener2 interface.

This needs to be fixed in Allure reports.

I have also added more information in the github issue that was logged for this : https://github.com/cbeust/testng/issues/2246

Body:
TestNG Version

7.1.0

Expected behavior

mvn test command should execute the test normally, knowing that same POM was working fine before until I update testNG and some other dependencies, I'm using allure with testNG and maven as well, now if I disabled allure-TestNG test will be executed but allure won't generate any report

Actual behavior

I'm getting this error
      Please refer to C:\Users\warrior\Desktop\MobileAutomationTest\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked processorg/testng/IInvokedMethodListener2
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked processorg/testng/IInvokedMethodL
istener2

Is the issue reproducible on a runner?

[x] Maven

[x] IntelliJ

Test case sample

POM file

         <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
   4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MobileAutomationTest</groupId>
    <artifactId>SafeApp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <jre.level>1.8</jre.level>
        <jdk.level>1.8</jdk.level>
        <aspectj.version>1.9.5</aspectj.version>
    </properties>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${jdk.level}</source>
                    <target>${jdk.level}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M4</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    </argLine>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/java/TestNG.xml/</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.1.0</version>
        </dependency>

        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-testng</artifactId>
            <version>2.13.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.141.59</version>
            </dependency>

            <dependency>
                <groupId>io.appium</groupId>
                <artifactId>java-client</artifactId>
                <version>7.3.0</version>
            </dependency>

            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>com.relevantcodes</groupId>
                <artifactId>extentreports</artifactId>
                <version>2.41.2</version>
            </dependency>

            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.29</version>
            </dependency>
        </dependencies>
        <reporting>
            <excludeDefaults>true</excludeDefaults>
            <plugins>
                <plugin>
                    <groupId>io.qameta.allure</groupId>
                    <artifactId>allure-maven</artifactId>
                    <version>2.10.0</version>
                    <configuration>
                        <reportDirectory>${basedir}\target\allure-report</reportDirectory>
                    </configuration>
                </plugin>
            </plugins>
        </reporting>

    </project>


问:
Unable to add in the text colour of my menu navbar
This should be a fairly simple thing, however no matter where I add in color: black; the menu items do not show, you can only see them when I click and highlight over them. Please could someone point out which class needs to color tag to alter the text colour to black? I have tried placing it in .topnav with color: black; but did not change anything?

Also I can't get the active class to change when I'm on a different page, seems to only stay on the Home page?

```<code>.topnav {
  background-color:white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */
.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */
.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
  display: block;
}
</code>```

THE MENU CODE:

```<code><!-- NAV BAR homepage-->
<nav>
  <!-- https://www.w3schools.com/howto/howto_js_topnav_responsive.asp -->
  <div class="topnav" id="myTopnav">
      <a href="index.php" class="active"><i class="fas fa-home">  Home</i></a>
      <a href="about.php"><i class="fas fa-info-circle">  About</i></a>
      <a href="contact.php"><i class="fas fa-envelope">  Contact</i></a>
      <?php
        // The below is a small 'if else' statement which depending on whether a user is logged in or not, the menu items will differ
        // If logged in, then show the logout and the dashboard item
        // If not logged in, then show the login and signup button
        if (!isset($_SESSION['studentID'])) {
          echo "<a name='login-submit' href='login.php'><i class='fas fa-sign-in-alt'>  Login</i></a>";
          echo "<a href='signup.php'><i class='fas fa-check-square'>  Sign Up</i></a>";
        } else if (isset($_SESSION['studentID'])) {
          echo "<a href ='dashboard.php'><i class='fas fa-tachometer-alt'>  Dashboard</i></a> ";
          echo "<a name='logout-submit' href='scripts/logout-script.php'><i class='fas fa-sign-out-alt'>  Logout</i></a>";
        }
      ?>
      <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="menu2Function()">☰</a>
  </div>
</nav>
</code>```

I have right clicked into the console to check the styles tab:

This is what I see on my screen without hovering over an item in the menu:

Then this is what I see when I hover over an item (About):

答:
Just add color: black to yours .topnav a components and get out the text from the fontawesome tag. For example replace that:

  Contact
```

<p>to that:</p>

<pre class="lang-html prettyprint-override"><code><i class="fas fa-envelope"></i>  Contact
</code>```

You will get something like that:

.topnav {
  background-color: white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */

.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */

.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */

.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */

.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */

.topnav a:hover,
.dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */

.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- NAV BAR homepage-->
<nav>
  <!-- https://www.w3schools.com/howto/howto_js_topnav_responsive.asp -->
  <div class="topnav" id="myTopnav">
    <i class="fas fa-home"></i>  Home
    <i class="fas fa-info-circle"></i>  About
    <i class="fas fa-envelope"></i>  Contact
    <i class='fas fa-sign-in-alt'></i>  Login;
    <i class='fas fa-check-square'></i>  Sign Up;
    <i class='fas fa-tachometer-alt'></i>  Dashboard;
    <i class='fas fa-sign-out-alt'></i>  Logout;
    ☰
  </div>
</nav></code>```

Body:
This should be a fairly simple thing, however no matter where I add in color: black; the menu items do not show, you can only see them when I click and highlight over them. Please could someone point out which class needs to color tag to alter the text colour to black? I have tried placing it in .topnav with color: black; but did not change anything?

Also I can't get the active class to change when I'm on a different page, seems to only stay on the Home page?

.topnav {
  background-color:white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */
.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */
.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
  display: block;
}

THE MENU CODE:

        Home
        About
        Contact
      <?php
        // The below is a small 'if else' statement which depending on whether a user is logged in or not, the menu items will differ
        // If logged in, then show the logout and the dashboard item
        // If not logged in, then show the login and signup button
        if (!isset($_SESSION['studentID'])) {
          echo "  Login";
          echo "  Sign Up";
        } else if (isset($_SESSION['studentID'])) {
          echo "  Dashboard ";
          echo "  Logout";
        }
      ?>
      ☰

I have right clicked into the console to check the styles tab:

This is what I see on my screen without hovering over an item in the menu:

Then this is what I see when I hover over an item (About):

Body:
Just add color: black to yours .topnav a components and get out the text from the fontawesome tag. For example replace that:

<i class="fas fa-envelope">&nbsp; Contact</i>

to that:

<i class="fas fa-envelope"></i>&nbsp; Contact

You will get something like that:

.topnav {
  background-color: white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */

.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */

.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */

.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */

.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */

.topnav a:hover,
.dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */

.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */

.dropdown:hover .dropdown-content {
  display: block;
}

<!-- NAV BAR homepage-->
<nav>
  <!-- https://www.w3schools.com/howto/howto_js_topnav_responsive.asp -->
  <div class="topnav" id="myTopnav">
    <a href="index.php" class="active"><i class="fas fa-home"></i>&nbsp; Home</a>
    <a href="about.php"><i class="fas fa-info-circle"></i>&nbsp; About</a>
    <a href="contact.php"><i class="fas fa-envelope"></i>&nbsp; Contact</a>
    <a name='login-submit' href='login.php'><i class='fas fa-sign-in-alt'></i>&nbsp; Login</a>;
    <a href='signup.php'><i class='fas fa-check-square'></i>&nbsp; Sign Up</a>;
    <a href='dashboard.php'><i class='fas fa-tachometer-alt'></i>&nbsp; Dashboard</a>;
    <a name='logout-submit' href='scripts/logout-script.php'><i class='fas fa-sign-out-alt'></i>&nbsp; Logout</a>;
    <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="menu2Function()">&#9776;</a>
  </div>
</nav>


问:
Taskkill /PID not working in GitBash
I'm trying to kill a process on GitBash on Windows10 using the taskkill command. However, I get the following error:

```<code>$ taskkill /pid 13588
ERROR: Invalid argument/option - 'C:/Program Files/Git/pid'.
Type "TASKKILL /?" for usage.
</code>```

it works fine on cmd. Can anyone help?

答:
To fix this I need to kill another additional program:</p>

```<code>taskkill //F //IM "git-bash.exe"
taskkill //F //IM "bash.exe"
</code>```

Title: Taskkill /PID not working in GitBash

Body:
I'm trying to kill a process on GitBash on Windows10 using the taskkill command. However, I get the following error:

$ taskkill /pid 13588
ERROR: Invalid argument/option - 'C:/Program Files/Git/pid'.
Type "TASKKILL /?" for usage.

it works fine on cmd. Can anyone help?

Body:
To fix this I need to kill another additional program:

taskkill //F //IM "git-bash.exe"
taskkill //F //IM "bash.exe"


问:
List cannot be converted to List
Why this is not allowed?

error: incompatible types: List<TextBook> cannot be
  converted to List<Book>

process(textBooks);

```<code>import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println(“OK”)

        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println(“OK”);
    }
}
</code>```

答: This is not allowed because you started out with an arraylist of Textbook. However you passed it to process as a list of Book. The process function could add something which is not a textbook to the list. At this point your original list would not be an arraylist of Textbook.

Title: List cannot be converted to List

Body:
Why this is not allowed?

error: incompatible types: List<TextBook> cannot be
  converted to List<Book>

process(textBooks);

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println(“OK”)

        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println(“OK”);
    }
}


问:
Programmatically add repeating section item to a word document using OpenXml.WordProcessing .NET
I have a document template which I want to dynamically populate using C#. The template contains a repeating section that has a few text boxes and some static text. I want to be able to populate the text boxes and to add new section items when needed.

The code that almost works is as follows:

```<code>WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\in\test.docx", true);
var mainDoc = doc.MainDocumentPart.Document.Body
    .GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.SdtBlock>()
    .GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.SdtContentBlock>();

var person = mainDoc.ChildElements[mainDoc.ChildElements.Count-1];
person.InsertAfterSelf<DocumentFormat.OpenXml.Wordprocessing.SdtBlock>(
    (DocumentFormat.OpenXml.Wordprocessing.SdtBlock) person.Clone());
</code>```

This however, produces a corrupted file because the unique IDs are also duplicated by the Clone method.

Any idea on how to achieve my goal?

答:
Here is some code that shows how you could do this. Note that this removes the existing unique Id (the w:id element) to ensure this is not repeated.

using WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\in\test.docx", true);

// Get the w:sdtContent element of the first block-level w:sdt element,
// noting that "sdtContent" is called "mainDoc" in the question.
SdtContentBlock sdtContent = doc.MainDocumentPart.Document.Body
    .Elements<SdtBlock>()
    .Select(sdt => sdt.SdtContentBlock)
    .First();

// Get last element within SdtContentBlock. This seems to represent a "person".
SdtBlock person = sdtContent.Elements<SdtBlock>().Last();

// Create a clone and remove an existing w:id element from the clone's w:sdtPr
// element, to ensure we don't repeat it. Note that the w:id element is optional
// and Word will add one when it saves the document.
var clone = (SdtBlock) person.CloneNode(true);
SdtId id = clone.SdtProperties?.Elements<SdtId>().FirstOrDefault();
id?.Remove();

// Add the clone as the new last element.
person.InsertAfterSelf(clone);
```

Body:
I have a document template which I want to dynamically populate using C#. The template contains a repeating section that has a few text boxes and some static text. I want to be able to populate the text boxes and to add new section items when needed.

The code that almost works is as follows:

WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\in\test.docx", true);
var mainDoc = doc.MainDocumentPart.Document.Body
    .GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.SdtBlock>()
    .GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.SdtContentBlock>();

var person = mainDoc.ChildElements[mainDoc.ChildElements.Count-1];
person.InsertAfterSelf<DocumentFormat.OpenXml.Wordprocessing.SdtBlock>(
    (DocumentFormat.OpenXml.Wordprocessing.SdtBlock) person.Clone());

This however, produces a corrupted file because the unique IDs are also duplicated by the Clone method.

Any idea on how to achieve my goal?


问:
How do you change the colour of the back button icon in Ionic 4?
I am trying to make the back button icon white in the toolbar of my Ionic 4 app. I have added:

```<code>ion-back-button {
  --color: white;
}
</code>```

in my global.scss, but the icon persists in being grey. I have managed to make my toolbar title white.

This is my template:

```<code><ion-toolbar>
    <ion-buttons slot="start">
        <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Title</ion-title>
</ion-toolbar>
</code>```

I'd like to be able to simply define a global style to change the colour of all back buttons globally without having to add additional markup to every page with a back button.

答:
I had this same problem.   No matter what I tried, I could not change the color of the ion-back-button from gray.   So, I used the Chrome developer tools to inspect the element and learned that a theme for a third-party module that I had loaded was applying that gray color to all span tags.  Fortunately, I no longer needed that module, so the answer for me was to simply remove the reference to the theme.

The module that was causing this problem was AWS Amplify.

I am posting this "answer" here to help you or anyone else take a "next step" in resolving this "maddening" problem: use Chrome developer tools to inspect the back button element in the DOM to identify the CSS rule that is being applied.

Body:
I am trying to make the back button icon white in the toolbar of my Ionic 4 app. I have added:

ion-back-button {
  --color: white;
}

in my global.scss, but the icon persists in being grey. I have managed to make my toolbar title white.

This is my template:

<ion-toolbar>
    <ion-buttons slot="start">
        <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Title</ion-title>
</ion-toolbar>

I'd like to be able to simply define a global style to change the colour of all back buttons globally without having to add additional markup to every page with a back button.


答:
For a first pitch, I would say that the color of your text is the same as the background of the navbar/body so you could try adding a background-color: color  to your navbar.

```<code>.topnav a {
 background-color: lightgray; //background-color
 float: left;
 display: block;
 color: black; //change color of the text
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
 font-size: 17px;
}
</code>```

If you decide to not add a background-color you can consider changing the color of the text to any other with color: [color].

Title: Unable to add in the text colour of my menu navbar

Body:
For a first pitch, I would say that the color of your text is the same as the background of the navbar/body so you could try adding a background-color: color  to your navbar.

.topnav a {
 background-color: lightgray; //background-color
 float: left;
 display: block;
 color: black; //change color of the text
 text-align: center;
 padding: 14px 16px;
 text-decoration: none;
 font-size: 17px;
}

If you decide to not add a background-color you can consider changing the color of the text to any other with color: [color].