问:
Plotting a better treemap using ggplot and the geom_rect hack, but how to get the labels correct?
I have found it challenging to create a treemap using ggplot, and this blog example captured the issues very well and also provided a nice work around.  The work around takes the output from the tree map package to create a ggplot version with geom_rect.

My problem and question is how to adjust the labels and, if I wanted to, colors by hierarchy as I have more groups than the linked example and have different labeling requirements.

Here is a reproducible simple example:

```<code>library(tidyverse)
library(treemap)

# Create dummy data
tree_data <- data.frame(
  my_segment = c(
    rep("seg_a", 5),
    rep("seg_b", 6),
    rep("seg_c", 7)),
  my_class = c(
    rep("class_1", 2),
    rep("class_2", 2),
    rep("class_3", 1),
    rep("class_4", 2),
    rep("class_5", 2),
    rep("class_6", 2),
    rep("class_7", 1),
    rep("class_8", 3),
    rep("class_9", 3)),
  my_type = c(
    rep("type_1", 7),
    rep("type_2", 6),
    rep("type_3", 5)),
  vals = round(runif(18, min = 20, max = 100), 0)
)
</code>```

Here is the head of the sample dataframe:

```<code>   my_segment my_class my_type vals
1       seg_a  class_1  type_1   86
2       seg_a  class_1  type_1   41
3       seg_a  class_2  type_1   23
4       seg_a  class_2  type_1   79
5       seg_a  class_3  type_1   33
6       seg_b  class_4  type_1   82
7       seg_b  class_4  type_1   85
8       seg_b  class_5  type_2   40
9       seg_b  class_5  type_2   83
10      seg_b  class_6  type_2   69
11      seg_b  class_6  type_2   98
12      seg_c  class_7  type_2   91
13      seg_c  class_8  type_2   33
</code>```

The tree map package runs fine, but produces unreadable output in RStudio, and I'd like to be able to customize more with ggplot (similar to the linked article)

```<code># Run treemap function
tree_p <- treemap(
  tree_data,
  index            = c("my_segment", "my_class", "my_type"),
  vColor           = "my_segment",
  vSize            = "vals",
  type             = "index",
  fontsize.labels  = c(15, 12, 10),
  fontcolor.labels = c("white", "orange", "green"),
  fontface.labels  = c(2, 1, 1),
  bg.labels        = 0,
  align.labels     = list(
    c("center", "center"),
    c("right", "bottom"),
    c("left", "bottom")
  ),
  overlap.labels   = 0.5,
  inflate.labels   = FALSE
)

# Note:  unreadable output in Rstudio (too small)
</code>```

Using the workaround in this blog, but adding an additional hierarchy and wanted to change the labeling is where the problem comes in.

```<code># Create the plot in ggplot using geom_rect

# Get underlying data created from running treemap
tm_plot_data <- tree_p$tm %>%
  mutate(x1 = x0 + w,
         y1 = y0 + h) %>%
  mutate(x = (x0+x1)/2,
         y = (y0+y1)/2) %>%
  mutate(
    primary_group = case_when(
      level == 1 ~ 1.5,
      level == 2 ~ 0.75,
      TRUE       ~ 0.5
    )
  )

# Plot
ggplot(tm_plot_data, aes(xmin = x0, ymin = y0, xmax = x1, ymax = y1)) +
  # add fill and borders for groups and subgroups
  geom_rect(aes(fill = color, size = primary_group),
            show.legend = FALSE,
            color       = "black",
            alpha       = 0.3
  ) +
  scale_fill_identity() +
  # set thicker lines for group borders
  scale_size(range = range(tm_plot_data$primary_group)) +
  # add labels
  ggfittext::geom_fit_text(aes(label = my_segment), color = "white", min.size = 1) +
  ggfittext::geom_fit_text(aes(label = my_class), color = "blue", min.size = 1) +
  ggfittext::geom_fit_text(aes(label = my_type), color = "red", min.size = 1) +
  # options
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme_void()
</code>```

So the question I have is there a way to create the labeling like treemap?  Specifically, seg_a, seg_b, and seg_c should only appear once, centered over the area of their respective segments.  I'd also like to move the labels so that they do not overlap

Thanks for any help and suggestions!

答:
The issue is that you use your full dataset tm_plot_data to add the labels. Hence, for each upper level you you get multiple labels. To solve this issue aggregate your datasets and pass these datasets as data to ggfittext::geom_fit_text. To deal with overlapping labels you could e.g. use the place argument of ggfittext::geom_fit_text to move the class labels to the bottom left and the type labels to the topright.

library(tidyverse)
library(treemap)

set.seed(123)

tm_seg <- tm_plot_data %>%
  group_by(my_segment) %>%
  summarise(x0 = min(x0), y0 = min(y0), y1 = max(y1), x1 = max(x1)) %>%
  ungroup()

tm_class <- tm_plot_data %>%
  group_by(my_segment, my_class) %>%
  summarise(x0 = min(x0), y0 = min(y0), y1 = max(y1), x1 = max(x1)) %>%
  ungroup()

tm_type <- tm_plot_data %>%
  group_by(my_segment, my_class, my_type) %>%
  summarise(x0 = min(x0), y0 = min(y0), y1 = max(y1), x1 = max(x1)) %>%
  ungroup()

# Plot
ggplot(tm_plot_data, aes(xmin = x0, ymin = y0, xmax = x1, ymax = y1)) +
  # add fill and borders for groups and subgroups
  geom_rect(aes(fill = color, size = primary_group),
    show.legend = FALSE,
    color       = "black",
    alpha       = 0.3
  ) +
  scale_fill_identity() +
  # set thicker lines for group borders
  scale_size(range = range(tm_plot_data$primary_group)) +
  # add labels
  ggfittext::geom_fit_text(data = tm_seg, aes(label = my_segment), color = "white", min.size = 4) +
  ggfittext::geom_fit_text(data = tm_class, aes(label = my_class), color = "blue", min.size = 1, place = "bottomleft") +
  ggfittext::geom_fit_text(data = tm_type, aes(label = my_type), color = "red", min.size = 1, place = "topright") +
  # options
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme_void()
#> Warning: Removed 3 rows containing missing values (geom_fit_text).
#> Warning: Removed 12 rows containing missing values (geom_fit_text).
```

Body:
I have found it challenging to create a treemap using ggplot, and this blog example captured the issues very well and also provided a nice work around.  The work around takes the output from the tree map package to create a ggplot version with geom_rect.

My problem and question is how to adjust the labels and, if I wanted to, colors by hierarchy as I have more groups than the linked example and have different labeling requirements.

Here is a reproducible simple example:

library(tidyverse)
library(treemap)

# Create dummy data
tree_data <- data.frame(
  my_segment = c(
    rep("seg_a", 5),
    rep("seg_b", 6),
    rep("seg_c", 7)),
  my_class = c(
    rep("class_1", 2),
    rep("class_2", 2),
    rep("class_3", 1),
    rep("class_4", 2),
    rep("class_5", 2),
    rep("class_6", 2),
    rep("class_7", 1),
    rep("class_8", 3),
    rep("class_9", 3)),
  my_type = c(
    rep("type_1", 7),
    rep("type_2", 6),
    rep("type_3", 5)),
  vals = round(runif(18, min = 20, max = 100), 0)
)

Here is the head of the sample dataframe:

   my_segment my_class my_type vals
1       seg_a  class_1  type_1   86
2       seg_a  class_1  type_1   41
3       seg_a  class_2  type_1   23
4       seg_a  class_2  type_1   79
5       seg_a  class_3  type_1   33
6       seg_b  class_4  type_1   82
7       seg_b  class_4  type_1   85
8       seg_b  class_5  type_2   40
9       seg_b  class_5  type_2   83
10      seg_b  class_6  type_2   69
11      seg_b  class_6  type_2   98
12      seg_c  class_7  type_2   91
13      seg_c  class_8  type_2   33

The tree map package runs fine, but produces unreadable output in RStudio, and I'd like to be able to customize more with ggplot (similar to the linked article)

# Run treemap function
tree_p <- treemap(
  tree_data,
  index            = c("my_segment", "my_class", "my_type"),
  vColor           = "my_segment",
  vSize            = "vals",
  type             = "index",
  fontsize.labels  = c(15, 12, 10),
  fontcolor.labels = c("white", "orange", "green"),
  fontface.labels  = c(2, 1, 1),
  bg.labels        = 0,
  align.labels     = list(
    c("center", "center"),
    c("right", "bottom"),
    c("left", "bottom")
  ),
  overlap.labels   = 0.5,
  inflate.labels   = FALSE
)

# Note:  unreadable output in Rstudio (too small)

Using the workaround in this blog, but adding an additional hierarchy and wanted to change the labeling is where the problem comes in.

# Create the plot in ggplot using geom_rect

# Get underlying data created from running treemap
tm_plot_data <- tree_p$tm %>%
  mutate(x1 = x0 + w,
         y1 = y0 + h) %>%
  mutate(x = (x0+x1)/2,
         y = (y0+y1)/2) %>%
  mutate(
    primary_group = case_when(
      level == 1 ~ 1.5,
      level == 2 ~ 0.75,
      TRUE       ~ 0.5
    )
  )

# Plot
ggplot(tm_plot_data, aes(xmin = x0, ymin = y0, xmax = x1, ymax = y1)) +
  # add fill and borders for groups and subgroups
  geom_rect(aes(fill = color, size = primary_group),
            show.legend = FALSE,
            color       = "black",
            alpha       = 0.3
  ) +
  scale_fill_identity() +
  # set thicker lines for group borders
  scale_size(range = range(tm_plot_data$primary_group)) +
  # add labels
  ggfittext::geom_fit_text(aes(label = my_segment), color = "white", min.size = 1) +
  ggfittext::geom_fit_text(aes(label = my_class), color = "blue", min.size = 1) +
  ggfittext::geom_fit_text(aes(label = my_type), color = "red", min.size = 1) +
  # options
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme_void()

So the question I have is there a way to create the labeling like treemap?  Specifically, seg_a, seg_b, and seg_c should only appear once, centered over the area of their respective segments.  I'd also like to move the labels so that they do not overlap

Thanks for any help and suggestions!


来源: stackexchange

问:
ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')
I can view the variables in the html-page but I got the error for only the value of the gametitle

ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Here is the ts-file:

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  gametitle: string,
  releasedate: number,
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail!: GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
        console.log("gametitle: " + this.gamedetail.gametitle);
    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL> {
      return this.http.get<GAMEDETAIL>('https://example.org/api/gamedetail/' + spielid);
    }

}
</code>```

And here is the html-file, that I simple use for viewing the details

```<code>    <h1>{{ gamedetail.gametitle }}</h1>

    <p>{{ gamedetail.description }}</p>
</code>```

And finally the output from the console of my browser:

答:
```<code><h1>{{ gamedetail?.gametitle }}</h1>

<p>{{ gamedetail?.description }}</p>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can view the variables in the html-page but I got the error for only the value of the gametitle

ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Here is the ts-file:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  gametitle: string,
  releasedate: number,
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];
  gamedetail!: GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );

      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
        console.log("gametitle: " + this.gamedetail.gametitle);
    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL> {
      return this.http.get<GAMEDETAIL>('https://example.org/api/gamedetail/' + spielid);
    }

}

And here is the html-file, that I simple use for viewing the details

{{ gamedetail.gametitle }}

{{ gamedetail.description }}

And finally the output from the console of my browser:


问:
Can we convert (marshal) java objects with variables of 'Object' data type using JAXB
I have Class with variables which have 'Object' data type. I have to use the Object data type  because the data type of that filed is unknown. (Sometimes it is a String, String Array, Or other custom object etc.). But when we use 'Object' the JAXB Marshalling process is failing with errors.
Is there a way to handle this ?

My class is similar to below

```<code>@XmlRootElement(name = "student")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {

    private String name;
    private int id;
    private Object subject;
</code>```

}

when I use the @XmlTransient for the 'Object subject'. Marshalling errors are not available. But it does not add the 'subject' filed to the XML file.

答:
I have found that there is no direct way to handle the above situation if you do not know the Data type/types that can be assigned to 'Object' type variable.
But if you know all the data types that can be assigned to the 'Object' variable you can use @XMLElements annotation.</p>

Body:
I have Class with variables which have 'Object' data type. I have to use the Object data type  because the data type of that filed is unknown. (Sometimes it is a String, String Array, Or other custom object etc.). But when we use 'Object' the JAXB Marshalling process is failing with errors.
Is there a way to handle this ?

My class is similar to below

@XmlRootElement(name = "student")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {

    private String name;
    private int id;
    private Object subject;

}

when I use the @XmlTransient for the 'Object subject'. Marshalling errors are not available. But it does not add the 'subject' filed to the XML file.


问:
Why is form data not being sent to the server?
I am implementing a chat, creating a registration window, and it is necessary that the data from the form be sent to the server, so that it is then sent to the client side to be displayed in the list of clients. But for some reason the data from the form does not come, what's the problem? Here is the form index.html:

<form class = "FORM" action="/" method="post">
  Username

  <input type = "TEXT" class = "CHECK" autocomplete="off" name="Username">
  <button type = "submit" class="BTN" onclick="redirect()">Send</button>
</form>
```
<p>Here is the server on express index.js</p>
```const express = require('express');
const app = express();
const db = require('./database/database'); // подключаемся к бд
const urlencodedParser = express.urlencoded({extended: false});
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};

app.use(express.static(__dirname));

app.get('/', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {

    app.post("/", urlencodedParser, function (request, response) {
        if(!request.body) return response.sendStatus(400);
        console.log(request.body);
        //response.send(`${request.body.userName} - ${request.body.userAge}`);
    });
.....
```

Why is the data not coming from the form to the server?

答:
You would have to make an axios post request to the endpoint.

if you're using vanilla javascript, you also need to add eventlistener to the form.

```<code>const form = document.getElementsByClassName("FORM");
form.addEventListener("submit", (event) => {
event.preventDefault();
const userName = event.target.Username.value;
if (!userName) alert("Username is required");
else {
    axios
        .post(
            "http://localhost:3000/", {
            userName
        })
    .then((response) => {
        console.log(response.data);

        /*depending on what response you get from the server,
you may want to use .map() method to display all the usernames*/
    })
    .catch((error) => console.log(error));
    event.target.reset();
 }
})
</code>```

Body:
I am implementing a chat, creating a registration window, and it is necessary that the data from the form be sent to the server, so that it is then sent to the client side to be displayed in the list of clients. But for some reason the data from the form does not come, what's the problem? Here is the form index.html:

<form class = "FORM" action="/" method="post">
  Username

  <input type = "TEXT" class = "CHECK" autocomplete="off" name="Username">
  <button type = "submit" class="BTN" onclick="redirect()">Send</button>
</form>

Here is the server on express index.js

const express = require('express');
const app = express();
const db = require('./database/database'); // подключаемся к бд
const urlencodedParser = express.urlencoded({extended: false});
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};

app.use(express.static(__dirname));

app.get('/', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {

    app.post("/", urlencodedParser, function (request, response) {
        if(!request.body) return response.sendStatus(400);
        console.log(request.body);
        //response.send(`${request.body.userName} - ${request.body.userAge}`);
    });
.....

Why is the data not coming from the form to the server?

Body:
You would have to make an axios post request to the endpoint.

if you're using vanilla javascript, you also need to add eventlistener to the form.

const form = document.getElementsByClassName("FORM");
form.addEventListener("submit", (event) => {
event.preventDefault();
const userName = event.target.Username.value;
if (!userName) alert("Username is required");
else {
    axios
        .post(
            "http://localhost:3000/", {
            userName
        })
    .then((response) => {
        console.log(response.data);

        /*depending on what response you get from the server,
you may want to use .map() method to display all the usernames*/
    })
    .catch((error) => console.log(error));
    event.target.reset();
 }
})


问:
Re-authentication using Identity Server 4
We have 2 MVC applications as clients and an Identity Server 4.

We have setup cookie middleware and openIdconnect using owin.

Client 1 has a cookie lifetime of 40 minutes.

Client 2 has a cookie lifetime of 10 minutes (maybe it's more strict for security reasons)

We send max-age = session_length in the autzorization endpoint but in some cases we want to send the user immediately for re-authentication (for security reasons).

So, we decided to send max-age=0 in these cases.

So our problem is if we need to send the user for re-authentication before client cookie is expired, the user will be redirected to Identity Server with max-age=0 but what happening if a user hits again the client login page, the user will be redirected with max-age=session_length and the user will get tokens.

How can we protect the client?
The user is not authenticated so we don't know which user it is. How can we store information about the users previous activity? For example, where can we store the previous max-age value? So if the user tries to access the login page again we will know the correct max-age value.

答: I think that you are using the wrong mechanism. To force a reauthentication you should set prompt=login and not use max-age,


问:
How to pass previous React route through query param to next route
How to store previous location (route) in a constant and pass it through a query param?

I am using React router v5.

In my React (route) component I have a Link

```<code>import { Link } from 'react-router-dom';

<Link to={{ pathname: MyPage, search: `?redirectUrl=previous-route` }}>
 Go to page
</Link>
</code>```

I need to pass the previous location route to the next route (MyPage) through the query param redirectUrl.

```<code><Link to={{ pathname: MyPage, search: `?redirectUrl=${<----- My previous route value here}` }}>
  Go to page
</Link>
</code>```

How do I manage that?

答:
Use the useLocation hook to get the current location to pass along as the previous location for the next page.

```<code>import { Link, useLocation } from 'react-router-dom';

...

const { pathname } = useLocation();

...

<Link to={{ pathname: MyPage, search: `?redirectUrl=${pathname}` }}>
 Go to page
</Link>
</code>```

Body:
How to store previous location (route) in a constant and pass it through a query param?

I am using React router v5.

In my React (route) component I have a Link

import { Link } from 'react-router-dom';

<Link to={{ pathname: MyPage, search: `?redirectUrl=previous-route` }}>
 Go to page
</Link>

I need to pass the previous location route to the next route (MyPage) through the query param redirectUrl.

<Link to={{ pathname: MyPage, search: `?redirectUrl=${<----- My previous route value here}` }}>
  Go to page
</Link>

How do I manage that?

Body:
Use the useLocation hook to get the current location to pass along as the previous location for the next page.

import { Link, useLocation } from 'react-router-dom';

...

const { pathname } = useLocation();

...

<Link to={{ pathname: MyPage, search: `?redirectUrl=${pathname}` }}>
 Go to page
</Link>


问:
How to format json file view on html
current json view on html page

```<code>{"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to":
"27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected
 to": "27716125197"}]}
</code>```

what I want it to be formatted display like

```<code>{
   "result":[
      {
         "id":"103300640",
         "sms_phone":"730276061",
         "corrected to":"27730276061"
      },
      {
         "id":"103277733",
         "sms_phone":"716125197",
         "corrected to":"27716125197"
      }]
}
</code>```

JS code:

```<code>@app.route('/<path:req_path>')
def dir_listing(req_path):
   abs_path = os.path.join(UPLOAD_FOLDER, req_path)
   # Check if path is a file and serve
   if os.path.isfile(abs_path):
      return send_file(abs_path, mimetype="application/json")
return render_template('/index.html')
</code>```

HTML code:

```<code><ul>
    {% for file in file_list %}
    <li><a href="{{ file }}" id="list">{{ file }}</a></li>
    {% endfor %}
</ul>
</code>```

答:
You have to use JS to achieve this.
Please have a look at the below code.
Use the <code>```</code> tag to achieve this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body onload="myFunction()">
<script>
function myFunction() {
var data = {
    "data": {
        "x": "1",
        "y": "1",
        "url": "http://test.com"
    },
    "event": "start",
    "show": 1,
    "id": 50
}

document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
}

</script>
<pre id="json">```
</body>
<html></code>```
</div>
</div>
</p>

Title: How to format json file view on html

Body:
current json view on html page

{"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to":
"27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected
 to": "27716125197"}]}

what I want it to be formatted display like

{
   "result":[
      {
         "id":"103300640",
         "sms_phone":"730276061",
         "corrected to":"27730276061"
      },
      {
         "id":"103277733",
         "sms_phone":"716125197",
         "corrected to":"27716125197"
      }]
}

JS code:

@app.route('/<path:req_path>')
def dir_listing(req_path):
   abs_path = os.path.join(UPLOAD_FOLDER, req_path)
   # Check if path is a file and serve
   if os.path.isfile(abs_path):
      return send_file(abs_path, mimetype="application/json")
return render_template('/index.html')

HTML code:

    {% for file in file_list %}

{{ file }}

    {% endfor %}

Body:
You have to use JS to achieve this.
Please have a look at the below code.
Use the <pre> tag to achieve this.

<html>
<head>
</head>
<body onload="myFunction()">
<script>
function myFunction() {
var data = {
    "data": {
        "x": "1",
        "y": "1",
        "url": "http://test.com"
    },
    "event": "start",
    "show": 1,
    "id": 50
}

document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
}

</script>
<pre id="json"></pre>
</body>
<html>


问:
Call a modal with data ajax laravel 8
I have a problem with my app , when i click the edit btn in the table then my modal is showed with data and when i click the second row in the table then my modal is not show.

this my controller :

```<code>public function edit_kpi_program_plan(Request $request)
{
    $data = kpi_input_program::where('id' , $request->id)->first();

    return response()->json($data, 200);
}
</code>```

this my route :

```<code>Route::post('/edit-program-input', [InputController::class, 'edit_kpi_program_plan'])->name('edit.program');
</code>```

this my button in blade:

```<code><a href="javascript:void(0)" id="btn-edit-plan" class="btn btn-primary edit" data-id="{{ $itemd->id }}">Edit</a>
</code>```

this my modal in blade:

```<code> <!-- Modal Input Program Plan Value Update -->
    <div class="modal fade" id="new_modal_plan" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Input Program Plan</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
            </div>
            <div class="modal-body">
                <form action="{{ route('update-kpi-program-plan') }}" method="post">
                    @csrf
                    <div class="form-group">
                        <label for="exampleFormControlSelect1">Pilih Item</label>
                        <select name="id_program_plan_update" class="form-control" id="exampleFormControlSelect1">
                            @forelse ($data_drop_update as $item)
                                  <option value="{{ $item->id }}">{{ $item->program }}</option>
                               @empty
                                   <td colspan="18"><h3 class="text-center">No Data Inputed</h3></td>
                               @endforelse
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlSelect1">Konfirmasi Pilihan</label>
                        <select name="kpi_program_plan_id" class="form-control" id="exampleFormControlSelect1">
                            @forelse ($data_drop as $item)
                                  <option value="{{ $item->id }}">{{ $item->program }}</option>
                               @empty
                                   <td colspan="18"><h3 class="text-center">No Data Inputed</h3></td>
                               @endforelse
                        </select>
                    </div>

                    <div class="form-group">
                        <table class="table table-bordered">
                            <thead>
                                <th>Jan</th>
                                <th>Feb</th>
                                <th>Mar</th>
                                <th>Apr</th>
                                <th>May</th>
                                <th>Jun</th>
                                <th>Jul</th>
                                <th>Aug</th>
                                <th>Sep</th>
                                <th>Oct</th>
                                <th>Nov</th>
                                <th>Dec</th>
                            </thead>
                            <tbody>

                                @foreach ($dataf as $item)

                                <td><input type="text" name="jan_plan" id="jan_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="feb_plan" id="feb_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="mar_plan" id="mar_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="apr_plan" id="apr_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="may_plan" id="may_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="jun_plan" id="jun_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="jul_plan" id="jul_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="aug_plan" id="aug_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="sep_plan" id="sep_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="oct_plan" id="oct_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="nov_plan" id="nov_plan" style="max-width: 40px"></td>
                                <td><input type="text" name="dec_plan" id="dec_plan" style="max-width: 40px"></td>
                                @endforeach

                            </tbody>
                        </table>
                    </div>
                    <button class="btn btn-primary" type="submit" id="btn-save">Save</button>
                </form>
            </div>
        </div>
        </div>
    </div>
</code>```

and this my ajax :

```<code><script>
  $(document).ready(function($) {
    $('#btn-edit-plan').on('click', function() {
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });
    var id = $(this).data('id');
    console.log(id);

    // ajax
    $.ajax({
        type: "POST",
        url: "{{ url('edit-program-input') }}",
        data: { id: id },
        dataType: 'json',
        success: function(res) {
          $('#new_modal_plan').modal('show');
          $('#jan_plan').val(res.jan);
          $('#feb_plan').val(res.feb);
          $('#mar_plan').val(res.mar);
          $('#apr_plan').val(res.apr);
          $('#may_plan').val(res.may);
          $('#jun_plan').val(res.jun);
          $('#jul_plan').val(res.jul);
          $('#aug_plan').val(res.aug);
          $('#sep_plan').val(res.sep);
          $('#oct_plan').val(res.oct);
          $('#nov_plan').val(res.nov);
          $('#dec_plan').val(res.dec);
        }
      });
    });
  })
</script>
</code>```

答:
The id attribute should be unique for every element in the page. but it is not like this with class attribute.

so update your button:

```<code><a href="javascript:void(0)" class="btn btn-primary edit btn-edit-plan" data-id="{{ $itemd->id }}">Edit</a>
</code>```

and update your jQuery selector to:

```<code>$(document).on('click', '.btn-edit-plan', function() {
  // Your code here
})
</code>```

You can learn more about it here: Difference between class and id in jQuery

Title: Call a modal with data ajax laravel 8

Body:
I have a problem with my app , when i click the edit btn in the table then my modal is showed with data and when i click the second row in the table then my modal is not show.

this my controller :

public function edit_kpi_program_plan(Request $request)
{
    $data = kpi_input_program::where('id' , $request->id)->first();

    return response()->json($data, 200);
}

this my route :

Route::post('/edit-program-input', [InputController::class, 'edit_kpi_program_plan'])->name('edit.program');

this my button in blade:

id }}">Edit

this my modal in blade:

Input Program Plan

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

                <form action="{{ route('update-kpi-program-plan') }}" method="post">
                    @csrf

                        Pilih Item
                        <select name="id_program_plan_update" class="form-control" id="exampleFormControlSelect1">
                            @forelse ($data_drop_update as $item)
                                  <option value="{{ $item->id }}">{{ $item->program }}</option>
                               @empty

No Data Inputed

                               @endforelse
                        </select>

                        Konfirmasi Pilihan
                        <select name="kpi_program_plan_id" class="form-control" id="exampleFormControlSelect1">
                            @forelse ($data_drop as $item)
                                  <option value="{{ $item->id }}">{{ $item->program }}</option>
                               @empty

No Data Inputed

                               @endforelse
                        </select>

                                Jan
                                Feb
                                Mar
                                Apr
                                May
                                Jun
                                Jul
                                Aug
                                Sep
                                Oct
                                Nov
                                Dec

                                @foreach ($dataf as $item)

                                <input type="text" name="jan_plan" id="jan_plan" style="max-width: 40px">
                                <input type="text" name="feb_plan" id="feb_plan" style="max-width: 40px">
                                <input type="text" name="mar_plan" id="mar_plan" style="max-width: 40px">
                                <input type="text" name="apr_plan" id="apr_plan" style="max-width: 40px">
                                <input type="text" name="may_plan" id="may_plan" style="max-width: 40px">
                                <input type="text" name="jun_plan" id="jun_plan" style="max-width: 40px">
                                <input type="text" name="jul_plan" id="jul_plan" style="max-width: 40px">
                                <input type="text" name="aug_plan" id="aug_plan" style="max-width: 40px">
                                <input type="text" name="sep_plan" id="sep_plan" style="max-width: 40px">
                                <input type="text" name="oct_plan" id="oct_plan" style="max-width: 40px">
                                <input type="text" name="nov_plan" id="nov_plan" style="max-width: 40px">
                                <input type="text" name="dec_plan" id="dec_plan" style="max-width: 40px">
                                @endforeach

                    <button class="btn btn-primary" type="submit" id="btn-save">Save</button>
                </form>

and this my ajax :

Body:
The id attribute should be unique for every element in the page. but it is not like this with class attribute.

so update your button:

<a href="javascript:void(0)" class="btn btn-primary edit btn-edit-plan" data-id="{{ $itemd->id }}">Edit</a>

and update your jQuery selector to:

$(document).on('click', '.btn-edit-plan', function() {
  // Your code here
})

You can learn more about it here: Difference between class and id in jQuery


问:
How make a bot delete Discord channel messages that start with or are from a bot
I have a bot in my Discord server for playing music. As it works with commands, and it answers if there is something like a playlist the channel is spammed with songs or messages that later on are meaningless. So I want the bot that each time it leaves a voice channel, it clears the command messages that were sent to it and the answer messages that it sent.

So I have looked around a bit and came to this code but it doesnt work. I added some console logs to see up where it goes in, and it reaches FLAG 1 but not FLAG 2. So what is wrong in that condition? PREFIX is the "!" that commands start with, and 0123456789 is the bot ID

```<code>else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
        const channel = msg.channel;
        const messageManager = channel.messages;
        messageManager.fetch({ limit: 100 }).then((messages) => {
             messages.forEach((message) => {
                 console.log("FLAG 1: "+ util.inspect(message))
                 if ( (message.content.startWith(PREFIX)) || (message.author.id == 0123456789)) {
                     console.log("FLAG 2: "+ util.inspect(message))
                     message.delete();
                 }
             });
        });

}
</code>```

Thanks in advance

答:
Two things here: startWith should actually be startsWith since you didn't mention any errors I'll assume this is just a typo from the example code.

Second, message.author.id == 0123456789 won't work since IDs should be strings, not numbers.

Body:
I have a bot in my Discord server for playing music. As it works with commands, and it answers if there is something like a playlist the channel is spammed with songs or messages that later on are meaningless. So I want the bot that each time it leaves a voice channel, it clears the command messages that were sent to it and the answer messages that it sent.

So I have looked around a bit and came to this code but it doesnt work. I added some console logs to see up where it goes in, and it reaches FLAG 1 but not FLAG 2. So what is wrong in that condition? PREFIX is the "!" that commands start with, and 0123456789 is the bot ID

else if (msg.content.trim().toLowerCase() == _CMD_LEAVE) {
        const channel = msg.channel;
        const messageManager = channel.messages;
        messageManager.fetch({ limit: 100 }).then((messages) => {
             messages.forEach((message) => {
                 console.log("FLAG 1: "+ util.inspect(message))
                 if ( (message.content.startWith(PREFIX)) || (message.author.id == 0123456789)) {
                     console.log("FLAG 2: "+ util.inspect(message))
                     message.delete();
                 }
             });
        });

}

Thanks in advance


问:
Jenkins disables project builds on branches after a pull request is issued
Note: I only have Jenkinsfile set up in one of my branches, not the master.

I have setup Git webhooks to monitor push events to my Github repository. However, I am noticing that my Jenkins builds are working fine (picking up push events, triggering builds) as branches, but after a pull request is issued, my branch build gets disabled in the Branches tab of my project.

However, I do see the new PR listed in my Pull Requests tab. But now, when I push to Github, the new commits are not triggering builds anymore. In my branches tab, my old branch is now crossed out.

How do I force Jenkins to keep building my branches? I would like to continue building from a branch, even if a PR has been issued.

答: I guess if change your configuration of Behaviours by changing discover branches' strategy to All Branches then your issue might get fixed. By default it is set as Exclude Branches that are also filed as PRs</p>


问:
Docker build failed in SPA React with Asp Core Project
My Docker File

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

```<code>FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y libpng-dev libjpeg-dev curl libxi6 build-essential libgl1-mesa-glx
RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y libpng-dev libjpeg-dev curl libxi6 build-essential libgl1-mesa-glx
RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs
WORKDIR /src
COPY ["LT-Service/LT-Service.csproj", "LT-Service/"]
COPY ["DAL/DAL.csproj", "DAL/"]
RUN dotnet restore "LT-Service/LT-Service.csproj"
COPY . .
WORKDIR "/src/LT-Service"
RUN dotnet build "LT-Service.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "LT-Service.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "LT-Service.dll"]
</code>```

error MSB3644: The reference assemblies for .NETFramework,Version=v4.7.2 were not found.

答: Your app targets .NET framework which is Windows only, so you can't run it in a Linux container. Based on the images you use, you should target .NET 5.</p>

Body:
My Docker File

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y libpng-dev libjpeg-dev curl libxi6 build-essential libgl1-mesa-glx
RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y libpng-dev libjpeg-dev curl libxi6 build-essential libgl1-mesa-glx
RUN curl -sL https://deb.nodesource.com/setup_lts.x | bash -
RUN apt-get install -y nodejs
WORKDIR /src
COPY ["LT-Service/LT-Service.csproj", "LT-Service/"]
COPY ["DAL/DAL.csproj", "DAL/"]
RUN dotnet restore "LT-Service/LT-Service.csproj"
COPY . .
WORKDIR "/src/LT-Service"
RUN dotnet build "LT-Service.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "LT-Service.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "LT-Service.dll"]

error MSB3644: The reference assemblies for .NETFramework,Version=v4.7.2 were not found.


问:
Python Pandas read_excel() module not found
I'm currently trying to use pandas.read_excel() to import an .xlsx file using this basic script

```<code>import pandas as pd
x = pd.read_excel("crypt_db.xlsx", "sheet1")
</code>```

and I get a module ('read_excel') not found error. Could I get some help on this?

My pandas is updated to the latest version.

Thank you for your help

Full traceback

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'read_excel'
</code>```

答:
This did the trick for me:

```<code>#import player regular season
df = pd.read_excel ("Player-Data-Set/NBA-Player-Statistics-season.xlsx", [0,1,2,3,4])
</code>```

Thank you Chanda Korat your post put me on the right track

ContentLicense: CC BY-SA 3.0

Body:
I'm currently trying to use pandas.read_excel() to import an .xlsx file using this basic script

import pandas as pd
x = pd.read_excel("crypt_db.xlsx", "sheet1")

and I get a module ('read_excel') not found error. Could I get some help on this?

My pandas is updated to the latest version.

Thank you for your help

Full traceback

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'read_excel'

Body:
This did the trick for me:

#import player regular season
df = pd.read_excel ("Player-Data-Set/NBA-Player-Statistics-season.xlsx", [0,1,2,3,4])

Thank you Chanda Korat your post put me on the right track


问:
IEnumerable<T> from Enumerable.FromRange().Select() vs ToList()
This really stumped me, as I expected 'pass by reference' behavior.  I expected this code to print "5,5,5", but instead it prints "7,7,7".

```<code>IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}
</code>```

Whereas this prints "7,7,7" as expected.

```<code>IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 }).ToList();
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}
</code>```

Obviously this is a simplified version of the actual code I was writing.  This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object.  Here I understand why I would get a new instance every time I reference Mine.

```<code>public MyObj Mine => new MyObj();
</code>```

I was just very surprised to see this behavior in the above code, where it feels more like I've "locked in" the enumerated objects.  Can anyone help me understand this?

答:
This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object

Your feelings are correct

As a preface to this answer I want to point out that in C# we can store methods inside variables like we can store data:

```<code>var method = () => new MyObj();
</code>```

The () => new MyObj() is the "method"; it has no name, takes no parameters and returns a new MyObj. We don't actually refer to it as a method, we tend to call it a lambda, but for all intents and purposes it behaves like what you're familiar with as "a method":

```<code>public MyObj SomeName(){
    return new MyObj();
}
</code>```

You can probably pick out the common parts- the compiler guesses the return type, provides a name for it internally because we don't care and when it's a single statement that produces a value, the compiles fills in the return keyword for us too. It's a very compact method logic.

So, back to this variable called method:

```<code>var method = () => new MyObj();
</code>```

You could run it like:

```<code>var myObj = method.Invoke();
</code>```

You could even remove the Invoke word and just write method(), but I'll leave Invoke in for now, for clarity. When invoked the method will run, return a new MyObj data and that data would be stored in myObj..

So, most times when we code, a variable stores data but sometimes it stores a method, and this is handy..

When you make a LINQ Select it requires you to give it a method that it will run every time the resulting enumerable is enumerated:

```<code>var enumerable = new []{1,2,3}.Select(x => new MyObj());
</code>```

It doesn't run the method x => new MyObj() you give at the time you call Select, it doesn't generate any data; it just stores the method for later

Every time you loop over (enumerate) this it will run that method (x => new MyObj()) up to 3 times - I say up to, because you don't have to fully enumerate but if you do, there are 3 elements in the array so the enumeration can cause at most 3 invocations of the method.

LINQ Select doesn't run the method and grab the data - it effectively creates a collection of data-providing methods rather than a collection of data

Conceptually it's like Select produces you an array of full of methods:

```<code>var enumerable = new[]{
  () => new MyObj(),
  () => new MyObj(),
  () => new MyObj()
};
</code>```

You could enumerate this and run these methods yourself:

```<code>foreach(var method in enumerable)
  method.Invoke();
</code>```

Your Alter() ran the enumeration (did a loop), got each new object returned from each method, modified it, then it was thrown away. Conceptually your Alter method did this:

```<code>foreach(var method in enumerable)
  method.Invoke().Name = 5;
</code>```

The method was run, a new MyObj was made with some default value for Name, then Name was changed to 5, then the object data was thrown away

After your Alter was done with you enumerated it again, new objects were made again because the methods were run again, the Name was of course unaltered - new object, no changes. Nothing here is geared up to remember the data being generated; the only thing that is remembered is the list of methods that generate the data

When you put a ToList() on the end, that's different - ToList internally enumerates the enumerable, causes the methods that generate the objects to be run but critically it stashes the resulting objects in a list and gives you the list of objects. Instead of being a collection of methods that provides values, it's a collection of values that you can alter.

It's like it does this:

```<code>var r = new List<MyObj>();

foreach(var method in enumerable)
  r.Add(method.Invoke());

return r;
</code>```

This means you get a list of data back (not a list of methods that provide data), and if you then loop ovet this list you're altering data that is stored in the list, rather than running methods, altering the returned value and throwing it away

Body:
This really stumped me, as I expected 'pass by reference' behavior.  I expected this code to print "5,5,5", but instead it prints "7,7,7".

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Whereas this prints "7,7,7" as expected.

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 }).ToList();
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Obviously this is a simplified version of the actual code I was writing.  This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object.  Here I understand why I would get a new instance every time I reference Mine.

public MyObj Mine => new MyObj();

I was just very surprised to see this behavior in the above code, where it feels more like I've "locked in" the enumerated objects.  Can anyone help me understand this?

Body:
This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object

Your feelings are correct

As a preface to this answer I want to point out that in C# we can store methods inside variables like we can store data:

var method = () => new MyObj();

The () => new MyObj() is the "method"; it has no name, takes no parameters and returns a new MyObj. We don't actually refer to it as a method, we tend to call it a lambda, but for all intents and purposes it behaves like what you're familiar with as "a method":

public MyObj SomeName(){
    return new MyObj();
}

You can probably pick out the common parts- the compiler guesses the return type, provides a name for it internally because we don't care and when it's a single statement that produces a value, the compiles fills in the return keyword for us too. It's a very compact method logic.

So, back to this variable called method:

var method = () => new MyObj();

You could run it like:

var myObj = method.Invoke();

You could even remove the Invoke word and just write method(), but I'll leave Invoke in for now, for clarity. When invoked the method will run, return a new MyObj data and that data would be stored in myObj..

So, most times when we code, a variable stores data but sometimes it stores a method, and this is handy..

When you make a LINQ Select it requires you to give it a method that it will run every time the resulting enumerable is enumerated:

var enumerable = new []{1,2,3}.Select(x => new MyObj());

It doesn't run the method x => new MyObj() you give at the time you call Select, it doesn't generate any data; it just stores the method for later

Every time you loop over (enumerate) this it will run that method (x => new MyObj()) up to 3 times - I say up to, because you don't have to fully enumerate but if you do, there are 3 elements in the array so the enumeration can cause at most 3 invocations of the method.

LINQ Select doesn't run the method and grab the data - it effectively creates a collection of data-providing methods rather than a collection of data

Conceptually it's like Select produces you an array of full of methods:

var enumerable = new[]{
  () => new MyObj(),
  () => new MyObj(),
  () => new MyObj()
};

You could enumerate this and run these methods yourself:

foreach(var method in enumerable)
  method.Invoke();

Your Alter() ran the enumeration (did a loop), got each new object returned from each method, modified it, then it was thrown away. Conceptually your Alter method did this:

foreach(var method in enumerable)
  method.Invoke().Name = 5;

The method was run, a new MyObj was made with some default value for Name, then Name was changed to 5, then the object data was thrown away

After your Alter was done with you enumerated it again, new objects were made again because the methods were run again, the Name was of course unaltered - new object, no changes. Nothing here is geared up to remember the data being generated; the only thing that is remembered is the list of methods that generate the data

When you put a ToList() on the end, that's different - ToList internally enumerates the enumerable, causes the methods that generate the objects to be run but critically it stashes the resulting objects in a list and gives you the list of objects. Instead of being a collection of methods that provides values, it's a collection of values that you can alter.

It's like it does this:

var r = new List<MyObj>();

foreach(var method in enumerable)
  r.Add(method.Invoke());

return r;

This means you get a list of data back (not a list of methods that provide data), and if you then loop ovet this list you're altering data that is stored in the list, rather than running methods, altering the returned value and throwing it away


问:
AES-256-CTR decryption in Golang
I have difficulties to decrypt payload with AES-256-CTR in Golang

Format:

```<code>A zero IV.
Not padded.
</code>```

Input:

```<code>func main() {
encryptedKey := []byte{196, 231, 38, 149, 234, 51, 142, 186, 230, 214, 96, 243, 229, 153, 103, 74, 117, 241, 237, 135, 91, 170, 216, 167, 235, 154, 180, 28, 125, 48, 82, 44}
encryptedData := "bj4hUUJtwIZJnnGYO+04JpIxf1Omnsrq+ilLv+eQXSEbvsEKgD9BZ0cnxGBrvd4KHeyHkoiZZbObDkZemFtQkgo0jw1AtscTv4HSIz9OeOFZmNjjA724dA8oyuHY8WWlFddXcArqv4R5a9DO2Qs4e9sk3KIRYn4OJH//lNi8t111J//wcsSTvuer+EO9XeQIZHsZ4sr+fhdU1Jxz7Z1KOM6c2MGuXAqfKj/ebn01XA/LgnaDO8xZ+k7vs19WY0pH33HM0K5K1C+XUVaRGhUtFt2BDgnG5T/MPIyVlfUpJpHJjEdsvTxTN7muK9UsbSonr3XAp9oV/w7xx65N5iEEjvC1CaehAnKOSM6QiyKs8KLiv2vHaabsNNusFZgHUZYUApErbpK9g3UR0744Sy8hVe/l75SmOofZvu59vU509MMc8TdqxssIv2g7JTw="
plaintext, err := Decode(encryptedKey, encryptedData)
if err != nil {
    fmt.Errorf("an error occured while decrypting: %s", err.Error())
}
fmt.Printf("in hex format: %x", plaintext)
}

func Decode(encryptionKey []byte, encryptedData string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
    return nil, err
}
block, err := aes.NewCipher(encryptionKey)
if err != nil {
    return nil, err
}
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCTR(block, iv)
plaintext := make([]byte, len(ciphertext)-aes.BlockSize)
stream.XORKeyStream(plaintext, ciphertext[aes.BlockSize:])
return plaintext, nil
}
</code>```

Output:

15affcc3abb646bbf776136d0dc4a37c1e70c3433f9df8a9f7434b74992c25316d78405deffdbf964bb7e9229f9185b85bcf253bb3dcddb782872e018a1aed84414aaf5bc76af8d8accaf6137758d72322d09a7f56a9b57afc22a1b36cf84f24dc558b6654c69875cfb3b753c765794d22765b6f47f7a5c2b8a1822cbae4e2b66e8d413cdb5631a5a39fc435681bc139d01b06034faca8d7cc1677a4209f7e4fe9b746d7b530e54604a0cd2af2475837083823381626d9e3bfcaa6e531d9125ad851deb34c2d42363e3de5e3ac93bf66b3b2e506c57f1068c41c70a9dfe0d4d131f45ed6d2514a1ec273850c7a51982d31d0e68a785b5eceff141be88512b7eed66bb20d510bdc9ec12095c8e445699325c2cee9e52dec8e8e05359330bc946e6e5e5279acd84369394867d37b2002205f5883f4a281c9123ef6d1ab

Expected output:

7b226d65737361676545787069726174696f6e223a2231363434383331333036303037222c226d6573736167654964223a22414832456a74635157674c4f31364b415a702d316f6e5f353954386a58736f356135305064426f555f39664e737a396e763533376c6c52674e70345a4e4a5536754177714d7845646e50625a6c69753656666568665150366d514534326448544b4b5f6f6f765a74316a30796c6a7a424778424743326f7333655f33654b6f503463745a4b65694139767637222c227061796d656e744d6574686f64223a2243415244222c227061796d656e744d6574686f6444657461696c73223a7b2265787069726174696f6e59656172223a323032372c2265787069726174696f6e4d6f6e7468223a31322c2270616e223a2234313131313131313131313131313131222c22617574684d6574686f64223a2250414e5f4f4e4c59227d7d

Sample sandbox

答:
Since your IV is 0, you need to set iv and plaintext as:

```<code>    iv := make([]byte, aes.BlockSize)
</code>```

and

```<code>    plaintext := make([]byte, len(ciphertext))
</code>```

which yields the expected output.

See https://go.dev/play/p/X3ifo26irH5

Title: AES-256-CTR decryption in Golang

Body:
I have difficulties to decrypt payload with AES-256-CTR in Golang

Format:

A zero IV.
Not padded.

Input:

func main() {
encryptedKey := []byte{196, 231, 38, 149, 234, 51, 142, 186, 230, 214, 96, 243, 229, 153, 103, 74, 117, 241, 237, 135, 91, 170, 216, 167, 235, 154, 180, 28, 125, 48, 82, 44}
encryptedData := "bj4hUUJtwIZJnnGYO+04JpIxf1Omnsrq+ilLv+eQXSEbvsEKgD9BZ0cnxGBrvd4KHeyHkoiZZbObDkZemFtQkgo0jw1AtscTv4HSIz9OeOFZmNjjA724dA8oyuHY8WWlFddXcArqv4R5a9DO2Qs4e9sk3KIRYn4OJH//lNi8t111J//wcsSTvuer+EO9XeQIZHsZ4sr+fhdU1Jxz7Z1KOM6c2MGuXAqfKj/ebn01XA/LgnaDO8xZ+k7vs19WY0pH33HM0K5K1C+XUVaRGhUtFt2BDgnG5T/MPIyVlfUpJpHJjEdsvTxTN7muK9UsbSonr3XAp9oV/w7xx65N5iEEjvC1CaehAnKOSM6QiyKs8KLiv2vHaabsNNusFZgHUZYUApErbpK9g3UR0744Sy8hVe/l75SmOofZvu59vU509MMc8TdqxssIv2g7JTw="
plaintext, err := Decode(encryptedKey, encryptedData)
if err != nil {
    fmt.Errorf("an error occured while decrypting: %s", err.Error())
}
fmt.Printf("in hex format: %x", plaintext)
}

func Decode(encryptionKey []byte, encryptedData string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
    return nil, err
}
block, err := aes.NewCipher(encryptionKey)
if err != nil {
    return nil, err
}
iv := ciphertext[:aes.BlockSize]
stream := cipher.NewCTR(block, iv)
plaintext := make([]byte, len(ciphertext)-aes.BlockSize)
stream.XORKeyStream(plaintext, ciphertext[aes.BlockSize:])
return plaintext, nil
}

Output:

15affcc3abb646bbf776136d0dc4a37c1e70c3433f9df8a9f7434b74992c25316d78405deffdbf964bb7e9229f9185b85bcf253bb3dcddb782872e018a1aed84414aaf5bc76af8d8accaf6137758d72322d09a7f56a9b57afc22a1b36cf84f24dc558b6654c69875cfb3b753c765794d22765b6f47f7a5c2b8a1822cbae4e2b66e8d413cdb5631a5a39fc435681bc139d01b06034faca8d7cc1677a4209f7e4fe9b746d7b530e54604a0cd2af2475837083823381626d9e3bfcaa6e531d9125ad851deb34c2d42363e3de5e3ac93bf66b3b2e506c57f1068c41c70a9dfe0d4d131f45ed6d2514a1ec273850c7a51982d31d0e68a785b5eceff141be88512b7eed66bb20d510bdc9ec12095c8e445699325c2cee9e52dec8e8e05359330bc946e6e5e5279acd84369394867d37b2002205f5883f4a281c9123ef6d1ab

Expected output:

7b226d65737361676545787069726174696f6e223a2231363434383331333036303037222c226d6573736167654964223a22414832456a74635157674c4f31364b415a702d316f6e5f353954386a58736f356135305064426f555f39664e737a396e763533376c6c52674e70345a4e4a5536754177714d7845646e50625a6c69753656666568665150366d514534326448544b4b5f6f6f765a74316a30796c6a7a424778424743326f7333655f33654b6f503463745a4b65694139767637222c227061796d656e744d6574686f64223a2243415244222c227061796d656e744d6574686f6444657461696c73223a7b2265787069726174696f6e59656172223a323032372c2265787069726174696f6e4d6f6e7468223a31322c2270616e223a2234313131313131313131313131313131222c22617574684d6574686f64223a2250414e5f4f4e4c59227d7d

Sample sandbox

Body:
Since your IV is 0, you need to set iv and plaintext as:

    iv := make([]byte, aes.BlockSize)

and

    plaintext := make([]byte, len(ciphertext))

which yields the expected output.

See https://go.dev/play/p/X3ifo26irH5


问:
Entity Framework & MVC Models
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

```<code>     public ActionResult Create(EFModels.User user)    {    }
</code>```

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

```<code>namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}
</code>```

//MVC Model Class

```<code>namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}
</code>```

//MVC VIEW PAGE

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>User</h2>
  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>
        </div>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
</asp:Content>
</code>```

//Controller Method

```<code> public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }
</code>```

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

答:
Automapper should work. We use it all the time even with different property names. Please post usage of automapper that does not work for you. Otherwise see following post to make it work with different property names.

Usage of Automapper when property names are different

Title: Entity Framework & MVC Models

Body:
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}

//MVC Model Class

namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}

//MVC VIEW PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

User

  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>

            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>

            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>

            <input type="submit" value="Create" />

    </fieldset>
    <% } %>
</asp:Content>

//Controller Method

 public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???


问:
Profiling JAX code: What is redzone_checker and why does it take so much time?
I have found this post but am still unclear on what the redzone_checker kernel is doing and why. Specifically, should it be taking > 90% of my application's runtime? TensorBoard reports that it is taking the vast majority of the runtime of my JAX code, and I'd like to know

Is it actually the case that this kernel is taking way too much time, or is this a side effect of profiling JAX with TensorBoard (i.e., the output is misleading in some way)?

Is there a way to reduce the amount of time taken by the redzone_checker kernel? Is that even a good idea?

Thanks in advance for any insights.

答:
make sure warmup before profiling.

it maybe jit compiling time.


问:
DatePicker New Date type does not match
I'm using react and typescript, and for datepicker I'm using react-dates.

I want to convert the date to unix when I select it, but I get a ts error.

I get a ts error with a startDate of new Date(startDate).getTime() / 1000.

error

```<code>      Type 'null' is not assignable to type 'string | number | Date'.
  Overload 2 of 4, '(value: string | number): Date', gave the following error.
    Argument of type 'Moment | null' is not assignable to parameter of type 'string |
</code>```

number'.
Type 'null' is not assignable to type 'string | number'.ts(2769)

```<code>import { DayPickerRangeController } from "react-dates";
import React, { useState } from "react";
import moment from "moment";

import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const [startDate, setStartDate] = useState<moment.Moment | null>(null);
  const [endDate, setEndDate] = useState<moment.Moment | null>(null);
  const [focusedInput, setFocusedInput] = useState<"startDate" | "endDate">(
    "startDate"
  );

  console.log(new Date(startDate).getTime() / 1000);

  return (
    <DayPickerRangeController
      startDate={startDate}
      endDate={endDate}
      focusedInput={focusedInput}
      numberOfMonths={2}
      onFocusChange={(focusedInput) => {
        console.log(focusedInput, "focusedInput");
      }}
      onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          console.log(selectedDates, "startDate");
          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}
    />
  );
}

</code>```

答:
The error is correct, as you can’t create a new date from a null value. Instead, make the conversion onDatesChange, so that you know you’ll have a date at that point:

onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          console.log(selectedDates, "startDate");
          console.log(new Date(selectedDates.startDate).getTime() / 1000);

          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}
```

Once you can confirm that’s the shape you want it to be, you can create a function convertDateToUnix handling that conversion, so you can reuse it for both start and end dates

Title: DatePicker New Date type does not match

Body:
I'm using react and typescript, and for datepicker I'm using react-dates.

I want to convert the date to unix when I select it, but I get a ts error.

I get a ts error with a startDate of new Date(startDate).getTime() / 1000.

error

      Type 'null' is not assignable to type 'string | number | Date'.
  Overload 2 of 4, '(value: string | number): Date', gave the following error.
    Argument of type 'Moment | null' is not assignable to parameter of type 'string |

number'.
Type 'null' is not assignable to type 'string | number'.ts(2769)

import { DayPickerRangeController } from "react-dates";
import React, { useState } from "react";
import moment from "moment";

import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const [startDate, setStartDate] = useState<moment.Moment | null>(null);
  const [endDate, setEndDate] = useState<moment.Moment | null>(null);
  const [focusedInput, setFocusedInput] = useState<"startDate" | "endDate">(
    "startDate"
  );

  console.log(new Date(startDate).getTime() / 1000);

  return (
    <DayPickerRangeController
      startDate={startDate}
      endDate={endDate}
      focusedInput={focusedInput}
      numberOfMonths={2}
      onFocusChange={(focusedInput) => {
        console.log(focusedInput, "focusedInput");
      }}
      onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          console.log(selectedDates, "startDate");
          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}
    />
  );
}

Body:
The error is correct, as you can’t create a new date from a null value. Instead, make the conversion onDatesChange, so that you know you’ll have a date at that point:

onDatesChange={(selectedDates) => {
        if (focusedInput === "startDate") {
          console.log(selectedDates, "startDate");
          console.log(new Date(selectedDates.startDate).getTime() / 1000);

          setStartDate(selectedDates.startDate);
        } else {
          setEndDate(selectedDates.endDate);
        }
      }}

Once you can confirm that’s the shape you want it to be, you can create a function convertDateToUnix handling that conversion, so you can reuse it for both start and end dates


问:
How do you pass a struct that contains a String reference between threads?
In the following code snippet I am trying to create a tuple that contains a String value and a struct that contains an attribute that is set as the reference to the first value (which would be the String) in the tuple.

My question is how do I make the String (which is the first value in the tuple) live long enough.

Here is the code:

```<code>#[derive(Debug, Clone)]
struct RefTestStruct {
    key: usize,
    ref_value: Option<&'static str>,
}

fn init3<'a>( cache: &Arc<Mutex<HashMap<usize, (String, Option<RefTestStruct>)>>> ) {
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        //create reference copy of cache
        let cache_clone = Arc::clone(cache);

        let handle = thread::spawn(move || {
                //lock cache
                let mut locked_cache = cache_clone.lock().unwrap();

                // add new object to cache
                let tuple_value = (format!("value: {}", idx), None );
                let mut ts_obj =
                    RefTestStruct {
                        key: idx,
                        ref_value: Some( tuple_value.0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);
                locked_cache.insert(idx as usize, tuple_value);

                println!("IDX: {} - CACHE: {:?}", idx, locked_cache.get( &(idx as usize) ).unwrap() )
            });

        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("\n");
}

fn main() {
    // init
    let cache = HashMap::<usize, (String, Option<RefTestStruct>)>::new();
    let am_cache = Arc::new(Mutex::new(cache));

    init3(&am_cache);

    // change cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let mut locked_cache = cache_clone.lock().unwrap();
                let tuple_value = locked_cache.get_mut( &(idx as usize) ).unwrap();
                (*tuple_value).0 = format!("changed value: {}", (*tuple_value).1.unwrap().key + 11);
                let ts_obj =
                    RefTestStruct {
                        key: (*tuple_value).1.unwrap().key,
                        ref_value: Some( (*tuple_value).0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);

                // locked_cache.insert(idx as usize, tuple_value);

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    // display cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let locked_cache = cache_clone.lock().unwrap();
                let ts_obj = locked_cache.get( &(idx as usize) ).unwrap();

                println!("IDX: {} - CACHE: {:?}", idx, &ts_obj );

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

}
</code>```

ERROR:

error[E0597]: `tuple_value.0` does not live long enough
   --> src\main.rs:215:42
    |
215 |                         ref_value: Some( tuple_value.0.as_str() ),
    |                                          ^^^^^^^^^^^^^^^^^^^^^^
    |                                          |
    |                                          borrowed value does not live long enough
    |                                          argument requires that `tuple_value.0` is borrowed for `'static`
...
221 |             });
    |             - `tuple_value.0` dropped here while still borrowed
```

答:
How do you pass a struct that contains a String reference between threads?

First I answer the question in the caption and ignore the program you posted (And I'll try to ignore my itch to guess what you really want to do.)

I'll assume, you want to avoid unsafe in your own code. (So dependencies with unsafe code might be ok.)

To pass a reference to a thread, the reference has to live as long as the thread will live.

Your options:

Have a 'static lifetime on your reference.

Use threads which have a non 'static lifetime.

Regarding 1. have a 'static lifetime on the reference.

So now the questions changed into, how to obtain a reference to
a String with 'static lifetime.

We can't use a constant, as we can't initialize it.

This leaves us with the possibility to Box the String and leak it.

But of course, this leaks memory, as the String can't be dropped any more. Also you get a &'mut String out
of it, so only one thread can have it at a time and after being
done with it, pass it on. So to me it looks like it is essentially
the same you could do with the owned value of type String too,
so why bother and risk the memory leak. (Putting a Arc<Mutex<..>> around it, is also "same you coud do with the owned value".).

Other methods might exist, which I am not aware of.

Regarding 2. Use threads which have a non `'static' lifetime.

These are called scoped threads and guarantee, that the thread exits,
before the lifetime ends. These are not in standard rust yet, but there
are crates implementing those (I guess using unsafe).

For example crossbeam offers an implementation of this.

Looking at your program though, I guess you want to have long lived
threads.

The program you posted and what you probably want to achieve.

The program you posted has a different issue besides.

You try to create a self referential value in your cache. As far as I know, this is not possible in rust, without using a shared ownership tool, like Arc.

If you try to use a plain Arc, the access would be read only and users of the cache could only change, which String the cache entry points to, but not the "pointed to" String itself.

So If one user replaced the Arc<String> in the cache, other threads would still have a reference to the "old" String and don't see the changed value. But I guess that is what you want to achieve.

But that is a conceptual problem, you can't have unsynchronized read access to a value, which can then be mutated concurrently (by whatever means).

So, if you want to have the ability to change the value with all prior users being able to see it, this leaves you with Mutex or RWLock depending on the access pattern, you are anticipating.

A solution using Arc<String> with the aforementioned defects:

```<code>use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};

#[derive(Debug, Clone)]
struct RefTestStruct {
    key: usize,
    _ref_value: Arc<String>,
}

type Cache = HashMap<usize, (Arc<String>, RefTestStruct)>;
type AmCache = Arc<Mutex<Cache>>;

fn init3(cache: &AmCache) {
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        //create reference copy of cache
        let cache_clone = Arc::clone(cache);

        let handle = thread::spawn(move || {
            //lock cache
            let mut locked_cache = cache_clone.lock().unwrap();

            // add new object to cache
            let s = Arc::new(format!("value: {}", idx));
            let ref_struct = RefTestStruct {
                key: idx,
                _ref_value: s.clone(),
            };
            let tuple_value = (s, ref_struct);
            locked_cache.insert(idx, tuple_value);

            println!(
                "IDX: {} - CACHE: {:?}",
                idx,
                locked_cache.get(&idx).unwrap()
            )
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("\n");
}

fn main() {
    // init
    let cache = Cache::new();
    let am_cache = Arc::new(Mutex::new(cache));

    init3(&am_cache);

    // change cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
            let mut locked_cache = cache_clone.lock().unwrap();
            let tuple_value = locked_cache.get_mut(&idx).unwrap();
            let new_key = tuple_value.1.key + 11;
            let new_s = Arc::new(format!("changed value: {}", new_key));
            (*tuple_value).1 = RefTestStruct {
                key: new_key,
                _ref_value: new_s.clone(),
            };
            (*tuple_value).0 = new_s;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // display cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
            let locked_cache = cache_clone.lock().unwrap();
            let ts_obj = locked_cache.get(&idx).unwrap();

            println!("IDX: {} - CACHE: {:?}", idx, &ts_obj);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}
</code>```

I am sure it is not difficult to derive the Arc<Mutex<String>> version from that, if desired.

That would not be as pointless, as one might think. The Mutex around the cache protects the HashMap for insertion and deletion. And the Mutex around the String values, protects the string values themselves and can be locked indepently of the Mutex around the HashMap. Usual caveats apply, if you ever need both locks at the same time, lock them in the same order always, or risk a deadlock.

Body:
In the following code snippet I am trying to create a tuple that contains a String value and a struct that contains an attribute that is set as the reference to the first value (which would be the String) in the tuple.

My question is how do I make the String (which is the first value in the tuple) live long enough.

Here is the code:

#[derive(Debug, Clone)]
struct RefTestStruct {
    key: usize,
    ref_value: Option<&'static str>,
}

fn init3<'a>( cache: &Arc<Mutex<HashMap<usize, (String, Option<RefTestStruct>)>>> ) {
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        //create reference copy of cache
        let cache_clone = Arc::clone(cache);

        let handle = thread::spawn(move || {
                //lock cache
                let mut locked_cache = cache_clone.lock().unwrap();

                // add new object to cache
                let tuple_value = (format!("value: {}", idx), None );
                let mut ts_obj =
                    RefTestStruct {
                        key: idx,
                        ref_value: Some( tuple_value.0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);
                locked_cache.insert(idx as usize, tuple_value);

                println!("IDX: {} - CACHE: {:?}", idx, locked_cache.get( &(idx as usize) ).unwrap() )
            });

        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("\n");
}

fn main() {
    // init
    let cache = HashMap::<usize, (String, Option<RefTestStruct>)>::new();
    let am_cache = Arc::new(Mutex::new(cache));

    init3(&am_cache);

    // change cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let mut locked_cache = cache_clone.lock().unwrap();
                let tuple_value = locked_cache.get_mut( &(idx as usize) ).unwrap();
                (*tuple_value).0 = format!("changed value: {}", (*tuple_value).1.unwrap().key + 11);
                let ts_obj =
                    RefTestStruct {
                        key: (*tuple_value).1.unwrap().key,
                        ref_value: Some( (*tuple_value).0.as_str() ),
                    };
                tuple_value.1 = Some(ts_obj);

                // locked_cache.insert(idx as usize, tuple_value);

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

    // display cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10 {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
                let locked_cache = cache_clone.lock().unwrap();
                let ts_obj = locked_cache.get( &(idx as usize) ).unwrap();

                println!("IDX: {} - CACHE: {:?}", idx, &ts_obj );

            });
        handles.push(handle);

    }

    for handle in handles {
        handle.join().unwrap();
    }

}

ERROR:

error[E0597]: `tuple_value.0` does not live long enough
   --> src\main.rs:215:42
    |
215 |                         ref_value: Some( tuple_value.0.as_str() ),
    |                                          ^^^^^^^^^^^^^^^^^^^^^^
    |                                          |
    |                                          borrowed value does not live long enough
    |                                          argument requires that `tuple_value.0` is borrowed for `'static`
...
221 |             });
    |             - `tuple_value.0` dropped here while still borrowed

Body:
How do you pass a struct that contains a String reference between threads?

First I answer the question in the caption and ignore the program you posted (And I'll try to ignore my itch to guess what you really want to do.)

I'll assume, you want to avoid unsafe in your own code. (So dependencies with unsafe code might be ok.)

To pass a reference to a thread, the reference has to live as long as the thread will live.

Your options:

Have a 'static lifetime on your reference.

Use threads which have a non 'static lifetime.

Regarding 1. have a 'static lifetime on the reference.

So now the questions changed into, how to obtain a reference to
a String with 'static lifetime.

We can't use a constant, as we can't initialize it.

This leaves us with the possibility to Box the String and leak it.

But of course, this leaks memory, as the String can't be dropped any more. Also you get a &'mut String out
of it, so only one thread can have it at a time and after being
done with it, pass it on. So to me it looks like it is essentially
the same you could do with the owned value of type String too,
so why bother and risk the memory leak. (Putting a Arc<Mutex<..>> around it, is also "same you coud do with the owned value".).

Other methods might exist, which I am not aware of.

Regarding 2. Use threads which have a non `'static' lifetime.

These are called scoped threads and guarantee, that the thread exits,
before the lifetime ends. These are not in standard rust yet, but there
are crates implementing those (I guess using unsafe).

For example crossbeam offers an implementation of this.

Looking at your program though, I guess you want to have long lived
threads.

The program you posted and what you probably want to achieve.

The program you posted has a different issue besides.

You try to create a self referential value in your cache. As far as I know, this is not possible in rust, without using a shared ownership tool, like Arc.

If you try to use a plain Arc, the access would be read only and users of the cache could only change, which String the cache entry points to, but not the "pointed to" String itself.

So If one user replaced the Arc<String> in the cache, other threads would still have a reference to the "old" String and don't see the changed value. But I guess that is what you want to achieve.

But that is a conceptual problem, you can't have unsynchronized read access to a value, which can then be mutated concurrently (by whatever means).

So, if you want to have the ability to change the value with all prior users being able to see it, this leaves you with Mutex or RWLock depending on the access pattern, you are anticipating.

A solution using Arc<String> with the aforementioned defects:

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};

#[derive(Debug, Clone)]
struct RefTestStruct {
    key: usize,
    _ref_value: Arc<String>,
}

type Cache = HashMap<usize, (Arc<String>, RefTestStruct)>;
type AmCache = Arc<Mutex<Cache>>;

fn init3(cache: &AmCache) {
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        //create reference copy of cache
        let cache_clone = Arc::clone(cache);

        let handle = thread::spawn(move || {
            //lock cache
            let mut locked_cache = cache_clone.lock().unwrap();

            // add new object to cache
            let s = Arc::new(format!("value: {}", idx));
            let ref_struct = RefTestStruct {
                key: idx,
                _ref_value: s.clone(),
            };
            let tuple_value = (s, ref_struct);
            locked_cache.insert(idx, tuple_value);

            println!(
                "IDX: {} - CACHE: {:?}",
                idx,
                locked_cache.get(&idx).unwrap()
            )
        });

        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("\n");
}

fn main() {
    // init
    let cache = Cache::new();
    let am_cache = Arc::new(Mutex::new(cache));

    init3(&am_cache);

    // change cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
            let mut locked_cache = cache_clone.lock().unwrap();
            let tuple_value = locked_cache.get_mut(&idx).unwrap();
            let new_key = tuple_value.1.key + 11;
            let new_s = Arc::new(format!("changed value: {}", new_key));
            (*tuple_value).1 = RefTestStruct {
                key: new_key,
                _ref_value: new_s.clone(),
            };
            (*tuple_value).0 = new_s;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // display cache contents
    let mut handles: Vec<JoinHandle<()>> = vec![];
    for idx in 0..10_usize {
        let cache_clone = Arc::clone(&am_cache);

        let handle = thread::spawn(move || {
            let locked_cache = cache_clone.lock().unwrap();
            let ts_obj = locked_cache.get(&idx).unwrap();

            println!("IDX: {} - CACHE: {:?}", idx, &ts_obj);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

I am sure it is not difficult to derive the Arc<Mutex<String>> version from that, if desired.

That would not be as pointless, as one might think. The Mutex around the cache protects the HashMap for insertion and deletion. And the Mutex around the String values, protects the string values themselves and can be locked indepently of the Mutex around the HashMap. Usual caveats apply, if you ever need both locks at the same time, lock them in the same order always, or risk a deadlock.


问:
Selecting dropdown values using Excel(OpenPyXl) - Selenium-Python
I am having a web application which is having multiple dropdowns. For inputting the values for the other text fields, I am reading the data from excel to comply with data driven testing. But I want to know if it is possible to read the dropdown values also from excel? As of now I have used Xpath to read the dropdown values.

To read the excel I have used the following code

```<code>    wk = openpyxl.load_workbook(FilePath.Test_Data_Path + 'testdata.xlsx')
    sh = wk['user_details']
    rows = sh.max_row
    for i in range(2, rows + 1):
        cell_name = sh.cell(row=i, column=1)
        cell_email = sh.cell(row=i, column=2)
        cell_product = sh.cell(row=i, column=3)
        cell_make = sh.cell(row=i, column=4)
        cell_model = sh.cell(row=i, column=5)
</code>```

To read the dropdown, I have used the following method

```<code>dropdown=driver.find_elements_by_xpath(xpath)
</code>```

答:
Below code may solve your problem:

```<code>wk = openpyxl.load_workbook(FilePath.Test_Data_Path + 'testdata.xlsx')
sh = wk['user_details']
rows = sh.max_row

for i in range(2, rows + 1):
    cell_name = sh.cell(row=i, column=1)
    dropdown = driver.find_element_by_xpath('dropdown_xpath')

    for option in dropdown.find_elements_by_tag_name('option'):
        name = option.text

        if name == cell_name:
           option.click()
           break
</code>```

It will check each option value with our excel value and if it match then option will select

Body:
I am having a web application which is having multiple dropdowns. For inputting the values for the other text fields, I am reading the data from excel to comply with data driven testing. But I want to know if it is possible to read the dropdown values also from excel? As of now I have used Xpath to read the dropdown values.

To read the excel I have used the following code

    wk = openpyxl.load_workbook(FilePath.Test_Data_Path + 'testdata.xlsx')
    sh = wk['user_details']
    rows = sh.max_row
    for i in range(2, rows + 1):
        cell_name = sh.cell(row=i, column=1)
        cell_email = sh.cell(row=i, column=2)
        cell_product = sh.cell(row=i, column=3)
        cell_make = sh.cell(row=i, column=4)
        cell_model = sh.cell(row=i, column=5)

To read the dropdown, I have used the following method

dropdown=driver.find_elements_by_xpath(xpath)

Body:
Below code may solve your problem:

wk = openpyxl.load_workbook(FilePath.Test_Data_Path + 'testdata.xlsx')
sh = wk['user_details']
rows = sh.max_row

for i in range(2, rows + 1):
    cell_name = sh.cell(row=i, column=1)
    dropdown = driver.find_element_by_xpath('dropdown_xpath')

    for option in dropdown.find_elements_by_tag_name('option'):
        name = option.text

        if name == cell_name:
           option.click()
           break

It will check each option value with our excel value and if it match then option will select


问:
How long are requests stored in apache tomcat request queue?
Is there a timeout setting for requests stored in the apache tomcat request queue? If yes, what is the default value for the embedded tomcat in spring boot?</p>

答:
When configuring a web server, it also might be useful to set the server connection timeout. This represents the maximum amount of time the server will wait for the client to make their request after connecting before the connection is closed.
You may specify this property in your application.properties as follows.</p>
```<code>server.connection-timeout=5s
</code>```

Body:
When configuring a web server, it also might be useful to set the server connection timeout. This represents the maximum amount of time the server will wait for the client to make their request after connecting before the connection is closed.
You may specify this property in your application.properties as follows.

server.connection-timeout=5s