问:
Is there a way to remove unused imports for Python in VS Code?
I would really like to know if there is some Extension in Visual Studio Code or other means that could help identify and remove any unused imports.

I have quite a large number of imports like this and it's getting close to 40 lines. I know some of them aren't in use, the problem is removing them safely.

```<code>from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from rest_framework import routers, serializers, viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
</code>```

答:
You can create such a VSCode Task by yourself.

1. Install autoflake

pip install autoflake
```
<h2>2. Create Vscode Task</h2>
<ul>
<li><p>Create ".vscode/tasks.json".</p>
</li>
<li><p>Add the following settings.</p>
</li>
</ul>
<h3>Option 1. Without <code>activate</code></h3>
<pre class="lang-json prettyprint-override"><code>{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "autoflake.removeUnusedImports",
            "command": "${command:python.interpreterPath}",
            // in Git Bash, "'${command:python.interpreterPath}'",
            "args": [
                "-m"
                "autoflake",
                "--in-place",
                "--remove-all-unused-imports",
                "${file}",
                // in Git Bash, "'${file}'",
                // to run on all files in the working directory, replace "${file}", with "--recursive", "."
            ],
            "presentation": {
                "echo": true,
                "reveal": "silent",
                "focus": false,
                "panel": "dedicated",
                "showReuseMessage": false,
                "clear": false,
                "close": true
            },
            "problemMatcher": []
        },
    ]
}
</code>```

Option 2. With activate

The above method (running autoflake as a module) works at least on Windows (works in PowerShell and Command Prompt, Git Bash), and may work on other operating systems or environments. (I don't know because I don't have one. Please edit.) Alternatively, you can use activate.

PowerShell

"command": "${command:python.interpreterPath}\\..\\activate.ps1\r\n",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}",
],
```
<h4>Command Prompt</h4>
<pre class="lang-json prettyprint-override"><code>"command": "${command:python.interpreterPath}\\..\\activate &&",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}",
],
</code>```

Bash

In Bash, it seems that file paths must be enclosed in quotation marks.

"command": "source",
"args": [
    "\"${command:python.interpreterPath}\\..\\activate\"\r\n"
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "\"${file}\"",
],
```
<h2>3. Add the task to keyboard shortcuts (Optional)</h2>
<ul>
<li>Press <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>P</kbd> and select <code>Preferences: Open Keyboard Shortcuts (JSON)</code>.</li>
<li>Add the following settings.</li>
</ul>
<pre class="lang-json prettyprint-override"><code>[
    {
        "key": "Shift+Alt+P",//Set this value to any you like.
        "command": "workbench.action.tasks.runTask",
        "args": "autoflake.removeUnusedImports",
    }
]
</code>```

In this way, pressing the shortcut key will automatically delete unused imports.

Unfortunately, vscode-autoflake did not work in to my environment for some reason.

Body:
I would really like to know if there is some Extension in Visual Studio Code or other means that could help identify and remove any unused imports.

I have quite a large number of imports like this and it's getting close to 40 lines. I know some of them aren't in use, the problem is removing them safely.

from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from rest_framework import routers, serializers, viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User

Body:
You can create such a VSCode Task by yourself.

1. Install autoflake

pip install autoflake

2. Create Vscode Task

Create ".vscode/tasks.json".

Add the following settings.

Option 1. Without activate

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "autoflake.removeUnusedImports",
            "command": "${command:python.interpreterPath}",
            // in Git Bash, "'${command:python.interpreterPath}'",
            "args": [
                "-m"
                "autoflake",
                "--in-place",
                "--remove-all-unused-imports",
                "${file}",
                // in Git Bash, "'${file}'",
                // to run on all files in the working directory, replace "${file}", with "--recursive", "."
            ],
            "presentation": {
                "echo": true,
                "reveal": "silent",
                "focus": false,
                "panel": "dedicated",
                "showReuseMessage": false,
                "clear": false,
                "close": true
            },
            "problemMatcher": []
        },
    ]
}

Option 2. With activate

The above method (running autoflake as a module) works at least on Windows (works in PowerShell and Command Prompt, Git Bash), and may work on other operating systems or environments. (I don't know because I don't have one. Please edit.) Alternatively, you can use activate.

PowerShell

"command": "${command:python.interpreterPath}\\..\\activate.ps1\r\n",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}",
],

Command Prompt

"command": "${command:python.interpreterPath}\\..\\activate &&",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}",
],

Bash

In Bash, it seems that file paths must be enclosed in quotation marks.

"command": "source",
"args": [
    "\"${command:python.interpreterPath}\\..\\activate\"\r\n"
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "\"${file}\"",
],

3. Add the task to keyboard shortcuts (Optional)

Press CtrlShiftP and select Preferences: Open Keyboard Shortcuts (JSON).

Add the following settings.

[
    {
        "key": "Shift+Alt+P",//Set this value to any you like.
        "command": "workbench.action.tasks.runTask",
        "args": "autoflake.removeUnusedImports",
    }
]

In this way, pressing the shortcut key will automatically delete unused imports.

Unfortunately, vscode-autoflake did not work in to my environment for some reason.


来源: stackexchange

问:
How to insert Hexcode within string template literal
Right now I have the following in my

```<code>{<span>#</span>}
      {`${totalQuantity}`} <span>₹</span>
      {`${totalCost}`}
</code>```

This outputs #0₹0 ('totalQuantity' & 'totalCost' are variables with value of zero as of now)

However, as you can see, I have 2 span's & 2 template literals because I do not know how to insert the hex code of # & ₹ into template literal. How do I do that? Can I even do that?

答:
Entities are a part of HTML (their long name is "HTML Entity") and so can be treated similar to how you might do .innerHTML = '

'.

For example,

```<code>someElement.innerHTML = `#${totalQuantity} ₹${totalCost}`;
</code>```

Note that since HTML5 documents are encouraged to be encoded as UTF-8, you can also do the following (though you may have reasons not to):

```<code>someElement.innerHTML = `#${totalQuantity} ₹${totalCost}`;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Right now I have the following in my

{#}
      {`${totalQuantity}`} ₹
      {`${totalCost}`}

This outputs #0₹0 ('totalQuantity' & 'totalCost' are variables with value of zero as of now)

However, as you can see, I have 2 span's & 2 template literals because I do not know how to insert the hex code of # & ₹ into template literal. How do I do that? Can I even do that?

Body:
Entities are a part of HTML (their long name is "HTML Entity") and so can be treated similar to how you might do .innerHTML = '<div></div>'.

For example,

someElement.innerHTML = `&#35;${totalQuantity} &#8377;${totalCost}`;

Note that since HTML5 documents are encouraged to be encoded as UTF-8, you can also do the following (though you may have reasons not to):

someElement.innerHTML = `#${totalQuantity} ₹${totalCost}`;


问:
Search data between two tables from SQL
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

```<code>SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"
</code>```

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

答:
@RobroyBustilloCanales

your query is correct. you have mentioned category_id in product table as text so you need to cast that to integer before join and use single quotes instead of double quotes.

```<code>            SELECT p.code AS CODE, p.model AS NAME
            FROM products p
            LEFT JOIN categories c
            ON cast (p.category_id as INTEGER) = c.category_id
            WHERE p.model LIKE '%LAPTOP%' OR c.category_name LIKE '%LAPTOP%';
</code>```

Title: Search data between two tables from SQL

Body:
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

Body:
@RobroyBustilloCanales

your query is correct. you have mentioned category_id in product table as text so you need to cast that to integer before join and use single quotes instead of double quotes.

            SELECT p.code AS CODE, p.model AS NAME
            FROM products p
            LEFT JOIN categories c
            ON cast (p.category_id as INTEGER) = c.category_id
            WHERE p.model LIKE '%LAPTOP%' OR c.category_name LIKE '%LAPTOP%';


问:
How do I render different pages with variables on post request of login with passport.js local authentication?(Express)
I am trying to login the user with passport.js authentication and on success I redirect the user to the last page that comes from a variable inside the login page, and on failure I re-render the login page with a message, I tried to do it but I fail, here what I did:

```<code>router.post('/login',
  body('backurl').trim().escape(),

  (req,res,next) =>{
    passport.authenticate('local', (err,user)=>{
      if(err){return next(err)}
      if(!user){
        return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
      }
      if(req.body.backurl == null){
        return res.redirect('/yourcourses')
      }
      return res.redirect(req.body.backurl)
    });
  }
);
</code>```

it just keeps endlessly loading and nothing comes out, what is wrong with my code?

Thanks!

答:
I can't seem to find a definitive reference for passport.authenticate, but all the example in https://www.passportjs.org/concepts/authentication/ show it as a middleware, so I think you'll need to use it as such:

```<code>router.post('/login',
  passport.authenticate('local'),
  (req, res, next) => {
    req.body('backurl').trim().escape();
    if (!req.user) {
      return res.render('login', {
        message: 'Unable to login, the password or the username are wrong'
      });
    }
    if (req.body.backurl == null) {
      return res.redirect('/yourcourses');
    }

    return res.redirect(req.body.backurl);
  }
);
</code>```

Body:
I am trying to login the user with passport.js authentication and on success I redirect the user to the last page that comes from a variable inside the login page, and on failure I re-render the login page with a message, I tried to do it but I fail, here what I did:

router.post('/login',
  body('backurl').trim().escape(),

  (req,res,next) =>{
    passport.authenticate('local', (err,user)=>{
      if(err){return next(err)}
      if(!user){
        return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
      }
      if(req.body.backurl == null){
        return res.redirect('/yourcourses')
      }
      return res.redirect(req.body.backurl)
    });
  }
);

it just keeps endlessly loading and nothing comes out, what is wrong with my code?

Thanks!

Body:
I can't seem to find a definitive reference for passport.authenticate, but all the example in https://www.passportjs.org/concepts/authentication/ show it as a middleware, so I think you'll need to use it as such:

router.post('/login',
  passport.authenticate('local'),
  (req, res, next) => {
    req.body('backurl').trim().escape();
    if (!req.user) {
      return res.render('login', {
        message: 'Unable to login, the password or the username are wrong'
      });
    }
    if (req.body.backurl == null) {
      return res.redirect('/yourcourses');
    }

    return res.redirect(req.body.backurl);
  }
);


问:
Writing to a file with mode "w" versus "a" - I can't get "w" to work properly
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

```<code>Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph
</code>```

The starting_letter.txt file is also attached to my project.

```<code>Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel
</code>```

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

```<code>invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)
</code>```

答:
My code was simply not good. :D

I had an unnecessary readlines() call for the starting_letter.txt. I read too much into the instructors hints and overused that method.

I had to remove the second for loop and also change the opening method for starting_letter.txt to be a read() instead of a readlines(). This allowed me to pull in the whole starting_letter.txt and do one edit on it, rather than parsing through every line to do it. I'm a newbie, and it's showing!

```<code>starting_letter_list = starting_letter.readlines()
</code>```

should have been

```<code>starting_letter_list = starting_letter.read()
</code>```

Body:
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

The starting_letter.txt file is also attached to my project.

Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)

Body:
My code was simply not good. :D

I had an unnecessary readlines() call for the starting_letter.txt. I read too much into the instructors hints and overused that method.

I had to remove the second for loop and also change the opening method for starting_letter.txt to be a read() instead of a readlines(). This allowed me to pull in the whole starting_letter.txt and do one edit on it, rather than parsing through every line to do it. I'm a newbie, and it's showing!

starting_letter_list = starting_letter.readlines()

should have been

starting_letter_list = starting_letter.read()


问:
How hashmap inserts
Suppose that hashmap is created. By default it comes with 16 buckets. Is this a true statement?

Size of hashmap will increase if the element size reaches threshold. The threshold is elementSize/BucketNUmber=12. In our example the bucket size is 16. so if I add 13th element it will increase bucket size from 16 to 32.

If this statement is true, what if the all element is stored in the same bucket? It is quite possible bcs we the location of new comer element is calculated by its hashcode. In this case we will have 15 more empty buckets. Does hashmap increase the bucket or not?

答:
The whole point of resizing the hashmap is to get a better distribution of hashed items and to avoid collisions, and the performance penalties associated with collisions.  When Java increases the bucket size of the hashmap, it will also have to rehash every item contained in the map.  There is a cost with this as well, but it is one time and the hope is that the performance gain with a larger bucket size would outweigh this cost.

For reference, prior to Java 8, collisions in a hashmap would be resolved using a linked list, leading to O(N) worst search behavior for a map with N items.  As of Java 8, the HashMap class now uses a balanced tree to handle collisions, leading to a worst case search performance of O(N*lgN).

Title: How hashmap inserts


问:
how to start jvm and can we have multiple jvm running on a single system?
I had been asked this question in interview, how to start jvm and can we have multiple jvm running on a single system?</p>

答:
The way to start a jvm is by invoking the main, either by invoking a jar using java -jar MyJar or by simply running main class from an IDE.

Yes, Multiple jvm instances can be run on a single machine, they all will have their own memory allocated.
There will be that many jvms as many main programs you run.

ContentLicense: CC BY-SA 3.0


问:
What is the best way to access elements of parent control from a child control?
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

```<code>public enum ItemMode
{
    TRUE, FALSE, NONE
}
</code>```

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

```<code>e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);
</code>```

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

答: you could create an EventArgs which takes an ItemMode[] or a List<ItemMode> or a Dictionary<string, ItemMode> for those items (instead of the current 6 arguments) - that way you don't need to change much when adding more items...

Body:
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

public enum ItemMode
{
    TRUE, FALSE, NONE
}

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.


问:
How to use singlechildscroll view for Gridview.builder
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

```<code>  import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
You will try this..

```<code>class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;

  @override
Widget build(BuildContext context) {
  return Scaffold(
    bottomSheet: ElevatedButton(
    style: ElevatedButton.styleFrom(
        padding:
        const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
        primary: Theme.of(context).primaryColor,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.0))),
    onPressed: () {},
    child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                  padding: const EdgeInsets.symmetric(
                      vertical: 2, horizontal: 8.0),
                  width: 24.0,
                  height: 24.0,
                  decoration: const BoxDecoration(
                    color: Colors.black,
                    shape: BoxShape.circle,
                  ),
                  child: Text('fasdfa',
                      textAlign: TextAlign.center,
                      style: Theme.of(context)
                          .textTheme
                          .button!
                          .copyWith(color: Colors.white))),
              const SizedBox(width: 8.0),
              Text('USD 1000',
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.button)
            ],
          ),
          Text('NEXT',
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.button)
        ]),
    ),
    body: SafeArea(
     child: Column(
      children: [
        Padding(
          /** header */
          padding: const EdgeInsets.only(top: 14, bottom: 10),
          child: Container(
            height: 60,
            padding:
            const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
            width: MediaQuery.of(context).size.width * 1,
            color: Colors.blue,
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.white,
            width: MediaQuery.of(context).size.width,
            child: Padding(
              padding: const EdgeInsets.only(top: 4.0),
              child: Column(
                //_buildContent
                children: [
                  Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Container(
                            width: MediaQuery.of(context).size.width * 1,
                            height: 200,
                            color: Colors.yellow,
                          ),
                        ],
                      ),
                      Positioned(
                        top: MediaQuery.of(context).size.height * 0.265,
                        right: 20,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              shape: const CircleBorder(),
                              primary: Colors.white),
                          onPressed: () {},
                          child: Container(
                            color: Colors.blue,
                            width: 10,
                            height:
                            MediaQuery.of(context).size.height * 0.055,
                          ),
                        ),
                      )
                    ],
                  ),
                  const Expanded(child: Tabss()),
                ],
              ),
            ),
          ),
        ),
      ],
    ),
   ),
  );
 }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
 _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;

  @override
Widget build(BuildContext context) {
 return DefaultTabController(
  length: 3,
  child: Column(
    children: [
      TabBar(
        onTap: (a) {
          setState(() {});
        },
        labelStyle: Theme.of(context)
            .textTheme
            .button!
            .copyWith(fontWeight: FontWeight.normal),
        unselectedLabelStyle: Theme.of(context)
            .textTheme
            .subtitle1!
            .copyWith(fontSize: 14),
        isScrollable: true,
        labelPadding:
        const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
        indicatorWeight: 4,
        indicatorColor: Colors.blue,
        indicatorSize: TabBarIndicatorSize.label,
        tabs: List.generate(
          3,
              (index) => const Text(
            'TESTING',
            style: TextStyle(
              color: Colors.black,
            ),
          ),
        ),
      ),
      Flexible(
        flex: 6,
        child: TabBarView(
          children: List.generate(
            3,
                (index) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: GridView.builder(
                  shrinkWrap: true,
                  // FOR FOOD AND DECO
                  itemCount: 30,
                  gridDelegate:
                  const SliverGridDelegateWithFixedCrossAxisCount(
                      childAspectRatio: 0.95,
                      crossAxisSpacing: 15.0,
                      mainAxisSpacing: 10.0,
                      mainAxisExtent: 180,
                      crossAxisCount: 2),
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      color: Colors.red,
                      alignment: Alignment.center,
                      child: Text(
                        index.toString(),
                      ),
                    );
                  },
                ),
              );
            },
          ),
        ),
      ),
      const Spacer(),
    ],
   ),
 );
}
}
</code>```

Body:
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

  import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Body:
You will try this..

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;

  @override
Widget build(BuildContext context) {
  return Scaffold(
    bottomSheet: ElevatedButton(
    style: ElevatedButton.styleFrom(
        padding:
        const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
        primary: Theme.of(context).primaryColor,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.0))),
    onPressed: () {},
    child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                  padding: const EdgeInsets.symmetric(
                      vertical: 2, horizontal: 8.0),
                  width: 24.0,
                  height: 24.0,
                  decoration: const BoxDecoration(
                    color: Colors.black,
                    shape: BoxShape.circle,
                  ),
                  child: Text('fasdfa',
                      textAlign: TextAlign.center,
                      style: Theme.of(context)
                          .textTheme
                          .button!
                          .copyWith(color: Colors.white))),
              const SizedBox(width: 8.0),
              Text('USD 1000',
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.button)
            ],
          ),
          Text('NEXT',
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.button)
        ]),
    ),
    body: SafeArea(
     child: Column(
      children: [
        Padding(
          /** header */
          padding: const EdgeInsets.only(top: 14, bottom: 10),
          child: Container(
            height: 60,
            padding:
            const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
            width: MediaQuery.of(context).size.width * 1,
            color: Colors.blue,
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.white,
            width: MediaQuery.of(context).size.width,
            child: Padding(
              padding: const EdgeInsets.only(top: 4.0),
              child: Column(
                //_buildContent
                children: [
                  Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Container(
                            width: MediaQuery.of(context).size.width * 1,
                            height: 200,
                            color: Colors.yellow,
                          ),
                        ],
                      ),
                      Positioned(
                        top: MediaQuery.of(context).size.height * 0.265,
                        right: 20,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              shape: const CircleBorder(),
                              primary: Colors.white),
                          onPressed: () {},
                          child: Container(
                            color: Colors.blue,
                            width: 10,
                            height:
                            MediaQuery.of(context).size.height * 0.055,
                          ),
                        ),
                      )
                    ],
                  ),
                  const Expanded(child: Tabss()),
                ],
              ),
            ),
          ),
        ),
      ],
    ),
   ),
  );
 }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
 _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;

  @override
Widget build(BuildContext context) {
 return DefaultTabController(
  length: 3,
  child: Column(
    children: [
      TabBar(
        onTap: (a) {
          setState(() {});
        },
        labelStyle: Theme.of(context)
            .textTheme
            .button!
            .copyWith(fontWeight: FontWeight.normal),
        unselectedLabelStyle: Theme.of(context)
            .textTheme
            .subtitle1!
            .copyWith(fontSize: 14),
        isScrollable: true,
        labelPadding:
        const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
        indicatorWeight: 4,
        indicatorColor: Colors.blue,
        indicatorSize: TabBarIndicatorSize.label,
        tabs: List.generate(
          3,
              (index) => const Text(
            'TESTING',
            style: TextStyle(
              color: Colors.black,
            ),
          ),
        ),
      ),
      Flexible(
        flex: 6,
        child: TabBarView(
          children: List.generate(
            3,
                (index) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: GridView.builder(
                  shrinkWrap: true,
                  // FOR FOOD AND DECO
                  itemCount: 30,
                  gridDelegate:
                  const SliverGridDelegateWithFixedCrossAxisCount(
                      childAspectRatio: 0.95,
                      crossAxisSpacing: 15.0,
                      mainAxisSpacing: 10.0,
                      mainAxisExtent: 180,
                      crossAxisCount: 2),
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      color: Colors.red,
                      alignment: Alignment.center,
                      child: Text(
                        index.toString(),
                      ),
                    );
                  },
                ),
              );
            },
          ),
        ),
      ),
      const Spacer(),
    ],
   ),
 );
}
}


问:
How to get form data from login screen into a usable string in my controller in flutter
I feel as if this should be something very easy but I cannot figure it out, I have everything working I just need to make the 'email' and 'password' fields change to whatever the user enters. Below is my controller where the data gets sent via HTTP

```<code> postData() async {
    try {
      var response = await http
          .post(Uri.parse("http://exampleIP/untitled/authentication/login.php"), body: {
        "username": 'email',   // needs to be what user inputs//
        "password": 'password' // needs to be what user inputs//
</code>```

I understand all the code is not there but the code works I just need to know how to get the input from the form

Here is form code

```<code>import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutx/flutx.dart';
import 'package:harralander/images.dart';
import 'package:harralander/theme/app_theme.dart';

import '../controllers/login_controller.dart';

class LogInScreen extends StatefulWidget {
  const LogInScreen({Key? key}) : super(key: key);

  @override
  _LogInScreenState createState() => _LogInScreenState();
}

class _LogInScreenState extends State<LogInScreen> {
  late ThemeData theme;
  late CustomTheme customTheme;

  late LogInController controller;
  late OutlineInputBorder outlineInputBorder;

  @override
  void initState() {
    super.initState();
    theme = AppTheme.theme;
    customTheme = AppTheme.customTheme;

    controller = FxControllerStore.putOrFind(LogInController());
    outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(4)),
      borderSide: BorderSide(
        color: Colors.transparent,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FxBuilder<LogInController>(
        controller: controller,
        builder: (controller) {
          return _buildBody();
        });
  }

  Widget _buildBody() {
    return Scaffold(
      body: Padding(
        padding: FxSpacing.x(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FxText.h3(
              'Log In',
              fontWeight: 700,
            ),
            FxSpacing.height(20),
            Form(
              key: controller.formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.mail,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Email Address",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.emailTE,
                    validator: controller.validateEmail,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                  FxSpacing.height(20),
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.lock,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Password",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.passwordTE,
                    validator: controller.validatePassword,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                ],
              ),
            ),
            FxSpacing.height(20),
            Align(
              alignment: Alignment.centerRight,
              child: FxButton.text(
                  onPressed: () {
                    controller.goToForgotPasswordScreen();
                  },
                  padding: FxSpacing.zero,
                  splashColor: customTheme.fitnessPrimary.withAlpha(40),
                  child: FxText.b3(
                    'Forgot password ?',
                    color: customTheme.fitnessPrimary,
                  )),
            ),
            FxSpacing.height(20),
            Row(
              children: [
                FxButton(
                    padding: FxSpacing.xy(16, 12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.card,
                    splashColor: theme.colorScheme.onBackground.withAlpha(40),
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: Row(
                      children: [
                        Image(
                          image: AssetImage(Images.google),
                          height: 17,
                          width: 17,
                        ),
                        FxSpacing.width(20),
                        FxText.l2(
                          'Login with Google',
                          fontWeight: 600,
                          color: theme.colorScheme.onBackground,
                        ),
                      ],
                    )),
                FxSpacing.width(20),
                Expanded(
                  child: FxButton(
                    padding: FxSpacing.y(12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.fitnessPrimary,
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: FxText.b2(
                      'Log In',
                      color: customTheme.fitnessOnPrimary,
                      fontWeight: 600,
                    ),
                  ),
                ),
              ],
            ),
            FxSpacing.height(20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FxText.b3(
                  'New to Harralander? ',
                ),
                FxButton.text(
                    onPressed: () {
                      controller.goToRegisterScreen();
                    },
                    padding: FxSpacing.zero,
                    splashColor: customTheme.fitnessPrimary.withAlpha(40),
                    child: FxText.b3(
                      'Register',
                      color: customTheme.fitnessPrimary,
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

</code>```

Thank you

答:
you have to TextEditingController to get user input, and store those in varibale or access through using .text method.
Eg:

```<code>TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

String? uName;
String? pwd;

//inside from:
//we can get data using
uName = _emailController.text;
pwd = _passwordController.text;
//or we can pass this directly as a parameter like this:
_passwordController.text
</code>```

import 'package:flutter/material.dart';
import 'package:flutterloginform/validation.dart';

```<code>class LoginFormWithAutoValidation extends StatefulWidget {
  @override
  _LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
}

class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {

  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);

  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

  final _formKey = new GlobalKey<FormState>();

  String _email;
  String _password;

  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.green[400],
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              color: Color(0xffF3F3F3),
              elevation: 5,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Form(
                  key: _formKey,
                  autovalidate: _autoValidate,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[

                      Center(
                          child: Text(
                        "Your Logo Here",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 25,
                        ),
                      )),
                      SizedBox(height: 25.0),

             // TextFormField for email address

                      TextFormField(
                        keyboardType: TextInputType.emailAddress,
                        autofocus: false,
                        controller: _emailController,
                        validator: validateEmail,
                        onSaved: (value) => _email = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Email",
                          border: OutlineInputBorder(
                           borderRadius:BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

            // TextFormField for email address

                      TextFormField(
                        autofocus: false,
                        controller: _passwordController,
                        validator: validatePassword,
                        onSaved: (value) => _password = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                         hintText: "Password",
                         border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

                      Divider(color: Colors.black),      // divider

                      SizedBox(height: 20.0),

                      Material(                   // login button
                        elevation: 5.0,
                        borderRadius: BorderRadius.circular(20.0),
                        color: Colors.green,
                        child: MaterialButton(
                          minWidth: MediaQuery.of(context).size.width,
                 padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () {

                            if (_formKey.currentState.validate()) {
                              Navigator.push(context,
                               MaterialPageRoute(builder: (context) {
                                return LoginFormWithAutoValidation();
                              }));
                            } else {
                              setState(() {
                             // validation error
                                _autoValidate = true;
                              });
                            }
                          },
                          child: Text("Login",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20)),
                        ),
                      ),
                      SizedBox(height: 10.0),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
</code>```

Body:
I feel as if this should be something very easy but I cannot figure it out, I have everything working I just need to make the 'email' and 'password' fields change to whatever the user enters. Below is my controller where the data gets sent via HTTP

 postData() async {
    try {
      var response = await http
          .post(Uri.parse("http://exampleIP/untitled/authentication/login.php"), body: {
        "username": 'email',   // needs to be what user inputs//
        "password": 'password' // needs to be what user inputs//

I understand all the code is not there but the code works I just need to know how to get the input from the form

Here is form code

import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutx/flutx.dart';
import 'package:harralander/images.dart';
import 'package:harralander/theme/app_theme.dart';

import '../controllers/login_controller.dart';

class LogInScreen extends StatefulWidget {
  const LogInScreen({Key? key}) : super(key: key);

  @override
  _LogInScreenState createState() => _LogInScreenState();
}

class _LogInScreenState extends State<LogInScreen> {
  late ThemeData theme;
  late CustomTheme customTheme;

  late LogInController controller;
  late OutlineInputBorder outlineInputBorder;

  @override
  void initState() {
    super.initState();
    theme = AppTheme.theme;
    customTheme = AppTheme.customTheme;

    controller = FxControllerStore.putOrFind(LogInController());
    outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(4)),
      borderSide: BorderSide(
        color: Colors.transparent,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FxBuilder<LogInController>(
        controller: controller,
        builder: (controller) {
          return _buildBody();
        });
  }

  Widget _buildBody() {
    return Scaffold(
      body: Padding(
        padding: FxSpacing.x(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FxText.h3(
              'Log In',
              fontWeight: 700,
            ),
            FxSpacing.height(20),
            Form(
              key: controller.formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.mail,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Email Address",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.emailTE,
                    validator: controller.validateEmail,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                  FxSpacing.height(20),
                  TextFormField(
                    style: FxTextStyle.b2(),
                    decoration: InputDecoration(
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                        filled: true,
                        isDense: true,
                        fillColor: customTheme.card,
                        prefixIcon: Icon(
                          FeatherIcons.lock,
                          color: theme.colorScheme.onBackground,
                        ),
                        hintText: "Password",
                        enabledBorder: outlineInputBorder,
                        focusedBorder: outlineInputBorder,
                        border: outlineInputBorder,
                        contentPadding: FxSpacing.all(16),
                        hintStyle: FxTextStyle.b2(),
                        isCollapsed: true),
                    maxLines: 1,
                    controller: controller.passwordTE,
                    validator: controller.validatePassword,
                    cursorColor: theme.colorScheme.onBackground,
                  ),
                ],
              ),
            ),
            FxSpacing.height(20),
            Align(
              alignment: Alignment.centerRight,
              child: FxButton.text(
                  onPressed: () {
                    controller.goToForgotPasswordScreen();
                  },
                  padding: FxSpacing.zero,
                  splashColor: customTheme.fitnessPrimary.withAlpha(40),
                  child: FxText.b3(
                    'Forgot password ?',
                    color: customTheme.fitnessPrimary,
                  )),
            ),
            FxSpacing.height(20),
            Row(
              children: [
                FxButton(
                    padding: FxSpacing.xy(16, 12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.card,
                    splashColor: theme.colorScheme.onBackground.withAlpha(40),
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: Row(
                      children: [
                        Image(
                          image: AssetImage(Images.google),
                          height: 17,
                          width: 17,
                        ),
                        FxSpacing.width(20),
                        FxText.l2(
                          'Login with Google',
                          fontWeight: 600,
                          color: theme.colorScheme.onBackground,
                        ),
                      ],
                    )),
                FxSpacing.width(20),
                Expanded(
                  child: FxButton(
                    padding: FxSpacing.y(12),
                    onPressed: () {
                      controller.postData();
                    },
                    backgroundColor: customTheme.fitnessPrimary,
                    elevation: 0,
                    borderRadiusAll: 4,
                    child: FxText.b2(
                      'Log In',
                      color: customTheme.fitnessOnPrimary,
                      fontWeight: 600,
                    ),
                  ),
                ),
              ],
            ),
            FxSpacing.height(20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FxText.b3(
                  'New to Harralander? ',
                ),
                FxButton.text(
                    onPressed: () {
                      controller.goToRegisterScreen();
                    },
                    padding: FxSpacing.zero,
                    splashColor: customTheme.fitnessPrimary.withAlpha(40),
                    child: FxText.b3(
                      'Register',
                      color: customTheme.fitnessPrimary,
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Thank you

Body:
you have to TextEditingController to get user input, and store those in varibale or access through using .text method.
Eg:

TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

String? uName;
String? pwd;

//inside from:
//we can get data using
uName = _emailController.text;
pwd = _passwordController.text;
//or we can pass this directly as a parameter like this:
_passwordController.text

import 'package:flutter/material.dart';
import 'package:flutterloginform/validation.dart';

class LoginFormWithAutoValidation extends StatefulWidget {
  @override
  _LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
}

class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {

  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);

  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

  final _formKey = new GlobalKey<FormState>();

  String _email;
  String _password;

  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.green[400],
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              color: Color(0xffF3F3F3),
              elevation: 5,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Form(
                  key: _formKey,
                  autovalidate: _autoValidate,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[

                      Center(
                          child: Text(
                        "Your Logo Here",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 25,
                        ),
                      )),
                      SizedBox(height: 25.0),

             // TextFormField for email address

                      TextFormField(
                        keyboardType: TextInputType.emailAddress,
                        autofocus: false,
                        controller: _emailController,
                        validator: validateEmail,
                        onSaved: (value) => _email = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Email",
                          border: OutlineInputBorder(
                           borderRadius:BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

            // TextFormField for email address

                      TextFormField(
                        autofocus: false,
                        controller: _passwordController,
                        validator: validatePassword,
                        onSaved: (value) => _password = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                         hintText: "Password",
                         border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

                      Divider(color: Colors.black),      // divider

                      SizedBox(height: 20.0),

                      Material(                   // login button
                        elevation: 5.0,
                        borderRadius: BorderRadius.circular(20.0),
                        color: Colors.green,
                        child: MaterialButton(
                          minWidth: MediaQuery.of(context).size.width,
                 padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () {

                            if (_formKey.currentState.validate()) {
                              Navigator.push(context,
                               MaterialPageRoute(builder: (context) {
                                return LoginFormWithAutoValidation();
                              }));
                            } else {
                              setState(() {
                             // validation error
                                _autoValidate = true;
                              });
                            }
                          },
                          child: Text("Login",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20)),
                        ),
                      ),
                      SizedBox(height: 10.0),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }


问:
Suggestion for shopping cart update
I am working on a shopping on a online store for my brother. I am stuck in the in the process where the buyers cart is updated when he adds items to the basket . I want to know how to remember the buyer (as my bro wants user can buy without sign in,so no case of user id etc)? Should I create a session for him and save it to database?</p>

答: The standard way is indeed to use a session and the link SamT gave should suffice. But no need to store it to the database (yet).</p>

Title: Suggestion for shopping cart update


问:
Cookie not set in request header when request is sent from React
My backend is in Django and Frontend is in React.
I have set up CROS header and added settings as follows.
Django settings

For sending request I am using fetch and i have set credentials: 'include'.

I am using the session based authentication, So when I signin session of a user starts. Then from the parent component (from useEffect) I send a request to backend to fetch Jobs. Things work fine in this case. Below is the header of this particular request. It has COOKIE

Request header 1

when I send request from child component of react, COOKIE is not present in the header. Below is the header of this particular request.

Request header 2

I am not able to get why this thing is happening, One more difference in both the request headers is the value of HTTP_SEC_FETCH_SITE in request header.
In first request value of HTTP_SEC_FETCH_SITE is same-site whereas in second request HTTP_SEC_FETCH_SITE is cross-site. Even though request is sent through http://localhost:3000 in both cases why value of HTTP_SEC_FETCH_SITE is different.

答:
value of HTTP_SEC_FETCH_SITE was different for these two requests beccause baseurl for first request was set to http://localhost:8000/  where as for second request it was
http://127.0.0.1:8000/.

Event though both are local servers on same port, don't know why this thing happens.

I changed both baseurl to http://localhost:8000/ and things worked. Cookie was set in both the requests.


问:
How to install aws-cli on alpine?
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

```<code>  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages
</code>```

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

```<code>~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'
</code>```

Thanks!

答:
I've been using the image node:14-alpine

```<code>apk add --update --no-cache curl ca-certificates \
&& curl -sL -o /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub \
&& curl -sL -o glibc-2.28-r0.apk https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk \
&& apk add glibc-2.28-r0.apk \
&& curl -sL -o glibc-bin-2.28-r0.apk https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-bin-2.28-r0.apk \
&& apk add glibc-bin-2.28-r0.apk \
&& curl -sL -o awscliv2.zip https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.0.30.zip \
&& unzip awscliv2.zip \
&& ./aws/install \
&& rm -Rf aws/ awscliv2.zip glibc-2.28-r0.apk glibc-bin-2.28-r0.apk \
&& aws --version
</code>```

Title: How to install aws-cli on alpine?

Body:
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'

Thanks!

Body:
I've been using the image node:14-alpine

apk add --update --no-cache curl ca-certificates \
&& curl -sL -o /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub \
&& curl -sL -o glibc-2.28-r0.apk https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk \
&& apk add glibc-2.28-r0.apk \
&& curl -sL -o glibc-bin-2.28-r0.apk https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-bin-2.28-r0.apk \
&& apk add glibc-bin-2.28-r0.apk \
&& curl -sL -o awscliv2.zip https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.0.30.zip \
&& unzip awscliv2.zip \
&& ./aws/install \
&& rm -Rf aws/ awscliv2.zip glibc-2.28-r0.apk glibc-bin-2.28-r0.apk \
&& aws --version


问:
removing new line character from incoming stream using sed
I am new to shell scripting and i am trying to remove new line character from each line using SED. this is what i have done so far :

```<code>printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g'
</code>```

removes only Ist new line character.
I somewhere found this command :

```<code>printf "{new\nto\nlinux}" | sed ':a;N;$!ba;s/\n/ /g'
</code>```

but it gives :"ba: Event not found."

if i do:

```<code>printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g' | sed ':a;N;s/\n/ /g'
</code>```

then it gives correct output but i am looking for something better as i am not sure how many new character i will get when i run the script.
incoming stream is from echo or printf or some variable in script.

答:
Use perl instead of sed. perl is similar to sed:</p>
```<code>ubuntu@ubuntu:/$ printf "{new\nto\nlinux}" | sed 's/\n/ /g'; echo ''
{new
to
linux}
ubuntu@ubuntu:/$ printf "{new\nto\nlinux}" | perl -pe 's/\n/ /g'; echo ''
{new to linux}
ubuntu@ubuntu:/$ echo -e "new\nto\nlinux\ntest\n1\n2 3" | perl -pe 's/\n/_ _/g'; echo ''
new_ _to_ _linux_ _test_ _1_ _2 3_ _
ubuntu@ubuntu:/$
</code>```

Body:
I am new to shell scripting and i am trying to remove new line character from each line using SED. this is what i have done so far :

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g'

removes only Ist new line character.
I somewhere found this command :

printf "{new\nto\nlinux}" | sed ':a;N;$!ba;s/\n/ /g'

but it gives :"ba: Event not found."

if i do:

printf "{new\nto\nlinux}" | sed ':a;N;s/\n/ /g' | sed ':a;N;s/\n/ /g'

then it gives correct output but i am looking for something better as i am not sure how many new character i will get when i run the script.
incoming stream is from echo or printf or some variable in script.

Body:
Use perl instead of sed. perl is similar to sed:

ubuntu@ubuntu:/$ printf "{new\nto\nlinux}" | sed 's/\n/ /g'; echo ''
{new
to
linux}
ubuntu@ubuntu:/$ printf "{new\nto\nlinux}" | perl -pe 's/\n/ /g'; echo ''
{new to linux}
ubuntu@ubuntu:/$ echo -e "new\nto\nlinux\ntest\n1\n2 3" | perl -pe 's/\n/_ _/g'; echo ''
new_ _to_ _linux_ _test_ _1_ _2 3_ _
ubuntu@ubuntu:/$


问:
Opening XPS document in .Net causes a memory leak
The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.

'****** Console application BEGINS.

```<code>Module Main

    Const DefaultTestFilePath As String = "D:\Test.xps"
    Const DefaultLoopRuns As Integer = 1000

    Public Sub Main(ByVal Args As String())
        Dim PathToTestXps As String = DefaultTestFilePath
        Dim NumberOfLoops As Integer = DefaultLoopRuns

        If (Args.Count >= 1) Then PathToTestXps = Args(0)
        If (Args.Count >= 2) Then NumberOfLoops = CInt(Args(1))

        Console.Clear()
        Console.WriteLine("Start - {0}", GC.GetTotalMemory(True))
        For LoopCount As Integer = 1 To NumberOfLoops

            Console.CursorLeft = 0
            Console.Write("Loop {0:d5}", LoopCount)

            ' The more complex the XPS document and the more loops, the more memory is lost.
            Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
                Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence

                ' This line leaks a chunk of memory each time, when commented out it does not.
                FixedDocSequence = XPSItem.GetFixedDocumentSequence
            End Using
        Next
        Console.WriteLine()
        GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals).
        Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True))

        Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).")
        Console.ReadKey()

    End Sub

End Module
</code>```

'****** Console application ENDS.

The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).

The code was originally in another thread and class but has been simplified to this.

Any help greatly appreciated.

Ryan

答:
Interesting. The problem is still present in .net framework 4.0. My code was leaking ferociously.

The proposed fix -- where UpdateLayout is called in a loop immediately after creation of the FixedDocumentSequence did NOT fix the problem for me on a 400 page test document.

However, the following solution DID fix the problem for me.  As in previous fixes, I moved the call to GetFixedDocumentSequence() outside the for-each-page loop. The "using" clause... fair warning that I'm still not sure it's correct. But it's not hurting. The document is subsequently re-used to generate page previews on-screen. So it doesn't seem to hurt.

```<code>DocumentPaginator paginator
     =  document.GetFixedDocumentSequence().DocumentPaginator;
int numberOfPages = paginator.ComputePageCount();

for (int i = 0; i < NumberOfPages; ++i)
{
    DocumentPage docPage = paginator.GetPage(nPage);
    using (docPage)   // using is *probably* correct.
    {
        //  VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

        ((FixedPage)(docPage.Visual)).UpdateLayout();

        //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //  Adding THAT line cured my leak.

        RenderTargetBitmap bitmap = GetXpsPageAsBitmap(docPage, dpi);

        .... etc...
    }

}
</code>```

In reality, the fix line goes inside my GetXpsPageAsBitmap routine (ommited for clarity), which is pretty much identical to previously posted code.

Thanks to all who contributed.

OwnerDisplayName: Ryan ONeill

ContentLicense: CC BY-SA 2.5

Body:
The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.

'****** Console application BEGINS.

Module Main

    Const DefaultTestFilePath As String = "D:\Test.xps"
    Const DefaultLoopRuns As Integer = 1000

    Public Sub Main(ByVal Args As String())
        Dim PathToTestXps As String = DefaultTestFilePath
        Dim NumberOfLoops As Integer = DefaultLoopRuns

        If (Args.Count >= 1) Then PathToTestXps = Args(0)
        If (Args.Count >= 2) Then NumberOfLoops = CInt(Args(1))

        Console.Clear()
        Console.WriteLine("Start - {0}", GC.GetTotalMemory(True))
        For LoopCount As Integer = 1 To NumberOfLoops

            Console.CursorLeft = 0
            Console.Write("Loop {0:d5}", LoopCount)

            ' The more complex the XPS document and the more loops, the more memory is lost.
            Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
                Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence

                ' This line leaks a chunk of memory each time, when commented out it does not.
                FixedDocSequence = XPSItem.GetFixedDocumentSequence
            End Using
        Next
        Console.WriteLine()
        GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals).
        Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True))

        Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).")
        Console.ReadKey()

    End Sub

End Module

'****** Console application ENDS.

The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).

The code was originally in another thread and class but has been simplified to this.

Any help greatly appreciated.

Ryan

LastEditorDisplayName: Joel Coehoorn

Body:
Interesting. The problem is still present in .net framework 4.0. My code was leaking ferociously.

The proposed fix -- where UpdateLayout is called in a loop immediately after creation of the FixedDocumentSequence did NOT fix the problem for me on a 400 page test document.

However, the following solution DID fix the problem for me.  As in previous fixes, I moved the call to GetFixedDocumentSequence() outside the for-each-page loop. The "using" clause... fair warning that I'm still not sure it's correct. But it's not hurting. The document is subsequently re-used to generate page previews on-screen. So it doesn't seem to hurt.

DocumentPaginator paginator
     =  document.GetFixedDocumentSequence().DocumentPaginator;
int numberOfPages = paginator.ComputePageCount();

for (int i = 0; i < NumberOfPages; ++i)
{
    DocumentPage docPage = paginator.GetPage(nPage);
    using (docPage)   // using is *probably* correct.
    {
        //  VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

        ((FixedPage)(docPage.Visual)).UpdateLayout();

        //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //  Adding THAT line cured my leak.

        RenderTargetBitmap bitmap = GetXpsPageAsBitmap(docPage, dpi);

        .... etc...
    }

}

In reality, the fix line goes inside my GetXpsPageAsBitmap routine (ommited for clarity), which is pretty much identical to previously posted code.

Thanks to all who contributed.