问:
Flutter listview not updating after data update
I have a ListView inside a bottomSheet, that is built using an array of elements. Currently I have one item in there "empty" which is then .clear()ed and populated after an async DB call.

The variable update is correct, and I try to use setState((){}) but the ListView isn't updated at all. I need to close the bottomSheet, reopen it, and the ListView then has the correct items.

Do I need to just call setState or does the bottomSheet builder need to be flagged to update?

Main ListView section:

```<code> @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Map'),
          backgroundColor: Colors.green[700],
        ),

        //Put in a stack widget so can layer other widgets on top of map widget
        body: Stack(
          children: <Widget>[
            GoogleMap(
              mapType: _currentMapType,
              markers: _markers,
              onMapCreated: _onMapCreated,
              onCameraMove: _onCameraMove,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          ...
                      ),

                    ),

                    SizedBox(width: 16.0),

                    FloatingActionButton(
                      ...
                    ),

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.file_download, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {
                            showBottomSheet(
                                context: context,
                                builder: (context) {
                                  return ListView(
                                    padding: EdgeInsets.all(15.0),
                                    children: <Widget>[

                                         ...

                                      Divider(),

                                      ListTile(
                                        title: Text("Remote JSON Download"),
                                        trailing:
                                        Icon(Icons.refresh),
                                        selected: true,
                                        onTap: _OnPressedReloadJSON,               <-------------
                                      ),

                                      Divider(),

                                      Container(
                                        height: 150.0,
                                        child: ListView.builder(               <-------------
                                          scrollDirection: Axis.horizontal,

                                          itemCount : testList.length,
                                          itemBuilder: (BuildContext context, int index) {
                                              return Container(
                                                padding: EdgeInsets.all(5.0),
                                                margin: EdgeInsets.all(5.0),
                                                width: 150.0,
                                                color: Colors.red,
                                                child: Text(testList[index]),
                                              );
                                          },

                                        ),
                                      ),
</code>```

Async Get:

```<code>class _MyAppState extends State<MyApp> {

  ...

  _OnPressedReloadJSON() {
    fetchJSONAndMakeListTile();
  }

  ...

  List<String> testList= ["empty"];

  Future<http.Response> fetchJSONAndMakeListTile() async {
    final response = await http.get('https://..... file.json');

    // If the server did return a 200 OK response, then parse the JSON.
    if (response.statusCode == 200) {
      List<db_manager.MyObject> myObjects = (json.decode(response.body) as List)
          .map((e) => db_manager.MyObject.fromJson(e))
          .toList();

      testList.clear();
      myObjects.forEach((db_manager.MyObject al) {
        testList.add(al.code);
        print("debug:"+al.code+" - "+al.name);        <------------- prints correctly
      });

      //TODO Does this even work?
      //Trigger update of state - ie redraw/reload UI elements
      setState(() {});

    } else {
      // If the server did not return a 200 OK response, then throw an exception.
      print(response);
      throw Exception('Failed to load json');
    }
  }
</code>```

UPDATE:

I've abstracted the BottomSheet builder into another class (as per another answer) as its own StatefulWidget but I can't seem to access the void onPress() method from my main dart file. If the BottomSheet creation/builder is in this separate dart file, how do I call it to build and then update its state with the async call updating the listview contents List?

BottomSheetWidget.dart

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

class _BottomSheetDatabases extends State<BottomSheetDatabases> {

  void _onpress() {

  }

  void loadMe() {

  }

  List<String> testList= ["empty"];

  @override
  Widget build(BuildContext context) {
    return BottomSheet(

        builder: (context) {
          return ListView(
            padding: EdgeInsets.all(15.0),
            children: <Widget>[
              ListTile(
                ...

              ),

              Divider(),

              Container(
                height: 150.0,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,

                  itemCount: testList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      key: UniqueKey(),
                      //TODO  ??
                      padding: EdgeInsets.all(5.0),
                      margin: EdgeInsets.all(5.0),
                      width: 150.0,
                      color: Colors.red,
                      child: Text(testList[index]),
                    );
                  },

                ),
                //),
                //),
              ),

              ...
</code>```

Main.dart:

```<code>  void _loadSheetDatabases() {
    BottomSheetWidget bottomSheetwidget = BottomSheetWidget();
    bottomSheetwidget.loadMe();
  }
</code>```

答:
Your ListView is only built when onPressed is called on your FloatingActionButton.

I assume that's why it doesn't get built again when the state changes.

You could wrap the code to build the ListView in a new StatefulWidget with its own state and then update it when testList changes.

Body:
I have a ListView inside a bottomSheet, that is built using an array of elements. Currently I have one item in there "empty" which is then .clear()ed and populated after an async DB call.

The variable update is correct, and I try to use setState((){}) but the ListView isn't updated at all. I need to close the bottomSheet, reopen it, and the ListView then has the correct items.

Do I need to just call setState or does the bottomSheet builder need to be flagged to update?

Main ListView section:

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Map'),
          backgroundColor: Colors.green[700],
        ),

        //Put in a stack widget so can layer other widgets on top of map widget
        body: Stack(
          children: <Widget>[
            GoogleMap(
              mapType: _currentMapType,
              markers: _markers,
              onMapCreated: _onMapCreated,
              onCameraMove: _onCameraMove,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          ...
                      ),

                    ),

                    SizedBox(width: 16.0),

                    FloatingActionButton(
                      ...
                    ),

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.file_download, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {
                            showBottomSheet(
                                context: context,
                                builder: (context) {
                                  return ListView(
                                    padding: EdgeInsets.all(15.0),
                                    children: <Widget>[

                                         ...

                                      Divider(),

                                      ListTile(
                                        title: Text("Remote JSON Download"),
                                        trailing:
                                        Icon(Icons.refresh),
                                        selected: true,
                                        onTap: _OnPressedReloadJSON,               <-------------
                                      ),

                                      Divider(),

                                      Container(
                                        height: 150.0,
                                        child: ListView.builder(               <-------------
                                          scrollDirection: Axis.horizontal,

                                          itemCount : testList.length,
                                          itemBuilder: (BuildContext context, int index) {
                                              return Container(
                                                padding: EdgeInsets.all(5.0),
                                                margin: EdgeInsets.all(5.0),
                                                width: 150.0,
                                                color: Colors.red,
                                                child: Text(testList[index]),
                                              );
                                          },

                                        ),
                                      ),

Async Get:

class _MyAppState extends State<MyApp> {

  ...

  _OnPressedReloadJSON() {
    fetchJSONAndMakeListTile();
  }

  ...

  List<String> testList= ["empty"];

  Future<http.Response> fetchJSONAndMakeListTile() async {
    final response = await http.get('https://..... file.json');

    // If the server did return a 200 OK response, then parse the JSON.
    if (response.statusCode == 200) {
      List<db_manager.MyObject> myObjects = (json.decode(response.body) as List)
          .map((e) => db_manager.MyObject.fromJson(e))
          .toList();

      testList.clear();
      myObjects.forEach((db_manager.MyObject al) {
        testList.add(al.code);
        print("debug:"+al.code+" - "+al.name);        <------------- prints correctly
      });

      //TODO Does this even work?
      //Trigger update of state - ie redraw/reload UI elements
      setState(() {});

    } else {
      // If the server did not return a 200 OK response, then throw an exception.
      print(response);
      throw Exception('Failed to load json');
    }
  }

UPDATE:

I've abstracted the BottomSheet builder into another class (as per another answer) as its own StatefulWidget but I can't seem to access the void onPress() method from my main dart file. If the BottomSheet creation/builder is in this separate dart file, how do I call it to build and then update its state with the async call updating the listview contents List?

BottomSheetWidget.dart

class BottomSheetDatabases extends StatefulWidget {
  @override
  _BottomSheetDatabases createState() => _BottomSheetDatabases();
}

class _BottomSheetDatabases extends State<BottomSheetDatabases> {

  void _onpress() {

  }

  void loadMe() {

  }

  List<String> testList= ["empty"];

  @override
  Widget build(BuildContext context) {
    return BottomSheet(

        builder: (context) {
          return ListView(
            padding: EdgeInsets.all(15.0),
            children: <Widget>[
              ListTile(
                ...

              ),

              Divider(),

              Container(
                height: 150.0,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,

                  itemCount: testList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      key: UniqueKey(),
                      //TODO  ??
                      padding: EdgeInsets.all(5.0),
                      margin: EdgeInsets.all(5.0),
                      width: 150.0,
                      color: Colors.red,
                      child: Text(testList[index]),
                    );
                  },

                ),
                //),
                //),
              ),

              ...

Main.dart:

  void _loadSheetDatabases() {
    BottomSheetWidget bottomSheetwidget = BottomSheetWidget();
    bottomSheetwidget.loadMe();
  }


来源: stackexchange

问:
Apache POI SXSSF Shows NullPointerException on flush rows
I have 500 rows in my table. When I'm using setRandomAccessWindowSize(1000) it's working fine. Data is exported successfully in Excel file from resultset, But when I use setRandomAccessWindowSize(100) it is giving me a
NullPointerException I don't know what I'm doing wrong. Please suggest proper way to do this.

Here's my code:

```<code>workbook = new SXSSFWorkbook(100);      //SXSSF workbook
workbook.setCompressTempFiles(true);
SXSSFSheet spreadsheet = workbook.createSheet("Sheet1");     //Generating Excel file
SXSSFRow row;
SXSSFCell cell;
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();//Create font
font.setBold(true);//Make font bold
style.setFont(font);//set it to bold

int y = 1;
if (rs.isBeforeFirst() == true) {
    while (rs.next()) {
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("SR NO");
        cell.setCellStyle(style);
        for (int s = 1; s <= rsmd.getColumnCount(); s++) {
            cell = row.createCell(s);
            cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
            cell.setCellStyle(style);
        }
        row = spreadsheet.createRow(y);
        cell = row.createCell(0);
        cell.setCellValue(y + "");
        //spreadsheet.autoSizeColumn(0);
        for (int x = 1; x <= rsmd.getColumnCount(); x++) {
            cell = row.createCell(x);
            String address = new CellReference(cell).formatAsString();
            cell.setCellValue(address);
            cell.setCellValue(rs.getString(+x));
            //spreadsheet.autoSizeColumn(x);
        }
        y++;
    }

    FileOutputStream out = new FileOutputStream(new File(destination));
    workbook.write(out);
    out.close();
    workbook.dispose();
</code>```

答:
I have updated while loop in above code. It was writing 0th row multiple times. That's why on 101th row it was giving NullPointer exception as 0th row is already flushed.

Here's my fix-

```<code>if (rs.isBeforeFirst() == true) {
    while (rs.next()) {
        //writing columns
        if (rs.isFirst()) {
            row = spreadsheet.createRow(0);
            cell = row.createCell(0);
            cell.setCellValue("SR NO");
            cell.setCellStyle(style);
            for (int s = 1; s <= rsmd.getColumnCount(); s++) {
                cell = row.createCell(s);
                cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
                cell.setCellStyle(style);
            }
        }
        //Writing data
        row = spreadsheet.createRow(y);
        cell = row.createCell(0);
        cell.setCellValue(y + "");
        //spreadsheet.autoSizeColumn(0);
        for (int x = 1; x <= rsmd.getColumnCount(); x++) {
            cell = row.createCell(x);
            cell.setCellValue(rs.getString(+x));
            //spreadsheet.autoSizeColumn(x);
        }
        y++;
    }

    FileOutputStream out = new FileOutputStream(new File(destination));
    workbook.write(out);
    out.close();
    workbook.dispose();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 500 rows in my table. When I'm using setRandomAccessWindowSize(1000) it's working fine. Data is exported successfully in Excel file from resultset, But when I use setRandomAccessWindowSize(100) it is giving me a
NullPointerException I don't know what I'm doing wrong. Please suggest proper way to do this.

Here's my code:

workbook = new SXSSFWorkbook(100);      //SXSSF workbook
workbook.setCompressTempFiles(true);
SXSSFSheet spreadsheet = workbook.createSheet("Sheet1");     //Generating Excel file
SXSSFRow row;
SXSSFCell cell;
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();//Create font
font.setBold(true);//Make font bold
style.setFont(font);//set it to bold

int y = 1;
if (rs.isBeforeFirst() == true) {
    while (rs.next()) {
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("SR NO");
        cell.setCellStyle(style);
        for (int s = 1; s <= rsmd.getColumnCount(); s++) {
            cell = row.createCell(s);
            cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
            cell.setCellStyle(style);
        }
        row = spreadsheet.createRow(y);
        cell = row.createCell(0);
        cell.setCellValue(y + "");
        //spreadsheet.autoSizeColumn(0);
        for (int x = 1; x <= rsmd.getColumnCount(); x++) {
            cell = row.createCell(x);
            String address = new CellReference(cell).formatAsString();
            cell.setCellValue(address);
            cell.setCellValue(rs.getString(+x));
            //spreadsheet.autoSizeColumn(x);
        }
        y++;
    }

    FileOutputStream out = new FileOutputStream(new File(destination));
    workbook.write(out);
    out.close();
    workbook.dispose();

Body:
I have updated while loop in above code. It was writing 0th row multiple times. That's why on 101th row it was giving NullPointer exception as 0th row is already flushed.

Here's my fix-

if (rs.isBeforeFirst() == true) {
    while (rs.next()) {
        //writing columns
        if (rs.isFirst()) {
            row = spreadsheet.createRow(0);
            cell = row.createCell(0);
            cell.setCellValue("SR NO");
            cell.setCellStyle(style);
            for (int s = 1; s <= rsmd.getColumnCount(); s++) {
                cell = row.createCell(s);
                cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
                cell.setCellStyle(style);
            }
        }
        //Writing data
        row = spreadsheet.createRow(y);
        cell = row.createCell(0);
        cell.setCellValue(y + "");
        //spreadsheet.autoSizeColumn(0);
        for (int x = 1; x <= rsmd.getColumnCount(); x++) {
            cell = row.createCell(x);
            cell.setCellValue(rs.getString(+x));
            //spreadsheet.autoSizeColumn(x);
        }
        y++;
    }

    FileOutputStream out = new FileOutputStream(new File(destination));
    workbook.write(out);
    out.close();
    workbook.dispose();


问:
Recovering mysql case sensitive fulltext search after dropping index
I have a database where I deleted the fulltext index on a column. After re-adding it, I cannot get back the same original behavior.

Here's an example.

I create the table and set the character set to utf8_bin. I also add a fulltext index:

CREATE TABLE testtable (
             `Date` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
             `Headline` VARCHAR(256) CHARACTER SET utf8 NOT NULL,
             `Description` text CHARACTER SET utf8 NOT NULL,
            PRIMARY KEY (`Headline`)
            );
ALTER TABLE testtable CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
ALTER TABLE testtable ADD FULLTEXT (Headline);
```

<p>I add some dummy data:</p>

<pre class="lang-sh prettyprint-override"><code>INSERT INTO testtable (Headline,Description) VALUES ("the story of how an apple fell from the tree","");
INSERT INTO testtable (Headline,Description) VALUES ("Apple did something blah","");
</code>```

Now if I search:

SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('apple' IN BOOLEAN MODE);
```

```'2020-02-19 17:16:05', 'the story of how an apple fell from the tree'
```

<p>and</p>

<pre class="lang-sh prettyprint-override"><code>SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('Apple' IN BOOLEAN MODE);
</code>```

```<code>'2020-02-19 17:18:38', 'Apple did something blah'
</code>```

Great, that works, and that is the result I want.

Now let's drop the index, re-add it, and try that again:

DROP INDEX Headline ON testtable;
#ALTER TABLE testtable CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; # I also tried this with no difference
ALTER TABLE testtable ADD FULLTEXT (Headline);
SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('Apple' IN BOOLEAN MODE);
```

Gives null as a response, but searching for apple returns both rows.

So the question is, what is going on here, and more importantly, how do I get the table back to the way it was: a case sensitive fulltext index that gives me separate results for Apple and apple?

(Using Mysql 5.7, with InnoDB engine)

Thanks for the help!

答:
https://dev.mysql.com/doc/refman/5.6/en/fulltext-natural-language.html

By default, the search is performed in case-insensitive fashion. To
  perform a case-sensitive full-text search, use a binary collation for
  the indexed columns. For example, a column that uses the latin1
  character set of can be assigned a collation of latin1_bin to make it
  case-sensitive for full-text searches.

Body:
I have a database where I deleted the fulltext index on a column. After re-adding it, I cannot get back the same original behavior.

Here's an example.

I create the table and set the character set to utf8_bin. I also add a fulltext index:

CREATE TABLE testtable (
             `Date` timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
             `Headline` VARCHAR(256) CHARACTER SET utf8 NOT NULL,
             `Description` text CHARACTER SET utf8 NOT NULL,
            PRIMARY KEY (`Headline`)
            );
ALTER TABLE testtable CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
ALTER TABLE testtable ADD FULLTEXT (Headline);

I add some dummy data:

INSERT INTO testtable (Headline,Description) VALUES ("the story of how an apple fell from the tree","");
INSERT INTO testtable (Headline,Description) VALUES ("Apple did something blah","");

Now if I search:

SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('apple' IN BOOLEAN MODE);

'2020-02-19 17:16:05', 'the story of how an apple fell from the tree'

and

SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('Apple' IN BOOLEAN MODE);

'2020-02-19 17:18:38', 'Apple did something blah'

Great, that works, and that is the result I want.

Now let's drop the index, re-add it, and try that again:

DROP INDEX Headline ON testtable;
#ALTER TABLE testtable CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; # I also tried this with no difference
ALTER TABLE testtable ADD FULLTEXT (Headline);
SELECT `Date`,`Headline` FROM testtable WHERE MATCH (Headline) AGAINST ('Apple' IN BOOLEAN MODE);

Gives null as a response, but searching for apple returns both rows.

So the question is, what is going on here, and more importantly, how do I get the table back to the way it was: a case sensitive fulltext index that gives me separate results for Apple and apple?

(Using Mysql 5.7, with InnoDB engine)

Thanks for the help!


问:
Pushing an empty array into the state(userAnswer array) for every question asked so I can use those arrays to keep track of user answers
Here is what I have so far

```<code>AssignUserAnswerArray = () => {
        for (var i = 0; i < SurveyData.length; i++) {
            console.log("I am in the for loop assigning arrays")
            this.setState(prevstate => {
                let test = [...prevstate.userAnswers];
                test.push([]);
                return ({ userAnswers: test })

            })

        }
    }

state = {
        userAnswers: [],
       currentQuestion: 0,
        //options: []
    }
let test = AssignUserAnswerArray();
console.log(test)
</code>```

output:
26 I am in the for loop assigning arrays

0

The console.log repeats the correct number of times I am just not pushing an empty array to the state correctly. When AssignUserAnswerArray gets called it should make userAnswers contain as many empty arrays as for loop iterations.

答:
Hard to understand why you have it like this:

for (var i = 0; i < SurveyData.length; i++) {
            console.log("I am in the for loop assigning arrays")
            this.setState(prevstate => {
                let test = [...prevstate.userAnswers];
                test.push([]);
                return ({ userAnswers: test })

            })

        }
```

<p>perhaps something like:</p>

<pre class="lang-js prettyprint-override"><code>this.setState(prevstate => {
    let test = [...prevstate.userAnswers];
    for (var i = 0; i < SurveyData.length; i++) {
       test.push([]);
    }
    return {
        userAnswers: test
    };
});
</code>```

?

Body:
Here is what I have so far

AssignUserAnswerArray = () => {
        for (var i = 0; i < SurveyData.length; i++) {
            console.log("I am in the for loop assigning arrays")
            this.setState(prevstate => {
                let test = [...prevstate.userAnswers];
                test.push([]);
                return ({ userAnswers: test })

            })

        }
    }

state = {
        userAnswers: [],
       currentQuestion: 0,
        //options: []
    }
let test = AssignUserAnswerArray();
console.log(test)

output:
26 I am in the for loop assigning arrays

0

The console.log repeats the correct number of times I am just not pushing an empty array to the state correctly. When AssignUserAnswerArray gets called it should make userAnswers contain as many empty arrays as for loop iterations.

Body:
Hard to understand why you have it like this:

for (var i = 0; i < SurveyData.length; i++) {
            console.log("I am in the for loop assigning arrays")
            this.setState(prevstate => {
                let test = [...prevstate.userAnswers];
                test.push([]);
                return ({ userAnswers: test })

            })

        }

perhaps something like:

this.setState(prevstate => {
    let test = [...prevstate.userAnswers];
    for (var i = 0; i < SurveyData.length; i++) {
       test.push([]);
    }
    return {
        userAnswers: test
    };
});

?


问:
Bad formation on wrapfiure latex overlap image text

I am using overleaf online to compile my report and I am experiencing this problem with wrap figure. particularly over a weight of 6cm I experience the problem as shown in figure, image overlaps the text while independent on the size of the image there is some text with a weird formation in the successive page. Can someone help me?

```<code> \documentclass[a4paper,14pt]{extarticle}
  \usepackage{geometry}
     \usepackage[latin1]{inputenc}
   \usepackage{amsmath}
 \usepackage{amsfonts}
 \usepackage{amssymb}
 \usepackage{graphicx}
 \usepackage{subcaption}
 \usepackage{multicol}
\usepackage[english]{babel}
   \usepackage{graphicx,bm,times}
 \usepackage{mathtools}
 \usepackage{subcaption}
 \usepackage{wrapfig}
 \usepackage{siunitx}
 \usepackage{gensymb}
 \usepackage{amsmath}
 \usepackage{geometry}
  %\geometry{lmargin=1in,rmargin=1in}
   ...
   to suppress axial growth during GaInP shell growth, the nanowire cores were taken out from the reactor and the Au seed particles were removed using a cyanide based Au etchant. Shell growth was carried out in the same MOCVD as the core, using PH3, (TMIn), and TMGa as precursors gases.The shell growth temperature was set to 600 $\textdegree $C.

  \begin{wrapfigure}{l}{0.25\textwidth}
 \includegraphics[width=6cm,height=7cm]{IMAGES/nanos1.png}
%\caption{Caption1}
\label{fig:wrapfig}
\end{wrapfigure}
Transmission electron microscopy \textbf{TEM} and Electron Diffraction Spectroscopy \textbf{SEM} allow to investigate nanowires revealing its crystal structure: pure zinc blende, (without wurtzite segments, stacking faults, or twins).  Particularly high-resolution transmission electron microscopy showed dense fringes indicating significant strain (Fig A).
</code>```

答:
you could add an extra option to the wrapfigure command:

```<code>\begin{wrapfigure}[22]{L}{0.45\textwidth}
</code>```

where the '22' represents the number of lines you want to wrap around.

(Credit to Jenny who answered on a comment!)

Body:
I am using overleaf online to compile my report and I am experiencing this problem with wrap figure. particularly over a weight of 6cm I experience the problem as shown in figure, image overlaps the text while independent on the size of the image there is some text with a weird formation in the successive page. Can someone help me?

 \documentclass[a4paper,14pt]{extarticle}
  \usepackage{geometry}
     \usepackage[latin1]{inputenc}
   \usepackage{amsmath}
 \usepackage{amsfonts}
 \usepackage{amssymb}
 \usepackage{graphicx}
 \usepackage{subcaption}
 \usepackage{multicol}
\usepackage[english]{babel}
   \usepackage{graphicx,bm,times}
 \usepackage{mathtools}
 \usepackage{subcaption}
 \usepackage{wrapfig}
 \usepackage{siunitx}
 \usepackage{gensymb}
 \usepackage{amsmath}
 \usepackage{geometry}
  %\geometry{lmargin=1in,rmargin=1in}
   ...
   to suppress axial growth during GaInP shell growth, the nanowire cores were taken out from the reactor and the Au seed particles were removed using a cyanide based Au etchant. Shell growth was carried out in the same MOCVD as the core, using PH3, (TMIn), and TMGa as precursors gases.The shell growth temperature was set to 600 $\textdegree $C.

  \begin{wrapfigure}{l}{0.25\textwidth}
 \includegraphics[width=6cm,height=7cm]{IMAGES/nanos1.png}
%\caption{Caption1}
\label{fig:wrapfig}
\end{wrapfigure}
Transmission electron microscopy \textbf{TEM} and Electron Diffraction Spectroscopy \textbf{SEM} allow to investigate nanowires revealing its crystal structure: pure zinc blende, (without wurtzite segments, stacking faults, or twins).  Particularly high-resolution transmission electron microscopy showed dense fringes indicating significant strain (Fig A).

Body:
you could add an extra option to the wrapfigure command:

\begin{wrapfigure}[22]{L}{0.45\textwidth}

where the '22' represents the number of lines you want to wrap around.

(Credit to Jenny who answered on a comment!)


问:
tsc:1: maximum nested function level reached; increase FUNCNEST?
I'm trying to compile a typescript file, but run into this error:

```<code>work/gigMax [typescriptMigration●] » tsc src/mutate.ts
tsc:1: maximum nested function level reached; increase FUNCNEST?
work/gigMax [typescriptMigration●] » which tsc
tsc () {
    tsc --target ESNEXT $1
}
</code>```

Questions:

what is maximum nested function level?

What is FUNCNEST?

how can I fix this and compile from typescript down to javascript?

答:
I answered the last question by commenting out the tsc function overload in my .zshrc:

```<code>work/gigMax [typescriptMigration] » tsc src/mutate.ts
work/gigMax [typescriptMigration●] » which tsc
/home/geoff/.nvm/versions/node/v12.12.0/bin/tsc
</code>```

still curious about the other two questions.

Body:
I'm trying to compile a typescript file, but run into this error:

work/gigMax [typescriptMigration●] » tsc src/mutate.ts
tsc:1: maximum nested function level reached; increase FUNCNEST?
work/gigMax [typescriptMigration●] » which tsc
tsc () {
    tsc --target ESNEXT $1
}

Questions:

what is maximum nested function level?

What is FUNCNEST?

how can I fix this and compile from typescript down to javascript?

Body:
I answered the last question by commenting out the tsc function overload in my .zshrc:

work/gigMax [typescriptMigration] » tsc src/mutate.ts
work/gigMax [typescriptMigration●] » which tsc
/home/geoff/.nvm/versions/node/v12.12.0/bin/tsc

still curious about the other two questions.


问:
Update list Aspnet core 2.2
I would like to update a list of items most do not know how to do, when my only method adciona new items to existing inves change.

save change

```<code>public async Task<CommandResult> ExecuteAsync(EventsCommandsHandler handler)
        {
            var listItens = await handler.DbContext.ListItens
                .Where(f => f.Id == this.Id)
                .SingleOrDefaultAsync();

            listItens.SetData(
                name: Name,
                description: Description
            );

            handler.DbContext.ListItens.Update(listItens);

            if (Items.Length > 0)
            {
                var itens = Items
                    .Select(p => p.ToItemList(listItens.Id))
                    .Where(p => p != null)
                    .ToArray();
                await handler.DbContext.ItemsList.(itens);
            }

            var rows = await handler.DbContext.SaveChangesAsync();

            return await Task.FromResult(new CommandResult(rows));
        }

create intens

  public static ItemList ToItemList(this ItemCommand command, string listId)
        {
            if (string.IsNullOrWhiteSpace(command.Description))
                return null;

            var itens = new ItemList(
                id: String.IsNullOrWhiteSpace(command.Id) ? RandomId.NewId(8) : command.Id,
                description: command.Description,
                listId: listId
            );
            return itens;
        }
</code>```

I need a way for this method.
I have a list and this list has items, when I edit the list, I want to be able to delete, edit or add more items.

答:
You have a To-Do list. There should be an add button.

A post request should be sent and data should be written to the database, and page - updated when you press any button like remove, edit and add.

If you want it to be async, then you should use JavaScript or Blazor.

Title: Update list Aspnet core 2.2

Body:
I would like to update a list of items most do not know how to do, when my only method adciona new items to existing inves change.

save change

public async Task<CommandResult> ExecuteAsync(EventsCommandsHandler handler)
        {
            var listItens = await handler.DbContext.ListItens
                .Where(f => f.Id == this.Id)
                .SingleOrDefaultAsync();

            listItens.SetData(
                name: Name,
                description: Description
            );

            handler.DbContext.ListItens.Update(listItens);

            if (Items.Length > 0)
            {
                var itens = Items
                    .Select(p => p.ToItemList(listItens.Id))
                    .Where(p => p != null)
                    .ToArray();
                await handler.DbContext.ItemsList.(itens);
            }

            var rows = await handler.DbContext.SaveChangesAsync();

            return await Task.FromResult(new CommandResult(rows));
        }

create intens

  public static ItemList ToItemList(this ItemCommand command, string listId)
        {
            if (string.IsNullOrWhiteSpace(command.Description))
                return null;

            var itens = new ItemList(
                id: String.IsNullOrWhiteSpace(command.Id) ? RandomId.NewId(8) : command.Id,
                description: command.Description,
                listId: listId
            );
            return itens;
        }

I need a way for this method.
I have a list and this list has items, when I edit the list, I want to be able to delete, edit or add more items.


问:
Laravel: Undefined offset 0 in symfony/http-foundation when requiring SimpleSAMLphp
I'm attempting to upgrade dependancies on a simple Laravel 5.7 application that authenticates the user via SimpleSAMLphp, then displays some information it gets from an external API.

It looks like something changed between version 4.3.8 and version 4.4.0 of the symfony/http-foundation library included with Laravel, because when I upgrade this dependency I get the following error:

```<code>ErrorException (E_NOTICE): Undefined offset: 0 …/vendor/symfony/http-foundation/HeaderBag.php 126
</code>```

It looks like this is being triggered by requiring the SimpleSAMLphp service provider autoload file, even if I don't call any methods.

Since this is an extremely simple single page application, I'm just using middleware to handle the SimpleSAMLphp integration:

namespace App\Http\Middleware;

use Closure;

class SimpleSAMLphp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        /**
         * Load SimpleSAMLphp library
         */
        require_once('redacted/path/simplesaml/lib/_autoload.php');
        $ssphp = new \SimpleSAML\Auth\Simple('service-provider-name');
        $ssphp->requireAuth();

        return $next($request);
    }
}
```

It looks like Symfony HTTP Foundation changed how they are checking for header information in this version (I see extensive changes here: https://github.com/symfony/http-foundation/compare/v4.3.8...v4.4.0), but I don't understand why it is blowing up when SimpleSAMLphp is in the mix.

I'm deep down the rabbit hole on this one - any guidance would be much appreciated!

答:
I'm getting the same issue with Laravel 5.8 and a SimpleSAMLPhp installation.

Only had a quick poke around for now, but it seems that the HeaderBag.php is called at least twice during a request.  There is one particular call (where the error occurs) where it is trying to resolve a key of "Content-Type", which exists in $header as "content-type" (lowercase) but cannot be resolved due to the case difference. It has a set of other attributes such as "Cache-Control" as well in the $header.  If it manages to "get" the "content-type" attribute, then header correctly has a [0] offset property attainable.

I'm just trying a clean 5.8 install without my saml auth libraries to see if its doing the same thing. But I think you're right that its something to do with the authentication/redirect back from SAML which is causing the issue.

Will report back if I find anything useful.

Body:
I'm attempting to upgrade dependancies on a simple Laravel 5.7 application that authenticates the user via SimpleSAMLphp, then displays some information it gets from an external API.

It looks like something changed between version 4.3.8 and version 4.4.0 of the symfony/http-foundation library included with Laravel, because when I upgrade this dependency I get the following error:

ErrorException (E_NOTICE): Undefined offset: 0 …/vendor/symfony/http-foundation/HeaderBag.php 126

It looks like this is being triggered by requiring the SimpleSAMLphp service provider autoload file, even if I don't call any methods.

Since this is an extremely simple single page application, I'm just using middleware to handle the SimpleSAMLphp integration:

namespace App\Http\Middleware;

use Closure;

class SimpleSAMLphp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        /**
         * Load SimpleSAMLphp library
         */
        require_once('redacted/path/simplesaml/lib/_autoload.php');
        $ssphp = new \SimpleSAML\Auth\Simple('service-provider-name');
        $ssphp->requireAuth();

        return $next($request);
    }
}

It looks like Symfony HTTP Foundation changed how they are checking for header information in this version (I see extensive changes here: https://github.com/symfony/http-foundation/compare/v4.3.8...v4.4.0), but I don't understand why it is blowing up when SimpleSAMLphp is in the mix.

I'm deep down the rabbit hole on this one - any guidance would be much appreciated!


问:
windows 10 determine if "maintain aspect ratio" is set on a PCs GPU
I am trying to programically determine if a video card is set to "maintain aspect ratio". I've tracked down this registry key in windows.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration\\00\00
scaling =

4 = maintain aspect ratio 3 = scale full screen 2 = center image

This would be great, but it appears that "maintain display scaling" will retain whatever that key was set to before.

Does anyone have another location or another method to confirm, that a video card is set to maintain aspect ratio? (not using a cards GUI)

I should clarify this isn't about DPI settings, this is about aspect ratio of the video being displayed.

答:
Posting this as an answer (even though it's not) since I need to space to show what I've done so far--in case it helps anyone towards the answer.  I'm currently looking through other Windows API libs to try and find the answer.

@MinerBob, I saw that guy's code yesterday too but couldn't get it to work so I changed a few things and am now reporting the data as correctly as I can but looking over the struct, it doesn't appear to contain the information you're after but here's how you can generate the output to review it yourself:

```<code>Add-Type "
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;

[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
    private const int CCHDEVICENAME = 0x20;
    private const int CCHFORMNAME = 0x20;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
    public string dmDeviceName;
    public short dmSpecVersion;
    public short dmDriverVersion;
    public short dmSize;
    public short dmDriverExtra;
    public int dmFields;
    public int dmPositionX;
    public int dmPositionY;
    public ScreenOrientation dmDisplayOrientation;
    public int dmDisplayFixedOutput;
    public short dmColor;
    public short dmDuplex;
    public short dmYResolution;
    public short dmTTOption;
    public short dmCollate;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
    public string dmFormName;
    public short dmLogPixels;
    public int dmBitsPerPel;
    public int dmPelsWidth;
    public int dmPelsHeight;
    public int dmDisplayFlags;
    public int dmDisplayFrequency;
    public int dmICMMethod;
    public int dmICMIntent;
    public int dmMediaType;
    public int dmDitherType;
    public int dmReserved1;
    public int dmReserved2;
    public int dmPanningWidth;
    public int dmPanningHeight;
}

public static class user32
{

    [DllImport(`"user32.dll`")]
    public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

    public const int ENUM_CURRENT_SETTINGS = -1;
    public const int ENUM_REGISTRY_SETTINGS = -2;

    public static void GetDisplaySettings()
    {
        DEVMODE vDevMode = new DEVMODE();

        if (EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref vDevMode))
        {
        Console.WriteLine(@`"
            dmDeviceName = {0}
            dmSpecVersion = {1}
            dmDriverVersion = {2}
            dmSize = {3}
            dmDriverExtra = {4}
            dmFields = {5}
            dmPositionX = {6}
            dmPositionY = {7}
            dmDisplayOrientation = {8}
            dmDisplayFixedOutput = {9}
            dmColor = {10}
            dmDuplex = {11}
            dmYResolution = {12}
            dmTTOption = {13}
            dmCollate = {14}
            dmFormName = {15}
            dmLogPixels = {16}
            dmBitsPerPel = {17}
            dmPelsWidth = {18}
            dmPelsHeight = {19}
            dmDisplayFlags = {20}
            dmDisplayFrequency = {21}
            dmICMMethod = {22}
            dmICMIntent = {23}
            dmMediaType = {24}
            dmDitherType = {25}
            dmReserved1 = {26}
            dmReserved2 = {27}
            dmPanningWidth = {28}
            dmPanningHeight = {29}
        `",
            vDevMode.dmDeviceName,
            vDevMode.dmSpecVersion,
            vDevMode.dmDriverVersion,
            vDevMode.dmSize,
            vDevMode.dmDriverExtra,
            vDevMode.dmFields,
            vDevMode.dmPositionX,
            vDevMode.dmPositionY,
            vDevMode.dmDisplayOrientation,
            vDevMode.dmDisplayFixedOutput,
            vDevMode.dmColor,
            vDevMode.dmDuplex,
            vDevMode.dmYResolution,
            vDevMode.dmTTOption,
            vDevMode.dmCollate,
            vDevMode.dmFormName,
            vDevMode.dmLogPixels,
            vDevMode.dmBitsPerPel,
            vDevMode.dmPelsWidth,
            vDevMode.dmPelsHeight,
            vDevMode.dmDisplayFlags,
            vDevMode.dmDisplayFrequency,
            vDevMode.dmICMMethod,
            vDevMode.dmICMIntent,
            vDevMode.dmMediaType,
            vDevMode.dmDitherType,
            vDevMode.dmReserved1,
            vDevMode.dmReserved2,
            vDevMode.dmPanningWidth,
            vDevMode.dmPanningHeight
        );
        }
    }
}
" -ReferencedAssemblies System.Windows.Forms

[user32]::GetDisplaySettings()
</code>```

UPDATE 1:

According to the MSDN documentation for EnumDisplaySettings:

The EnumDisplaySettings function sets values for the following five
  DEVMODE members:

```<code>dmBitsPerPel
dmPelsWidth
dmPelsHeight
dmDisplayFlags
dmDisplayFrequency
</code>```

what I was originally focusing on 'dmScale' appears to be specific to Printers--as in, only Printer functions that populate the DEVMODE struct will fill that field.

Update 2:

It appears everything under GraphicsDrivers key, well, is updated by the graphics driver that's loaded for that monitor.  Very Intuitive.  Every article I could find talks about either changing the value in the vendor-specific UI that interacts with its driver OR using the appropriate monitor key under Graphics Drivers to interact with this feature.

There must be some Windows Graphics Driver documentation that talks about each driver updating/honoring these values.  Looking for that now to confirm.

Update 3:

Updated source to include the DEVMODE structure signature from pinvoke.net.  Also, I believe I found the smoking gun in Windows driver documentation:

Scaling depends on the source and target modes that are used for a
  path. In addition, the caller can call SetDisplayConfig without
  specifying the target mode information (that is, setting the
  modeInfoArray parameter is optional and can be set to NULL).
  Therefore, the caller cannot typically predict if SetDisplayConfig
  must perform any scaling. Furthermore, no API exists to get the full
  list of scaling types that the graphics adapter supports. The
  EnumDisplaySettings Win32 function (described in the Windows SDK
  documentation) returns DMDFO_DEFAULT in the dmDisplayFixedOutput
  member of the DEVMODE structure that the lpDevMode parameter points to
  when the caller requests the new Windows 7 scaling types.

The scaling that a caller passes to SetDisplayConfig is a scaling
  intent rather than an explicit request to perform a scaling operation.
  If scaling is required (for example, source and target resolutions
  differ), SetDisplayConfig uses the scaling that the caller supplies.
  If the supplied scaling is not supported, SetDisplayConfig uses the
  graphics adapter's default scaling. When the source and target
  resolutions that the caller passes to SetDisplayConfig are the same,
  SetDisplayConfig always sets identify scaling.

...my bolded emphasis. DMDFO_DEFAULT, according to the header file, is 0.

Sources:

https://learn.microsoft.com/en-us/windows-hardware/drivers/display/scaling-the-desktop-image

https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodea

Body:
Posting this as an answer (even though it's not) since I need to space to show what I've done so far--in case it helps anyone towards the answer.  I'm currently looking through other Windows API libs to try and find the answer.

@MinerBob, I saw that guy's code yesterday too but couldn't get it to work so I changed a few things and am now reporting the data as correctly as I can but looking over the struct, it doesn't appear to contain the information you're after but here's how you can generate the output to review it yourself:

Add-Type "
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;

[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
    private const int CCHDEVICENAME = 0x20;
    private const int CCHFORMNAME = 0x20;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
    public string dmDeviceName;
    public short dmSpecVersion;
    public short dmDriverVersion;
    public short dmSize;
    public short dmDriverExtra;
    public int dmFields;
    public int dmPositionX;
    public int dmPositionY;
    public ScreenOrientation dmDisplayOrientation;
    public int dmDisplayFixedOutput;
    public short dmColor;
    public short dmDuplex;
    public short dmYResolution;
    public short dmTTOption;
    public short dmCollate;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
    public string dmFormName;
    public short dmLogPixels;
    public int dmBitsPerPel;
    public int dmPelsWidth;
    public int dmPelsHeight;
    public int dmDisplayFlags;
    public int dmDisplayFrequency;
    public int dmICMMethod;
    public int dmICMIntent;
    public int dmMediaType;
    public int dmDitherType;
    public int dmReserved1;
    public int dmReserved2;
    public int dmPanningWidth;
    public int dmPanningHeight;
}

public static class user32
{

    [DllImport(`"user32.dll`")]
    public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

    public const int ENUM_CURRENT_SETTINGS = -1;
    public const int ENUM_REGISTRY_SETTINGS = -2;

    public static void GetDisplaySettings()
    {
        DEVMODE vDevMode = new DEVMODE();

        if (EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref vDevMode))
        {
        Console.WriteLine(@`"
            dmDeviceName = {0}
            dmSpecVersion = {1}
            dmDriverVersion = {2}
            dmSize = {3}
            dmDriverExtra = {4}
            dmFields = {5}
            dmPositionX = {6}
            dmPositionY = {7}
            dmDisplayOrientation = {8}
            dmDisplayFixedOutput = {9}
            dmColor = {10}
            dmDuplex = {11}
            dmYResolution = {12}
            dmTTOption = {13}
            dmCollate = {14}
            dmFormName = {15}
            dmLogPixels = {16}
            dmBitsPerPel = {17}
            dmPelsWidth = {18}
            dmPelsHeight = {19}
            dmDisplayFlags = {20}
            dmDisplayFrequency = {21}
            dmICMMethod = {22}
            dmICMIntent = {23}
            dmMediaType = {24}
            dmDitherType = {25}
            dmReserved1 = {26}
            dmReserved2 = {27}
            dmPanningWidth = {28}
            dmPanningHeight = {29}
        `",
            vDevMode.dmDeviceName,
            vDevMode.dmSpecVersion,
            vDevMode.dmDriverVersion,
            vDevMode.dmSize,
            vDevMode.dmDriverExtra,
            vDevMode.dmFields,
            vDevMode.dmPositionX,
            vDevMode.dmPositionY,
            vDevMode.dmDisplayOrientation,
            vDevMode.dmDisplayFixedOutput,
            vDevMode.dmColor,
            vDevMode.dmDuplex,
            vDevMode.dmYResolution,
            vDevMode.dmTTOption,
            vDevMode.dmCollate,
            vDevMode.dmFormName,
            vDevMode.dmLogPixels,
            vDevMode.dmBitsPerPel,
            vDevMode.dmPelsWidth,
            vDevMode.dmPelsHeight,
            vDevMode.dmDisplayFlags,
            vDevMode.dmDisplayFrequency,
            vDevMode.dmICMMethod,
            vDevMode.dmICMIntent,
            vDevMode.dmMediaType,
            vDevMode.dmDitherType,
            vDevMode.dmReserved1,
            vDevMode.dmReserved2,
            vDevMode.dmPanningWidth,
            vDevMode.dmPanningHeight
        );
        }
    }
}
" -ReferencedAssemblies System.Windows.Forms

[user32]::GetDisplaySettings()

UPDATE 1:

According to the MSDN documentation for EnumDisplaySettings:

The EnumDisplaySettings function sets values for the following five
  DEVMODE members:

dmBitsPerPel
dmPelsWidth
dmPelsHeight
dmDisplayFlags
dmDisplayFrequency

what I was originally focusing on 'dmScale' appears to be specific to Printers--as in, only Printer functions that populate the DEVMODE struct will fill that field.

Update 2:

It appears everything under GraphicsDrivers key, well, is updated by the graphics driver that's loaded for that monitor.  Very Intuitive.  Every article I could find talks about either changing the value in the vendor-specific UI that interacts with its driver OR using the appropriate monitor key under Graphics Drivers to interact with this feature.

There must be some Windows Graphics Driver documentation that talks about each driver updating/honoring these values.  Looking for that now to confirm.

Update 3:

Updated source to include the DEVMODE structure signature from pinvoke.net.  Also, I believe I found the smoking gun in Windows driver documentation:

Scaling depends on the source and target modes that are used for a
  path. In addition, the caller can call SetDisplayConfig without
  specifying the target mode information (that is, setting the
  modeInfoArray parameter is optional and can be set to NULL).
  Therefore, the caller cannot typically predict if SetDisplayConfig
  must perform any scaling. Furthermore, no API exists to get the full
  list of scaling types that the graphics adapter supports. The
  EnumDisplaySettings Win32 function (described in the Windows SDK
  documentation) returns DMDFO_DEFAULT in the dmDisplayFixedOutput
  member of the DEVMODE structure that the lpDevMode parameter points to
  when the caller requests the new Windows 7 scaling types.

The scaling that a caller passes to SetDisplayConfig is a scaling
  intent rather than an explicit request to perform a scaling operation.
  If scaling is required (for example, source and target resolutions
  differ), SetDisplayConfig uses the scaling that the caller supplies.
  If the supplied scaling is not supported, SetDisplayConfig uses the
  graphics adapter's default scaling. When the source and target
  resolutions that the caller passes to SetDisplayConfig are the same,
  SetDisplayConfig always sets identify scaling.

...my bolded emphasis. DMDFO_DEFAULT, according to the header file, is 0.

Sources:

https://learn.microsoft.com/en-us/windows-hardware/drivers/display/scaling-the-desktop-image

https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodea


问:
write data in binary format in Files in Android
hi all:
making a sample application in which we can store data on File and then could Read it.,
m using the following code.:

Code to Write:

```<code>OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(openFileOutput("finear.fin", 0));
        out.write(data); //data is String variable
        out.close();
        Toast.makeText(getApplicationContext(), "Data has been Saved! ", Toast.LENGTH_LONG).show();
    }
</code>```

Code to Read:

```<code>instream = openFileInput("finear.fin");
if(instream!=null)
{
InputStreamReader inputReader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputReader);
String dataRead = buffreader.readLine();
}
</code>```

Now problem is: The Data is stored in simple Text Form but i want that no one could read my data from that file and it should store the data in some binary form or some symbols type format so that when one opens the file in windows it should not display my text stored in the file or should display some other data.. BUT also that data could be readable in String form when i read. PLease Help

答:
You can use Android's internal storage, which is private to your application:

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

Here you can find the docs: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

ContentLicense: CC BY-SA 3.0

Body:
hi all:
making a sample application in which we can store data on File and then could Read it.,
m using the following code.:

Code to Write:

OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(openFileOutput("finear.fin", 0));
        out.write(data); //data is String variable
        out.close();
        Toast.makeText(getApplicationContext(), "Data has been Saved! ", Toast.LENGTH_LONG).show();
    }

Code to Read:

instream = openFileInput("finear.fin");
if(instream!=null)
{
InputStreamReader inputReader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputReader);
String dataRead = buffreader.readLine();
}

Now problem is: The Data is stored in simple Text Form but i want that no one could read my data from that file and it should store the data in some binary form or some symbols type format so that when one opens the file in windows it should not display my text stored in the file or should display some other data.. BUT also that data could be readable in String form when i read. PLease Help


问:
Upsert a document with value from filter
I have a collection with following structure in MongoDB:

```<code>{
  "userId": String,
  "refs": Set<String>
}
</code>```

I need to update the collections with those documents. I want to add to refs a new string, for users that are in the filter $in.
But, if the user is not exists I need to "upsert" him.

In code (golang) it looks like this:

filter := bson.M{
    "userId": bson.M{
        "$in:": tokens // tokens is []string
    }
}

update := bson.M{
    "$addToSet": bson.M{
        "refs": newReference
    }
}

ctx, _ := newDbOperationContext()
_, err := driver.UpdateMany(ctx, filter, update)
```

<p>So, for existing users it works ok, the reference is added. But, for users that not exists nothing happen.</p>

<p>I set in <code>driver.UpdateMany(bson, bson, opts...)</code> opts to <code>options.UpdateOptions.SetUpsert(true)"</code>, but as a result I got a document without userId:</p>

```{
  "_id": ObjectId("..."),
  "refs": ["new_reference"]
}
```

So, my question is, how to upsert the new values with userId field.

The scale is like 2*10^6 users to update, so I would like to do that using batch request. Creating using "one by one" and updating him is not an option here, I think.

Thanks for your support!

答:
Looking at your use case, I think the best solution will be the following :

Since you have a high scale and wish to make batch requests, it is best to use BulkWrite : The db.collection.bulkWrite() method provides the ability to perform bulk insert, update, and remove operations.
 Example : https://godoc.org/go.mongodb.org/mongo-driver/mongo#example-Collection-BulkWrite

This uses UpdateOne Model but it supports UpdateMany Model as well. It also a function of SetUpsert(true)
Now for the _id field : Your updated/upserted document should have _id field for the new document to have that _id field else mongoDb auto-generates an _id field while inserting the document if your upsert document does not have _id field

I think, it will not be much of a pain to have _id field in your documents, so that way your problem is solved.

Regarding the scale, I suggest using BulkWrite with UpdateOne or UpdateMany models.

Hope this helps.

Body:
I have a collection with following structure in MongoDB:

{
  "userId": String,
  "refs": Set<String>
}

I need to update the collections with those documents. I want to add to refs a new string, for users that are in the filter $in.
But, if the user is not exists I need to "upsert" him.

In code (golang) it looks like this:

filter := bson.M{
    "userId": bson.M{
        "$in:": tokens // tokens is []string
    }
}

update := bson.M{
    "$addToSet": bson.M{
        "refs": newReference
    }
}

ctx, _ := newDbOperationContext()
_, err := driver.UpdateMany(ctx, filter, update)

So, for existing users it works ok, the reference is added. But, for users that not exists nothing happen.

I set in driver.UpdateMany(bson, bson, opts...) opts to options.UpdateOptions.SetUpsert(true)", but as a result I got a document without userId:

{
  "_id": ObjectId("..."),
  "refs": ["new_reference"]
}

So, my question is, how to upsert the new values with userId field.

The scale is like 2*10^6 users to update, so I would like to do that using batch request. Creating using "one by one" and updating him is not an option here, I think.

Thanks for your support!


问:
Android SoundPool plays no sound
I want to play a short sound when a button is clicked using SoundPool. But when the button is clicked no sound appears despite the Log telling me it's loaded and "playing". The soundfile is an .ogg in case that's relevant. Here's my code, buttonSound() is called in onCreate().

```<code>void buttonSound(){
    AudioAttributes attributes = new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .build();

    soundPool = new SoundPool.Builder().setAudioAttributes(attributes).build();

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
            int status) {
            Log.d("SOUNDPOOL", "COMPLETE "+button);
        }
    });
    button = soundPool.load(this, R.raw.button, 1);

}

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_back:
            // Sound loaded
            if(button != 0) {
                soundPool.play(button, 1f, 1f, 1, 0, 1f);
                Log.d("PLAYING", "PLAYING");
            }
            break;
</code>```

答: So apparently AudioAttributes.USAGE_ASSISTANCE_SONIFICATION was the issue, it works fine with AudioAttributes.USAGE_GAME and AudioAttributes.USAGE_MEDIA. I have no idea why, though.

Title: Android SoundPool plays no sound

Body:
I want to play a short sound when a button is clicked using SoundPool. But when the button is clicked no sound appears despite the Log telling me it's loaded and "playing". The soundfile is an .ogg in case that's relevant. Here's my code, buttonSound() is called in onCreate().

void buttonSound(){
    AudioAttributes attributes = new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .build();

    soundPool = new SoundPool.Builder().setAudioAttributes(attributes).build();

    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
            int status) {
            Log.d("SOUNDPOOL", "COMPLETE "+button);
        }
    });
    button = soundPool.load(this, R.raw.button, 1);

}

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_back:
            // Sound loaded
            if(button != 0) {
                soundPool.play(button, 1f, 1f, 1, 0, 1f);
                Log.d("PLAYING", "PLAYING");
            }
            break;


问:
Given the quarter number and year, how to find the date ranges?
I am trying create a function that will return date ranges if I pass in the quarter number (1,2,3, or 4) and the year for that quarter.

Here is what I have so far:

```<code>export const getCurrentQuarterRangeString = (quarter, year) => {
  // let year = moment().year(year);
  let start = moment().quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment().quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}
</code>```

I get tripped up on trying to figure out how to key off that year parameter for MomentJS.

答:
You can create a moment when you pass a year into your function. Use that to manipulate and get you required dates.</p>

```<code>const moment = require("moment");

export const getCurrentQuarterRangeString = (quarter, year) => {
  const yearObject = moment(parseInt(year), "YYYY");

  const startOfQuater = yearObject.quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  const endOfQuarter = yearObject.quarter(quarter).endOf('quarter').format('YYYY-MM-DD');

  return `${start};#${end}`;
}
</code>```

Body:
I am trying create a function that will return date ranges if I pass in the quarter number (1,2,3, or 4) and the year for that quarter.

Here is what I have so far:

export const getCurrentQuarterRangeString = (quarter, year) => {
  // let year = moment().year(year);
  let start = moment().quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  let end = moment().quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
  let dateRangeString = `${start};#${end}`;
  return dateRangeString;
}

I get tripped up on trying to figure out how to key off that year parameter for MomentJS.

Body:
You can create a moment when you pass a year into your function. Use that to manipulate and get you required dates.

const moment = require("moment");

export const getCurrentQuarterRangeString = (quarter, year) => {
  const yearObject = moment(parseInt(year), "YYYY");

  const startOfQuater = yearObject.quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
  const endOfQuarter = yearObject.quarter(quarter).endOf('quarter').format('YYYY-MM-DD');

  return `${start};#${end}`;
}


问:
Get current working directory in terraform
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.

So I am trying to get the current working directory as follows:

```<code>resource null_resource "pwd" {
  triggers {
    always_run = "${uuid()}"
  }
  provisioner "local-exec" {
    command = "echo $pwd >> somefile.txt"
  }
}
</code>```

However the resulting file is empty.

Any suggestions?

答:
Terraform has a built-in object path that contains attributes for various paths Terraform knows about:

path.module is the directory containing the module where the path.module expression is placed.

path.root is the directory containing the root module.

path.cwd is the current working directory.

When writing Terraform modules, we most commonly want to resolve paths relative to the module itself, so that it is self-contained and doesn't make any assumptions about or cause impacts to any other modules in the configuration. Therefore path.module is most often the right choice, making a module agnostic to where it's being instantiated from.

It's very uncommon to use the current working directory because that would make a Terraform configuration sensitive to where it is applied, and likely cause unnecessary resource changes if you later apply the same configuration from a different directory or on a different machine altogether. However, in the rare situations where such a thing is needed, path.cwd will do it.

path.module and path.root are both relative paths from path.cwd, because that minimizes the risk of inadvertently introducing details about the system where Terraform is being run into the configuration. However, if you do need an absolute module path for some reason, you can use abspath, like abspath(path.module).

Body:
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.

So I am trying to get the current working directory as follows:

resource null_resource "pwd" {
  triggers {
    always_run = "${uuid()}"
  }
  provisioner "local-exec" {
    command = "echo $pwd >> somefile.txt"
  }
}

However the resulting file is empty.

Any suggestions?


问:
run button in xcode 4
Whenever I re-run my application by selecting the run button in xcode for, it says simulator already in use. So I have to stop it every time before re-running.
So my question is, is there any option or setting to avoid this. I want to run the application without stopping it like we used to do in xcode 3.</p>

答:
In Application PLIST file, we have a flag of “Application does not run in background”. </p>

<p>If you set this flag to “YES” and press home button, application will not maintain its status or perform any background tasks. </p>

Title: run button in xcode 4

Body:
In Application PLIST file, we have a flag of “Application does not run in background”.

If you set this flag to “YES” and press home button, application will not maintain its status or perform any background tasks.


问:
Linq replace values until first X value
I have a list:

```<code>var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
</code>```

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

```<code>var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)
</code>```

Actual Result:

```<code>{null,null,null,null,null,null,null,5,6,3,0,null,null,3}
</code>```

Expected Result:

```<code>{null,null,null,null,null,null,4,5,6,3,0,0,2,3}
</code>```

MRE:

```<code>public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}
</code>```

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

答:
If we're creating an extension method I think I would prefer it this way:

```<code>public static IEnumerable<T> ReplaceWhile<T>(IEnumerable<T> source, Func<T, bool> predicate, T subsitute)
{
    var matching = true;
    foreach(var item in source)
        yield return !matching ? item : (matching = predicate(item)) ? subsitute : item;
}
</code>```

Iterates every item exactly once, no need to first iterate to find an index or do a count etc.

Edit: Try it online

Title: Linq replace values until first X value

Body:
I have a list:

var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};

I want to replace all starting "n" zeros values with null until find first value != 0 and break.

I tried to use Select:

var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x)

Actual Result:

{null,null,null,null,null,null,null,5,6,3,0,null,null,3}

Expected Result:

{null,null,null,null,null,null,4,5,6,3,0,0,2,3}

MRE:

public static void Main()
{
    var l = new List<int?>{0,0,0,0,0,0,4,5,6,3,0,0,2,3};
    var l2 = l.Select((x, i) => i == 0 || l[i - 1] == 0 ? (int?)null : x);
    Console.WriteLine(string.Join(",", l2));
}

Note that this question is a rework of https://stackoverflow.com/q/60304342/1248177. I think that the question had some legs so here we go.

Body:
If we're creating an extension method I think I would prefer it this way:

public static IEnumerable<T> ReplaceWhile<T>(IEnumerable<T> source, Func<T, bool> predicate, T subsitute)
{
    var matching = true;
    foreach(var item in source)
        yield return !matching ? item : (matching = predicate(item)) ? subsitute : item;
}

Iterates every item exactly once, no need to first iterate to find an index or do a count etc.

Edit: Try it online


问:
Android Room giving error "Pre-packaged database has an invalid schema" but exported schema is correct
I am migrating from SQlite to room in my existing application. Therefore I created migration strategy to create new temporary tables, copy existing data into temporary tables and delete old tables and rename new tables.

After migrating, I checked my exported schema and it is exactly the same as expected schema but  I still get the error of my old schema is found and receiving error below. Main differences on the schema errors are "type" and #notNull" but I already corrected them during the migration

Pre-packaged database has an invalid schema:
User(com.afl.waterReminderDrinkAlarmMonitor.model.User)

My User Entity

```<code>@Entity(tableName = "User" )
data class User(
    @PrimaryKey
    var id: Int = 0,
    var age: Int = 0,
    var weight: Int = 0,
    var gender: String = "",
    var metric: String = "",
    var water: Int = 0
)
</code>```

AppDatabase

```<code>abstract class AppDatabase : RoomDatabase() {

    abstract fun dao(): Dao

    companion object {

        @Volatile
        private var INSTANCE: AppDatabase? = null

    val migration_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {

            //COPY USER TABLE
            // Create new  table
            database.execSQL("CREATE TABLE IF NOT EXISTS UserTmp ($COL_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_WEIGHT INTEGER NOT NULL, $COL_GENDER  TEXT NOT NULL,$COL_METRIC TEXT NOT NULL, $COL_AGE INTEGER NOT NULL, $COL_WATER INTEGER NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO UserTmp ($COL_ID, $COL_WEIGHT, $COL_GENDER, $COL_METRIC,$COL_AGE, $COL_WATER) SELECT $COL_ID, $COL_WEIGHT, $COL_GENDER, $COL_METRIC,$COL_AGE, $COL_WATER FROM $TABLE_NAME ")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE UserTmp RENAME TO $TABLE_NAME")

            //COPY DRUNK TABLE
            // Create new table
            database.execSQL("CREATE TABLE IF NOT EXISTS DrunkTmp ($COL_ID_DRUNK INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_DATE_DRUNK TEXT NOT NULL, $COL_TIME_DRUNK TEXT NOT NULL,$COL_DRINK_DRUNK TEXT NOT NULL, $COL_AMOUNT_DRUNK INTEGER NOT NULL ,$COL_METRIC_DRUNK TEXT NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO DrunkTmp ($COL_ID_DRUNK, $COL_DATE_DRUNK, $COL_TIME_DRUNK, $COL_DRINK_DRUNK, $COL_AMOUNT_DRUNK, $COL_METRIC_DRUNK) SELECT $COL_ID_DRUNK, $COL_DATE_DRUNK, $COL_TIME_DRUNK, $COL_DRINK_DRUNK, $COL_AMOUNT_DRUNK, $COL_METRIC_DRUNK FROM $TABLE_NAME_DRUNK")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME_DRUNK")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE DrunkTmp RENAME TO $TABLE_NAME_DRUNK")

            //COPY NOT TABLE
            // Create new table
            database.execSQL("CREATE TABLE IF NOT EXISTS NotificationTmp ($COL_ID_NOT INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_PREF_NOT INTEGER NOT NULL, $COL_START_NOT INTEGER NOT NULL, $COL_FINISH_NOT INTEGER NOT NULL,$COL_INTERVAL_NOT INTEGER NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO NotificationTmp ($COL_ID_NOT, $COL_PREF_NOT, $COL_START_NOT, $COL_FINISH_NOT, $COL_INTERVAL_NOT) SELECT $COL_ID_NOT, $COL_PREF_NOT, $COL_START_NOT, $COL_FINISH_NOT, $COL_INTERVAL_NOT FROM $TABLE_NAME_NOT ")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME_NOT")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE NotificationTmp RENAME TO $TABLE_NAME_NOT")
        }

    }

        fun getDatabase(context: Context?): AppDatabase {

            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }

            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context?.applicationContext!!,
                    AppDatabase::class.java, DATABASE_NAME
                )
                    .addMigrations(migration_1_2)
                    .build()
                INSTANCE = instance
                return instance
            }
        }

    }

}
</code>```

Exported Schema for User

```<code>  {
    "tableName": "User",
    "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `age` INTEGER NOT NULL, `weight` INTEGER NOT NULL, `gender` TEXT NOT NULL, `metric` TEXT NOT NULL, `water` INTEGER NOT NULL, PRIMARY KEY(`id`))",
    "fields": [
      {
        "fieldPath": "id",
        "columnName": "id",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "age",
        "columnName": "age",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "weight",
        "columnName": "weight",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "gender",
        "columnName": "gender",
        "affinity": "TEXT",
        "notNull": true
      },
      {
        "fieldPath": "metric",
        "columnName": "metric",
        "affinity": "TEXT",
        "notNull": true
      },
      {
        "fieldPath": "water",
        "columnName": "water",
        "affinity": "INTEGER",
        "notNull": true
      }
    ],
    "primaryKey": {
      "columnNames": [
        "id"
      ],
      "autoGenerate": false
    },
    "indices": [],
    "foreignKeys": []
  }
</code>```

and finally the error I receive it

```<code>java.lang.IllegalStateException: Pre-packaged database has an invalid schema: User(com.afl.waterReminderDrinkAlarmMonitor.model.User).

Expected: TableInfo{name='User', columns={weight=Column{name='weight', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, gender=Column{name='gender', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, metric=Column{name='metric', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, water=Column{name='water', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, age=Column{name='age', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

Found: TableInfo{name='User', columns={gender=Column{name='gender', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, metric=Column{name='metric', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, weight=Column{name='weight', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, water=Column{name='water', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, age=Column{name='age', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}
</code>```

答:
The question misses the pre-populated database, which either resides in assets or elsewhere; as the mismatch is actually in that file and a migration would need to load it and then change the column. As one can see, table User has the wrong data-type for columns gender and metric:

```<code>Expected: TableInfo{name='User', columns={
       id=Column{name='id',         type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'},
       age=Column{name='age',       type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null',
       weight=Column{name='weight', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       gender=Column{name='gender',    type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       metric=Column{name='metric',    type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       water=Column{name='water',   type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}
}}, foreignKeys=[], indices=[]}

Found:   TableInfo{name='User', columns={
       id=Column{name='id',              type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'},
       age=Column{name='age',            type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue ='null',
       weight=Column{name='weight',      type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       gender=Column{name='gender', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       metric=Column{name='metric', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       water=Column{name='water',        type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}
}}, foreignKeys=[], indices=[]}
</code>```

Editing the packaged database on a computer might be the least effort.

Body:
I am migrating from SQlite to room in my existing application. Therefore I created migration strategy to create new temporary tables, copy existing data into temporary tables and delete old tables and rename new tables.

After migrating, I checked my exported schema and it is exactly the same as expected schema but  I still get the error of my old schema is found and receiving error below. Main differences on the schema errors are "type" and #notNull" but I already corrected them during the migration

Pre-packaged database has an invalid schema:
User(com.afl.waterReminderDrinkAlarmMonitor.model.User)

My User Entity

@Entity(tableName = "User" )
data class User(
    @PrimaryKey
    var id: Int = 0,
    var age: Int = 0,
    var weight: Int = 0,
    var gender: String = "",
    var metric: String = "",
    var water: Int = 0
)

AppDatabase

abstract class AppDatabase : RoomDatabase() {

    abstract fun dao(): Dao

    companion object {

        @Volatile
        private var INSTANCE: AppDatabase? = null

    val migration_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {

            //COPY USER TABLE
            // Create new  table
            database.execSQL("CREATE TABLE IF NOT EXISTS UserTmp ($COL_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_WEIGHT INTEGER NOT NULL, $COL_GENDER  TEXT NOT NULL,$COL_METRIC TEXT NOT NULL, $COL_AGE INTEGER NOT NULL, $COL_WATER INTEGER NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO UserTmp ($COL_ID, $COL_WEIGHT, $COL_GENDER, $COL_METRIC,$COL_AGE, $COL_WATER) SELECT $COL_ID, $COL_WEIGHT, $COL_GENDER, $COL_METRIC,$COL_AGE, $COL_WATER FROM $TABLE_NAME ")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE UserTmp RENAME TO $TABLE_NAME")

            //COPY DRUNK TABLE
            // Create new table
            database.execSQL("CREATE TABLE IF NOT EXISTS DrunkTmp ($COL_ID_DRUNK INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_DATE_DRUNK TEXT NOT NULL, $COL_TIME_DRUNK TEXT NOT NULL,$COL_DRINK_DRUNK TEXT NOT NULL, $COL_AMOUNT_DRUNK INTEGER NOT NULL ,$COL_METRIC_DRUNK TEXT NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO DrunkTmp ($COL_ID_DRUNK, $COL_DATE_DRUNK, $COL_TIME_DRUNK, $COL_DRINK_DRUNK, $COL_AMOUNT_DRUNK, $COL_METRIC_DRUNK) SELECT $COL_ID_DRUNK, $COL_DATE_DRUNK, $COL_TIME_DRUNK, $COL_DRINK_DRUNK, $COL_AMOUNT_DRUNK, $COL_METRIC_DRUNK FROM $TABLE_NAME_DRUNK")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME_DRUNK")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE DrunkTmp RENAME TO $TABLE_NAME_DRUNK")

            //COPY NOT TABLE
            // Create new table
            database.execSQL("CREATE TABLE IF NOT EXISTS NotificationTmp ($COL_ID_NOT INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $COL_PREF_NOT INTEGER NOT NULL, $COL_START_NOT INTEGER NOT NULL, $COL_FINISH_NOT INTEGER NOT NULL,$COL_INTERVAL_NOT INTEGER NOT NULL)")
            // Copy the data
            database.execSQL("INSERT INTO NotificationTmp ($COL_ID_NOT, $COL_PREF_NOT, $COL_START_NOT, $COL_FINISH_NOT, $COL_INTERVAL_NOT) SELECT $COL_ID_NOT, $COL_PREF_NOT, $COL_START_NOT, $COL_FINISH_NOT, $COL_INTERVAL_NOT FROM $TABLE_NAME_NOT ")
            // Remove the old table
            database.execSQL("DROP TABLE $TABLE_NAME_NOT")
            // Change the table name to the correct one
            database.execSQL("ALTER TABLE NotificationTmp RENAME TO $TABLE_NAME_NOT")
        }

    }

        fun getDatabase(context: Context?): AppDatabase {

            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }

            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context?.applicationContext!!,
                    AppDatabase::class.java, DATABASE_NAME
                )
                    .addMigrations(migration_1_2)
                    .build()
                INSTANCE = instance
                return instance
            }
        }

    }

}

Exported Schema for User

  {
    "tableName": "User",
    "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `age` INTEGER NOT NULL, `weight` INTEGER NOT NULL, `gender` TEXT NOT NULL, `metric` TEXT NOT NULL, `water` INTEGER NOT NULL, PRIMARY KEY(`id`))",
    "fields": [
      {
        "fieldPath": "id",
        "columnName": "id",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "age",
        "columnName": "age",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "weight",
        "columnName": "weight",
        "affinity": "INTEGER",
        "notNull": true
      },
      {
        "fieldPath": "gender",
        "columnName": "gender",
        "affinity": "TEXT",
        "notNull": true
      },
      {
        "fieldPath": "metric",
        "columnName": "metric",
        "affinity": "TEXT",
        "notNull": true
      },
      {
        "fieldPath": "water",
        "columnName": "water",
        "affinity": "INTEGER",
        "notNull": true
      }
    ],
    "primaryKey": {
      "columnNames": [
        "id"
      ],
      "autoGenerate": false
    },
    "indices": [],
    "foreignKeys": []
  }

and finally the error I receive it

java.lang.IllegalStateException: Pre-packaged database has an invalid schema: User(com.afl.waterReminderDrinkAlarmMonitor.model.User).

Expected: TableInfo{name='User', columns={weight=Column{name='weight', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, gender=Column{name='gender', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, metric=Column{name='metric', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'}, water=Column{name='water', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, age=Column{name='age', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

Found: TableInfo{name='User', columns={gender=Column{name='gender', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, metric=Column{name='metric', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'}, weight=Column{name='weight', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'}, water=Column{name='water', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}, age=Column{name='age', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, foreignKeys=[], indices=[]}

Body:
The question misses the pre-populated database, which either resides in assets or elsewhere; as the mismatch is actually in that file and a migration would need to load it and then change the column. As one can see, table User has the wrong data-type for columns gender and metric:

Expected: TableInfo{name='User', columns={
       id=Column{name='id',         type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'},
       age=Column{name='age',       type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null',
       weight=Column{name='weight', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       gender=Column{name='gender',    type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       metric=Column{name='metric',    type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='null'},
       water=Column{name='water',   type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}
}}, foreignKeys=[], indices=[]}

Found:   TableInfo{name='User', columns={
       id=Column{name='id',              type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='null'},
       age=Column{name='age',            type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue ='null',
       weight=Column{name='weight',      type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       gender=Column{name='gender', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       metric=Column{name='metric', type='VARCHAR(256)', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='null'},
       water=Column{name='water',        type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}
}}, foreignKeys=[], indices=[]}

Editing the packaged database on a computer might be the least effort.


问:
Illegal mix of collations MySQL Error
I'm getting this strange error while processing a large number of data...

```<code>Error Number: 1267

Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

SELECT COUNT(*) as num from keywords WHERE campaignId='12' AND LCASE(keyword)='hello again æ˜” ã‹ã‚‰ ã‚ã‚‹ å ´æ‰€'
</code>```

What can I do to resolve this? Can I escape the string somehow so this error wouldn't occur, or do I need to change my table encoding somehow, and if so, what should I change it to?

答:
I found that using cast() was the best solution for me:

```<code>cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount
</code>```

There is also a convert() function. More details on it here

Another resource here

ContentLicense: CC BY-SA 2.5

Title: Illegal mix of collations MySQL Error

Body:
I'm getting this strange error while processing a large number of data...

Error Number: 1267

Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

SELECT COUNT(*) as num from keywords WHERE campaignId='12' AND LCASE(keyword)='hello again æ˜” ã‹ã‚‰ ã‚ã‚‹ å ´æ‰€'

What can I do to resolve this? Can I escape the string somehow so this error wouldn't occur, or do I need to change my table encoding somehow, and if so, what should I change it to?

Body:
I found that using cast() was the best solution for me:

cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount

There is also a convert() function. More details on it here

Another resource here