问:
How to solve flutter.gradle and flutter.bat error?Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' && flutter.bat error
FAILURE: Build failed with an exception.

Where:

Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991

What went wrong:

Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

答:
In case you're using flutter in command-line, just add -v which will run any flutter command in verbose mode. This should show you the origin of an error.

Like for me I was building with --split-debug-info and the folder I chose did not exist


来源: stackexchange

问:
SQL ignore parenthesis in name field for ORDER BY
I would like rows returned in a MySQL query to be sorted alphabetically by surname for which I have an SQL query like:

```<code>SELECT
  id,
  substring_index(name, ' ', -1) as surname
FROM
  my_table
ORDER BY
  surname asc
</code>```

However, some names have parenthesis to denote some special circumstance such as: Laura Angel (retired)

How can I modify my SQL above to ignore the parenthesised text, to sort by surname alphabetically?

答:
You can use this solution:</p>
```<code>SELECT id,
  substring_index(rtrim(substring_index(name, '(', 1)), ' ', -1) as surname
FROM test.test
ORDER BY
  surname asc;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like rows returned in a MySQL query to be sorted alphabetically by surname for which I have an SQL query like:

SELECT
  id,
  substring_index(name, ' ', -1) as surname
FROM
  my_table
ORDER BY
  surname asc

However, some names have parenthesis to denote some special circumstance such as: Laura Angel (retired)

How can I modify my SQL above to ignore the parenthesised text, to sort by surname alphabetically?

Body:
You can use this solution:

SELECT id,
  substring_index(rtrim(substring_index(name, '(', 1)), ' ', -1) as surname
FROM test.test
ORDER BY
  surname asc;


问:
Spring boot + thymeleaf in IntelliJ: cannot resolve vars
I'm writing a short web form application using spring boot and thymeleaf on IntelliJ, but it seems that in the html file, all fields in the model cannot be resolved. Here is my code:

Controller class:

```<code>@Controller
public class IndexController{

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    @RequestMapping(value="/", method = RequestMethod.POST)
    public String addNewPost(@Valid Post post, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){
            return "index";
        }
        model.addAttribute("title",post.getTitle());
        model.addAttribute("content",post.getContent());
        return "hello";
    }
}
</code>```

Model Class:

```<code>public class Post {

    @Size(min=4, max=35)
    private String title;

    @Size(min=30, max=1000)
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
</code>```

Then is the index.html:

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">

    <title>Spring Framework Leo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>

<h3>Spring Boot and Thymeleaf</h3>

    <form action="#" th:action="@{/}"  th:object="${post}" method="post">
        <table>
            <tr>
                <td>Title:</td>
                <td><input type="text" th:field="*{title}" /></td>
                <td th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Title error message</td>
            </tr>
            <tr>
                <td>Content:</td>
                <td><input type="text" th:field="*{content}" /></td>
                <td th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Content error message</td>
            </tr>
            <tr>
                <td><button type="submit">Submit post</button></td>
            </tr>
        </table>
    </form>
</code>```

There are always red lines under "post", "title"  and "content", but I don't know how to solve it. Is it a problem of IntelliJ or just a problem of my code?

答:
I had the same problem and fixed it (ultimate 2021.3.2).
Intellij has a hard time guessing the type of the attribute(s).

Keep www in the namespace xmlns:th="http://www.thymeleaf.org" otherwise Intellij won't parse thymeleaf tags

If you initialize one model in a controler,

don't use a method's return, declare a variable

```<code>String titre=post.getTitle();
model.addAttribute("title",titre);
</code>```

don't add attributes through sub methods, keep it in the main block

```<code>@GetMapping("/book")
public String ver(Model model) {
...
model.addAttribute("title", title);
return "frontpage";
}
</code>```

and don't use complex operator like the ternary one

```<code>model.addAttribute("titles", titles.size() > 0 ? titles : null);
</code>```

If you initialize 2 or 3 models in you controler,
don't push null values

```<code>model.addAttribute("employees", null);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a short web form application using spring boot and thymeleaf on IntelliJ, but it seems that in the html file, all fields in the model cannot be resolved. Here is my code:

Controller class:

@Controller
public class IndexController{

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    @RequestMapping(value="/", method = RequestMethod.POST)
    public String addNewPost(@Valid Post post, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){
            return "index";
        }
        model.addAttribute("title",post.getTitle());
        model.addAttribute("content",post.getContent());
        return "hello";
    }
}

Model Class:

public class Post {

    @Size(min=4, max=35)
    private String title;

    @Size(min=30, max=1000)
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Then is the index.html:

<!DOCTYPE html>

    <title>Spring Framework Leo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

Spring Boot and Thymeleaf

    <form action="#" th:action="@{/}"  th:object="${post}" method="post">

                Title:
                <input type="text" th:field="*{title}" />
                Title error message

                Content:
                <input type="text" th:field="*{content}" />
                Content error message

                <button type="submit">Submit post</button>

    </form>

There are always red lines under "post", "title"  and "content", but I don't know how to solve it. Is it a problem of IntelliJ or just a problem of my code?

Body:
I had the same problem and fixed it (ultimate 2021.3.2).
Intellij has a hard time guessing the type of the attribute(s).

Keep www in the namespace xmlns:th="http://www.thymeleaf.org" otherwise Intellij won't parse thymeleaf tags

If you initialize one model in a controler,

don't use a method's return, declare a variable

String titre=post.getTitle();
model.addAttribute("title",titre);

don't add attributes through sub methods, keep it in the main block

@GetMapping("/book")
public String ver(Model model) {
...
model.addAttribute("title", title);
return "frontpage";
}

and don't use complex operator like the ternary one

model.addAttribute("titles", titles.size() > 0 ? titles : null);

If you initialize 2 or 3 models in you controler,
don't push null values

model.addAttribute("employees", null);


问:
Provide dependent file in a multi-stage build
I need to read in my application from a file "cert.pem" whose path is a) provided as an argument or b) it is retrieved from the directory of the main application file main.py.

I have created the following dockerfile, but after building and running my application using the image the "cert.pem" file cannot be accessed. Is there a way to read from this file?

```<code>FROM golang:1.17-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o ./bin .

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/bin /app/bin
EXPOSE 3000

CMD ["/app/bin"]
</code>```

The instruction to load the file is the following:

```<code>....
var (
    cert_file = flag.String("cert", "./cert.pem", "File name of x509 certificate")
)
...
func main() {
...
    _, err := ioutil.ReadFile(*cert_file)
...
</code>```

答:
you just have to copy your cert.pem file to the location of the binary in the final stage in docker. Assuming you have the cert file in your docker build context, you run a copy command.

```<code>FROM golang:1.17-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o ./bin .

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/bin /app/bin
COPY cert.pem /app/
EXPOSE 3000

CMD ["/app/bin"]
</code>```

Make sure you set the cert.pem location in your go program as ./cert.pem

Body:
I need to read in my application from a file "cert.pem" whose path is a) provided as an argument or b) it is retrieved from the directory of the main application file main.py.

I have created the following dockerfile, but after building and running my application using the image the "cert.pem" file cannot be accessed. Is there a way to read from this file?

FROM golang:1.17-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o ./bin .

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/bin /app/bin
EXPOSE 3000

CMD ["/app/bin"]

The instruction to load the file is the following:

....
var (
    cert_file = flag.String("cert", "./cert.pem", "File name of x509 certificate")
)
...
func main() {
...
    _, err := ioutil.ReadFile(*cert_file)
...

Body:
you just have to copy your cert.pem file to the location of the binary in the final stage in docker. Assuming you have the cert file in your docker build context, you run a copy command.

FROM golang:1.17-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY . .
RUN go mod download
RUN go build -o ./bin .

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/bin /app/bin
COPY cert.pem /app/
EXPOSE 3000

CMD ["/app/bin"]

Make sure you set the cert.pem location in your go program as ./cert.pem


问:
How can I pass the `Graphql` mutation query in cypress req and get the data back in response?
How can I pass the Graphql mutation query in cypress req and get the data back in the response ?
I am getting an error like Validation error of type FieldUndefined: Field 'mutation' in type Query undefined @CreateOrganizationTeam '

```<code>let author = 'Main Author';
let teamname = 'Green Team';
let query = `mutation CreateOrganizationTeam($input: {category: "", author:${author}, isActive: false, orgId: 10, teamName: ${teamname}}) {
  createOrganizationTeam(input: $input) {
    author
    isActive
    teamName
  }
}`;

/* Cypress test to verify the GraphQl response data  */
Then('I access the graphQL end point', () => {
  cy.request({
    method: 'POST',
    url: 'https://some-end-point/api',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      query,
      variables: {
        input: {
          author,
          isActive,
          teamName,
        }
      }
    })
  }).then((response)=>{
    console.log("GraphQL resp output:"+response.body.data);
  });
});
</code>```

答:
Another way of doing it is create the field specifier separately, that way you can see exactly why you need to quote the string values.

const fields = {
  category: "",
  author: "Main Author",
  isActive: false,
  orgId: 10,
  teamName: "Green Team"
}

let query = `mutation CreateOrganizationTeam($input: ${JSON.stringify(fields)) {...
```

Body:
How can I pass the Graphql mutation query in cypress req and get the data back in the response ?
I am getting an error like Validation error of type FieldUndefined: Field 'mutation' in type Query undefined @CreateOrganizationTeam '

let author = 'Main Author';
let teamname = 'Green Team';
let query = `mutation CreateOrganizationTeam($input: {category: "", author:${author}, isActive: false, orgId: 10, teamName: ${teamname}}) {
  createOrganizationTeam(input: $input) {
    author
    isActive
    teamName
  }
}`;

/* Cypress test to verify the GraphQl response data  */
Then('I access the graphQL end point', () => {
  cy.request({
    method: 'POST',
    url: 'https://some-end-point/api',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      query,
      variables: {
        input: {
          author,
          isActive,
          teamName,
        }
      }
    })
  }).then((response)=>{
    console.log("GraphQL resp output:"+response.body.data);
  });
});


问:
st_intersection between polygons and points
I have two sf objects that I would like to intersect, but I can't.

D_sf has 633 observations and has a POLYGON geometry

Temp_points_sf has  11266 observations and has a POINT geometry.

My aim is to average out the multiple points that are found in each single polygon geometries.
Here you can find the full code:

```<code># Code for one layer of the grib (layer=days temperatures)
N_days = 365

#Create veCtors with the dates to label later data
Date <- seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by="days")

# Import Temp 2018 ore 13 era5 skin temperature
file <- "Data/Raw/Temperature/adaptor.mars.internal-1602054929.639875-5679-35-5d951960-05b1-4e42-8f0f-b42b0b69ad7f.grib"
GRIB<- stack(file)

# Convert D in a spatial polygon dataframe
D <- as_Spatial(D)

# Begin the dataset (just index now, then attaChes every variable at eaCh iteration).
Average_temperatures_URAU <- data.frame(D@data[, 1])
colnames(Average_temperatures_URAU)[1] <- "URAU_CODE"

# take the ith layer of the file (first day of 2018 to last day of 2018)
Grib_layer <- GRIB@layers[[1]]

# original data are Centered on the paCifiC. Use the rotate() funCtion to Center on europe, in this way it is not Cut
Grib_layer <- rotate(Grib_layer)

# Change the crs of D to use it as a mask in the Cycle
D2 <- spTransform(x = D, CRSobj = crs(Grib_layer))

# Extract D from world map
masked <- mask(x = Grib_layer, mask = D2)
cropped <- crop(x = masked, y = extent(D2))

# Transform the raster file to be a point one
layer_cropped  <- rasterToPoints(cropped, spatial="TRUE")

# Go baCk to normal Coordinates
layer_cropped_points <- spTransform(x = layer_cropped, CRSobj = crs(D))

# Change name
names(layer_cropped_points) <- "Temperature"

# Intersection of D and temps, sf is faster so we convert them
D_sf <- st_as_sf(D)
Temp_points_sf <- st_as_sf(layer_cropped_points)

#as often the case the geometry is invalid due to small irreg. make it valid
D_sf <- st_make_valid(D_sf)
Intersection_D_temp_sf <- st_intersection(D_sf, Temp_points_sf)

Intersection_D_temp_sf <- Intersection_D_temp_sf[, c("URAU_CODE", "Temperature" )]

# Sorting Now we Can average out the multiple points in the areas (apply mean by group)
yyy <- ddply(Intersection_D_temp_sf, .(URAU_CODE), summarize, Avg_temp=mean(Temperature))

# Change the name of the variable to "Avg_temp_Month_Year"
yyy_sorted <-  yyy[order(as.numeriC(yyy$URAU_CODE)),]

# Convert to Celsius
yyy_sorted$Avg_temp <- yyy_sorted$Avg_temp - 273.15

# Add the dates from the veCtor dates to the variable name
colnames(yyy_sorted)[2] <- as.character(Date[i])

# AttaCh the iterations' month to the whole dataset
Average_temperatures_URAU <- merge(Average_temperatures_URAU, yyy_sorted, by = "URAU_CODE")

print(i)
gc()
</code>```

However, the code takes forever to run. When I checked line by line, I found that the function st_intersectionis the one that blocks the code. How can i fix this?

答: It was taking me forever to compute the intersection while using st_intersection for two sf polygon data from all over US. I transformed the coordinate for both data to Albers conic (ESPG = 5070) and I was able to get the results in less than a minute. I am not sure how the accuracy will be impacted but for me it still seems to be accurate enough. So may be trying different coordinate system might help.</p>

Body:
I have two sf objects that I would like to intersect, but I can't.

D_sf has 633 observations and has a POLYGON geometry

Temp_points_sf has  11266 observations and has a POINT geometry.

My aim is to average out the multiple points that are found in each single polygon geometries.
Here you can find the full code:

# Code for one layer of the grib (layer=days temperatures)
N_days = 365

#Create veCtors with the dates to label later data
Date <- seq(as.Date("2018-01-01"), as.Date("2018-12-31"), by="days")

# Import Temp 2018 ore 13 era5 skin temperature
file <- "Data/Raw/Temperature/adaptor.mars.internal-1602054929.639875-5679-35-5d951960-05b1-4e42-8f0f-b42b0b69ad7f.grib"
GRIB<- stack(file)

# Convert D in a spatial polygon dataframe
D <- as_Spatial(D)

# Begin the dataset (just index now, then attaChes every variable at eaCh iteration).
Average_temperatures_URAU <- data.frame(D@data[, 1])
colnames(Average_temperatures_URAU)[1] <- "URAU_CODE"

# take the ith layer of the file (first day of 2018 to last day of 2018)
Grib_layer <- GRIB@layers[[1]]

# original data are Centered on the paCifiC. Use the rotate() funCtion to Center on europe, in this way it is not Cut
Grib_layer <- rotate(Grib_layer)

# Change the crs of D to use it as a mask in the Cycle
D2 <- spTransform(x = D, CRSobj = crs(Grib_layer))

# Extract D from world map
masked <- mask(x = Grib_layer, mask = D2)
cropped <- crop(x = masked, y = extent(D2))

# Transform the raster file to be a point one
layer_cropped  <- rasterToPoints(cropped, spatial="TRUE")

# Go baCk to normal Coordinates
layer_cropped_points <- spTransform(x = layer_cropped, CRSobj = crs(D))

# Change name
names(layer_cropped_points) <- "Temperature"

# Intersection of D and temps, sf is faster so we convert them
D_sf <- st_as_sf(D)
Temp_points_sf <- st_as_sf(layer_cropped_points)

#as often the case the geometry is invalid due to small irreg. make it valid
D_sf <- st_make_valid(D_sf)
Intersection_D_temp_sf <- st_intersection(D_sf, Temp_points_sf)

Intersection_D_temp_sf <- Intersection_D_temp_sf[, c("URAU_CODE", "Temperature" )]

# Sorting Now we Can average out the multiple points in the areas (apply mean by group)
yyy <- ddply(Intersection_D_temp_sf, .(URAU_CODE), summarize, Avg_temp=mean(Temperature))

# Change the name of the variable to "Avg_temp_Month_Year"
yyy_sorted <-  yyy[order(as.numeriC(yyy$URAU_CODE)),]

# Convert to Celsius
yyy_sorted$Avg_temp <- yyy_sorted$Avg_temp - 273.15

# Add the dates from the veCtor dates to the variable name
colnames(yyy_sorted)[2] <- as.character(Date[i])

# AttaCh the iterations' month to the whole dataset
Average_temperatures_URAU <- merge(Average_temperatures_URAU, yyy_sorted, by = "URAU_CODE")

print(i)
gc()

However, the code takes forever to run. When I checked line by line, I found that the function st_intersectionis the one that blocks the code. How can i fix this?


问:
JavaScript to get value from HTML table cell
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

```
<p>I was expecting this to work but no such luck ...</p>
<pre class="lang-js prettyprint-override"><code>  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);
</code>```

After several hours of failure, I'd greatly appreciate some help from the experts.

答:
You could get by class name as you were attempting however classes are intended to be applied to multiple elements so it returns a node list. You would want to select the node number for the element you wish to get. For example, the first element would be the following:</p>
```<code>var elements = document.getElementsByClassName('x-grid-cell-inner');
var single = elements[0].textContent.trim();
alert('the value is:' + single);
</code>```

Body:
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

I was expecting this to work but no such luck ...

  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);

After several hours of failure, I'd greatly appreciate some help from the experts.

Body:
You could get by class name as you were attempting however classes are intended to be applied to multiple elements so it returns a node list. You would want to select the node number for the element you wish to get. For example, the first element would be the following:

var elements = document.getElementsByClassName('x-grid-cell-inner');
var single = elements[0].textContent.trim();
alert('the value is:' + single);


问:
Field 'snapshot' has not been initialized
When trying to open this screen I get the message, "Field 'snapshot' has not been initialized." Pretty sure it's something to do with the "snapshot" being a late, but I don't know how to change it to make it work. This is an error when tying to open the page, not when building app. Any Help would be Appreciated!</p>
```<code>
class Upload extends StatefulWidget {
  @override
  _UploadState createState() => _UploadState();
}

class _UploadState extends State<Upload> {
  // ignore: cancel_subscriptions
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('NewsPost');

  @override

  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

  // TODO Pass Data Method
  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => PostDetails(snapshot: snap)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog App'),
        backgroundColor: Colors.redAccent,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => debugPrint('search'),
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => debugPrint('add'),
          )
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            UserAccountsDrawerHeader(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.purpleAccent, Colors.redAccent]),
              ),
              accountName: Text('Ahmer Iqbal'),
              accountEmail: Text('ahmer5253@gmail.com'),
              currentAccountPicture: CircleAvatar(
                child: Text('A'),
                backgroundColor: Colors.white,
              ),
            ),
            ListTile(
              leading: Icon(Icons.cake, color: Colors.purple),
              title: Text('First Page'),
            ),
            ListTile(
              leading: Icon(Icons.search, color: Colors.redAccent),
              title: Text('Second Page'),
            ),
            ListTile(
              leading: Icon(Icons.cached, color: Colors.orange),
              title: Text('Third Page'),
            ),
            ListTile(
              leading: Icon(Icons.menu, color: Colors.green),
              title: Text('Fourth Page'),
            ),
            Divider(height: 10.0, color: Colors.black),
            ListTile(
              trailing: Icon(Icons.close, color: Colors.red),
              title: Text('Close'),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
      body: snapshot == null
          ? Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: snapshot.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 10.0,
                  margin: EdgeInsets.all(10.0),
                  child: Container(
                    padding: EdgeInsets.all(10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        CircleAvatar(
                          child: Text(snapshot[index].get('title')[0]),
                          backgroundColor: Colors.redAccent,
                          foregroundColor: Colors.white,
                        ),
                        SizedBox(width: 10.0),
                        Container(
                          width: 210.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              InkWell(
                                child: Text(
                                  snapshot[index].get('title'),
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontSize: 22.0,
                                    color: Colors.green,
                                  ),
                                ),
                                onTap: () {
                                  // pass each and every index data
                                  passData(snapshot[index]);
                                },
                              ),
                              SizedBox(height: 5.0),
                              Text(
                                snapshot[index].get('content'),
                                maxLines: 2,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
}
import 'package:iona_central/Screens/Admin/updatedescription.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

class Upload extends StatefulWidget {
  @override
  _UploadState createState() => _UploadState();
}

class _UploadState extends State<Upload> {
  // ignore: cancel_subscriptions
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('NewsPost');

  @override

  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

  // TODO Pass Data Method
  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => PostDetails(snapshot: snap)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog App'),
        backgroundColor: Colors.redAccent,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => debugPrint('search'),
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => debugPrint('add'),
          )
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            UserAccountsDrawerHeader(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.purpleAccent, Colors.redAccent]),
              ),
              accountName: Text('Ahmer Iqbal'),
              accountEmail: Text('ahmer5253@gmail.com'),
              currentAccountPicture: CircleAvatar(
                child: Text('A'),
                backgroundColor: Colors.white,
              ),
            ),
            ListTile(
              leading: Icon(Icons.cake, color: Colors.purple),
              title: Text('First Page'),
            ),
            ListTile(
              leading: Icon(Icons.search, color: Colors.redAccent),
              title: Text('Second Page'),
            ),
            ListTile(
              leading: Icon(Icons.cached, color: Colors.orange),
              title: Text('Third Page'),
            ),
            ListTile(
              leading: Icon(Icons.menu, color: Colors.green),
              title: Text('Fourth Page'),
            ),
            Divider(height: 10.0, color: Colors.black),
            ListTile(
              trailing: Icon(Icons.close, color: Colors.red),
              title: Text('Close'),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
      body: snapshot == null
          ? Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: snapshot.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 10.0,
                  margin: EdgeInsets.all(10.0),
                  child: Container(
                    padding: EdgeInsets.all(10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        CircleAvatar(
                          child: Text(snapshot[index].get('title')[0]),
                          backgroundColor: Colors.redAccent,
                          foregroundColor: Colors.white,
                        ),
                        SizedBox(width: 10.0),
                        Container(
                          width: 210.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              InkWell(
                                child: Text(
                                  snapshot[index].get('title'),
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontSize: 22.0,
                                    color: Colors.green,
                                  ),
                                ),
                                onTap: () {
                                  // pass each and every index data
                                  passData(snapshot[index]);
                                },
                              ),
                              SizedBox(height: 5.0),
                              Text(
                                snapshot[index].get('content'),
                                maxLines: 2,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
}

Let me know if you need to see updatedesctription.dart aswell!

</code>```

答:
snapshot wasn't defined to be a nullable value so snapshot==null won't work.

Define it as a nullable like so:

Change late List<DocumentSnapshot> snapshot;

to

List<DocumentSnapshot>? snapshot;

Body:
When trying to open this screen I get the message, "Field 'snapshot' has not been initialized." Pretty sure it's something to do with the "snapshot" being a late, but I don't know how to change it to make it work. This is an error when tying to open the page, not when building app. Any Help would be Appreciated!

class Upload extends StatefulWidget {
  @override
  _UploadState createState() => _UploadState();
}

class _UploadState extends State<Upload> {
  // ignore: cancel_subscriptions
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('NewsPost');

  @override

  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

  // TODO Pass Data Method
  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => PostDetails(snapshot: snap)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog App'),
        backgroundColor: Colors.redAccent,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => debugPrint('search'),
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => debugPrint('add'),
          )
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            UserAccountsDrawerHeader(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.purpleAccent, Colors.redAccent]),
              ),
              accountName: Text('Ahmer Iqbal'),
              accountEmail: Text('ahmer5253@gmail.com'),
              currentAccountPicture: CircleAvatar(
                child: Text('A'),
                backgroundColor: Colors.white,
              ),
            ),
            ListTile(
              leading: Icon(Icons.cake, color: Colors.purple),
              title: Text('First Page'),
            ),
            ListTile(
              leading: Icon(Icons.search, color: Colors.redAccent),
              title: Text('Second Page'),
            ),
            ListTile(
              leading: Icon(Icons.cached, color: Colors.orange),
              title: Text('Third Page'),
            ),
            ListTile(
              leading: Icon(Icons.menu, color: Colors.green),
              title: Text('Fourth Page'),
            ),
            Divider(height: 10.0, color: Colors.black),
            ListTile(
              trailing: Icon(Icons.close, color: Colors.red),
              title: Text('Close'),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
      body: snapshot == null
          ? Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: snapshot.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 10.0,
                  margin: EdgeInsets.all(10.0),
                  child: Container(
                    padding: EdgeInsets.all(10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        CircleAvatar(
                          child: Text(snapshot[index].get('title')[0]),
                          backgroundColor: Colors.redAccent,
                          foregroundColor: Colors.white,
                        ),
                        SizedBox(width: 10.0),
                        Container(
                          width: 210.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              InkWell(
                                child: Text(
                                  snapshot[index].get('title'),
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontSize: 22.0,
                                    color: Colors.green,
                                  ),
                                ),
                                onTap: () {
                                  // pass each and every index data
                                  passData(snapshot[index]);
                                },
                              ),
                              SizedBox(height: 5.0),
                              Text(
                                snapshot[index].get('content'),
                                maxLines: 2,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
}
import 'package:iona_central/Screens/Admin/updatedescription.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

class Upload extends StatefulWidget {
  @override
  _UploadState createState() => _UploadState();
}

class _UploadState extends State<Upload> {
  // ignore: cancel_subscriptions
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('NewsPost');

  @override

  void initState() {
    super.initState();
    subscription = collectionReference.snapshots().listen((dataSnapshot) {
      setState(() {
        snapshot = dataSnapshot.docs;
      });
    });
  }

  // TODO Pass Data Method
  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => PostDetails(snapshot: snap)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog App'),
        backgroundColor: Colors.redAccent,
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => debugPrint('search'),
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () => debugPrint('add'),
          )
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: [
            UserAccountsDrawerHeader(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.purpleAccent, Colors.redAccent]),
              ),
              accountName: Text('Ahmer Iqbal'),
              accountEmail: Text('ahmer5253@gmail.com'),
              currentAccountPicture: CircleAvatar(
                child: Text('A'),
                backgroundColor: Colors.white,
              ),
            ),
            ListTile(
              leading: Icon(Icons.cake, color: Colors.purple),
              title: Text('First Page'),
            ),
            ListTile(
              leading: Icon(Icons.search, color: Colors.redAccent),
              title: Text('Second Page'),
            ),
            ListTile(
              leading: Icon(Icons.cached, color: Colors.orange),
              title: Text('Third Page'),
            ),
            ListTile(
              leading: Icon(Icons.menu, color: Colors.green),
              title: Text('Fourth Page'),
            ),
            Divider(height: 10.0, color: Colors.black),
            ListTile(
              trailing: Icon(Icons.close, color: Colors.red),
              title: Text('Close'),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      ),
      body: snapshot == null
          ? Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: snapshot.length,
              itemBuilder: (context, index) {
                return Card(
                  elevation: 10.0,
                  margin: EdgeInsets.all(10.0),
                  child: Container(
                    padding: EdgeInsets.all(10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        CircleAvatar(
                          child: Text(snapshot[index].get('title')[0]),
                          backgroundColor: Colors.redAccent,
                          foregroundColor: Colors.white,
                        ),
                        SizedBox(width: 10.0),
                        Container(
                          width: 210.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              InkWell(
                                child: Text(
                                  snapshot[index].get('title'),
                                  maxLines: 1,
                                  style: TextStyle(
                                    fontSize: 22.0,
                                    color: Colors.green,
                                  ),
                                ),
                                onTap: () {
                                  // pass each and every index data
                                  passData(snapshot[index]);
                                },
                              ),
                              SizedBox(height: 5.0),
                              Text(
                                snapshot[index].get('content'),
                                maxLines: 2,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
    );
  }
}

Let me know if you need to see updatedesctription.dart aswell!


问:
How to get mean/mode/median by Time Intervals with Python
I have a data set that looks like this:

5_second_groupings
canceled_orders_count

0 days 00:00:01
656

0 days 00:00:06
1348

0 days 00:00:11
3874

0 days 00:00:16
3586

I want to find the below:

What is the most comment time interval where people cancel their orders after placing order? Is it 5 seconds after the order?

2)What is the average interval where people cancel their order in? Do most people cancel their orders after 11 seconds of ordering or 16? What's the average?

I know I can use mode medium functions to find but it's not giving me what I need. It's just giving me mode of canceled_orders_count but I want to take into account the 5 second groupings as well.

答:
For your Q1, df.set_index('5_second_groupings')['canceled_orders_count'].idxmax() will find the maximum 'canceled_orders_count' but return the corresponding index which is one of the '5_second_groupings'

For your Q2, your need the weighted average, meaning an average of 5_second_groupings weighted by canceled_orders_count, which means (df['5_second_groupings'].dt.seconds * df['canceled_orders_count']).sum() / df['canceled_orders_count'].sum(), given that df['5_second_groupings'] is a datetime object so that dt.seconds will work. Btw, the average would have been more accurate if you just take the average of your Delta column in your last question. Your estimate here should be under-estimating because the grouping rounded the Delta value down.


问:
Dart Main File (and other essential files) Not Created In New Project
I am learning dart/flutter using InetlliJ, and when I go to create a new dart project, it only creates a few useless files. No main.dart. I have all the most recent versions of flutter and dart installed.
enter image description here</p>

答:
I found the answer. If you go File->Project Structure->Modules->click the (+) sign and select a new module, then all the proper files will be made. Apparently when it comes to Dart programming language, intelliJ requires you to create a subsequent module inside the project folder.
I also figured out that the new module you create has to have a completely lowercase title, otherwise the project problem repeats itself but in the new module folder this time.</p>


问:
ASP drop down select showing up weird
I've been trying to create a drop down list with asp tag helpers and for some reason they always look strange. I'll include my code for Controller, View, and view model. Also the picture of how it looks.
Controller:

```<code>public async Task<IActionResult> Create()
{
    var dalias = await _context.DeptAliases
        .Select(m => new SelectListItem { Text = m.Alias, Value = m.DeptAliasPkey.ToString() }).Distinct()
        .ToListAsync();

        var vm = new CopyCenterCreateViewModel()
        {
            DAlias = dalias,
        };
        return View(vm);
}
</code>```

View:

```<code>@model PrintShop.ViewModels.CopyCenterCreateViewModel
<form  asp-action="Create">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <label asp-for="DAlias" class="control-label"></label>
    <select asp-for="DAlias" asp-items="Model.DAlias" class="form-control"></select>
    <span asp-validation-for="DAlias" class="text-danger"></span>
</form>
</code>```

ViewModel:

```<code>public class CopyCenterCreateViewModel
{
    public List<SelectListItem> DAlias { get; set; }
}
</code>```

Result:

答:
It looks like the select control is rendering in multi-selection mode. If the tag helper asp-for is binding to an IEnumerable then the select element is rendered in multiple mode.

From tag-helpers multiple select section of the docs:

The Select Tag Helper will automatically generate the multiple = "multiple" attribute if the property specified in the asp-for
attribute is an IEnumerable.

You only have a single property in the ViewModel which is a List, and you're binding the items to the same property as the selected value.

You could rename the list of items to something else and add a property to bind to the value of the selected item:

```<code>public class CopyCenterCreateViewModel
{
    public string DAlias { get; set; }
    public List<SelectListItem> Items { get; set; }
}
</code>```

In the controller you'd populate the Items property of the CopyCenterCreateViewModel.

In the view bind asp-items to the view model Items property:

```<code><select asp-for="DAlias" asp-items="Model.Items" class="form-control"></select>
</code>```

Title: ASP drop down select showing up weird

Body:
I've been trying to create a drop down list with asp tag helpers and for some reason they always look strange. I'll include my code for Controller, View, and view model. Also the picture of how it looks.
Controller:

public async Task<IActionResult> Create()
{
    var dalias = await _context.DeptAliases
        .Select(m => new SelectListItem { Text = m.Alias, Value = m.DeptAliasPkey.ToString() }).Distinct()
        .ToListAsync();

        var vm = new CopyCenterCreateViewModel()
        {
            DAlias = dalias,
        };
        return View(vm);
}

View:

@model PrintShop.ViewModels.CopyCenterCreateViewModel
<form  asp-action="Create">

    <select asp-for="DAlias" asp-items="Model.DAlias" class="form-control"></select>

</form>

ViewModel:

public class CopyCenterCreateViewModel
{
    public List<SelectListItem> DAlias { get; set; }
}

Result:

Body:
It looks like the select control is rendering in multi-selection mode. If the tag helper asp-for is binding to an IEnumerable then the select element is rendered in multiple mode.

From tag-helpers multiple select section of the docs:

The Select Tag Helper will automatically generate the multiple = "multiple" attribute if the property specified in the asp-for
attribute is an IEnumerable.

You only have a single property in the ViewModel which is a List, and you're binding the items to the same property as the selected value.

You could rename the list of items to something else and add a property to bind to the value of the selected item:

public class CopyCenterCreateViewModel
{
    public string DAlias { get; set; }
    public List<SelectListItem> Items { get; set; }
}

In the controller you'd populate the Items property of the CopyCenterCreateViewModel.

In the view bind asp-items to the view model Items property:

<select asp-for="DAlias" asp-items="Model.Items" class="form-control"></select>