问:
Flutter multiple if-statement
I have the following multiple if-statement in my flutter app:

```<code>        Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
        Text('Data not found').toString(),
</code>```

When deploying on my mobile device, it works perfect but after launching on Play Store, it returns the first statement regardless.

Any idea why this is now broken and where to start fixing?

*****EDIT*****

Added Category Page content where if-statement is located.
Original CategoryPage Code:

```<code> class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(
                //snapshot.data.documents[0]['desc'].toString(),
                Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
                Text('Data not found').toString(),
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.normal),
                textAlign: TextAlign.left,
              );
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}
</code>```

*****UPDATE*****
After simplifying if-statement following Yann39 advice - code works perfectly fine on my side when deploying from Visual Code onto my phone but still does not work when downloading the app from Google Play Store.

Updated CategoryPage:

```<code>class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1.toString()),style: TextStyle(
                     color: Colors.white,
                     fontSize: 15,
                     fontWeight: FontWeight.normal),
                 textAlign: TextAlign.left,);
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}
</code>```

*****UPDATE******

After the above if-statement simplify, the correct category discriptions are displayed, but now it only returns Collection 'Level1' from Firestore :

```<code>stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
</code>```

The above multiple if-statement works fine when deploying the app on my device, it is only when installing the app from Play Store which gives me these issues with the multiple if-statements.

答:
Maybe it does not answer directly your question (it is too long for a comment) but I'm not sure to understand why you are using Text(text1).toString() == Text('text').toString() instead of text1 == 'text' directly ?

Also note that Text(text3).toString() will return the string "Text(text3)", not the contained text. If you want to get the contained text use Text(text3).data. But once again you shouldn't have to create Text widgets here, text1 == 'text' should do the job, it is much more simple and performant.

I would have also simplified thoses if repetitions into a function, for example (assuming that you don't have the documents titles in snapshot.data.documents then you would not need the map to do the mapping) :

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}
```

<p>So that in your widget you just have to call <code>DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1)</code>.</p>

<p>If you have the documents titles in your <code>snapshot.data.documents</code> then it would be something like :</p>

<pre class="lang-dart prettyprint-override"><code>class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    return snapshot.data.documents.firstWhere((Document d) => d.title == title)['desc'].replaceAll("/n", "\n");
  }

}
</code>```

Title: Flutter multiple if-statement

Body:
I have the following multiple if-statement in my flutter app:

        Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
        Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
        Text('Data not found').toString(),

When deploying on my mobile device, it works perfect but after launching on Play Store, it returns the first statement regardless.

Any idea why this is now broken and where to start fixing?

*****EDIT*****

Added Category Page content where if-statement is located.
Original CategoryPage Code:

 class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(
                //snapshot.data.documents[0]['desc'].toString(),
                Text(text1).toString()==Text('Info and Comms').toString()?(snapshot.data.documents[8]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Media').toString()?(snapshot.data.documents[10]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Utilities').toString()?(snapshot.data.documents[16]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Education').toString()?(snapshot.data.documents[4]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Repairs').toString()?(snapshot.data.documents[13]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Domestic Help').toString()?(snapshot.data.documents[3]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Transport').toString()?(snapshot.data.documents[15]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Manufacturing').toString()?(snapshot.data.documents[9]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Mining').toString()?(snapshot.data.documents[11]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Supply Chain').toString()?(snapshot.data.documents[14]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Government').toString()?(snapshot.data.documents[6]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Financial and Business Services').toString()?(snapshot.data.documents[5]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Construction').toString()?(snapshot.data.documents[2]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Agriculture').toString()?(snapshot.data.documents[1]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Wholesale and Retail Trade').toString()?(snapshot.data.documents[17]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Accomodation').toString()?(snapshot.data.documents[0]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Health Social and Personal').toString()?(snapshot.data.documents[7]['desc'].toString()).replaceAll("/n", "\n"):
                Text(text1).toString()==Text('Movement').toString()?(snapshot.data.documents[12]['desc'].toString()).replaceAll("/n", "\n"):
                Text('Data not found').toString(),
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.normal),
                textAlign: TextAlign.left,
              );
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}

*****UPDATE*****
After simplifying if-statement following Yann39 advice - code works perfectly fine on my side when deploying from Visual Code onto my phone but still does not work when downloading the app from Google Play Store.

Updated CategoryPage:

class CategoryPage extends StatelessWidget {

  final String text1;
  final String text2;
  final String text3;
  CategoryPage(
      {Key key,
      @required this.text1,
      @required this.text2,
      @required this.text3})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(text2),
        centerTitle: true,
        backgroundColor: Colors.grey,
      ),
      body: ListView(shrinkWrap: true, children: <Widget>[
        Container(
            child: ListTile(
              title: Text(
                'Current Level ' + text3.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Text(text3).toString() == Text("5").toString()
                        ? Colors.red[900]
                        : Text(text3).toString() == Text("4").toString()
                            ? Colors.orange[900]
                            : Text(text3).toString() == Text("3").toString()
                                ? Colors.brown[300]
                                : Text(text3).toString() == Text("2").toString()
                                    ? Colors.blue[300]
                                    : Text(text3).toString() == Text("1").toString()
                                        ? Colors.green[300]
                                        : Colors.black,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
           Container(
            child: ListTile(
              title: Text(
                text1.toString(),
                style: TextStyle(
                    //color: Colors.red[900],
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        Container(
        alignment: Alignment.topLeft,
        padding: const EdgeInsets.all(8.0),
        child: StreamBuilder(
          stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text('Loading data ...');
            } else {
              return Text(DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1.toString()),style: TextStyle(
                     color: Colors.white,
                     fontSize: 15,
                     fontWeight: FontWeight.normal),
                 textAlign: TextAlign.left,);
            }
          },
        ),
        decoration: BoxDecoration(border: Border.all(color: Colors.grey[300])),
      ),]
      ));
  }

}

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}

*****UPDATE******

After the above if-statement simplify, the correct category discriptions are displayed, but now it only returns Collection 'Level1' from Firestore :

stream: Text(text3).toString() == Text('1').toString()
              ? Firestore.instance.collection('Level1').snapshots()
              : Text(text3).toString() == Text('2').toString()
                  ? Firestore.instance.collection('Level2').snapshots()
                  : Text(text3).toString() == Text('3').toString()
                      ? Firestore.instance.collection('Level3').snapshots()
                      : Text(text3).toString() == Text('4').toString()
                          ? Firestore.instance.collection('Level4').snapshots()
                          : Text(text3).toString() == Text('5').toString()
                              ? Firestore.instance
                                  .collection('Level5')
                                  .snapshots()
                              : Firestore.instance
                                  .collection('Level1')
                                  .snapshots(),

The above multiple if-statement works fine when deploying the app on my device, it is only when installing the app from Play Store which gives me these issues with the multiple if-statements.

Body:
Maybe it does not answer directly your question (it is too long for a comment) but I'm not sure to understand why you are using Text(text1).toString() == Text('text').toString() instead of text1 == 'text' directly ?

Also note that Text(text3).toString() will return the string "Text(text3)", not the contained text. If you want to get the contained text use Text(text3).data. But once again you shouldn't have to create Text widgets here, text1 == 'text' should do the job, it is much more simple and performant.

I would have also simplified thoses if repetitions into a function, for example (assuming that you don't have the documents titles in snapshot.data.documents then you would not need the map to do the mapping) :

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    var map = {
      'Info and Comms':8,
      'Media':10,
      'Utilities':16,
      'Education':4,
      'Repairs':13,
      'Domestic Help':3,
      'Transport':15,
      'Manufacturing':9,
      'Mining':11,
      'Supply Chain':14,
      'Government':6,
      'Financial and Business Services':5,
      'Construction':2,
      'Agriculture':1,
      'Wholesale and Retail Trade':17,
      'Accomodation':0,
      'Health Social and Personal':7,
      'Movement':12,
    };
    return map[title] != null ? snapshot.data.documents[map[title]]['desc'].toString().replaceAll("/n", "\n") : 'Data not found';
  }

}

So that in your widget you just have to call DocumentUtils.getDocumentDescriptionFromTitle(snapshot, text1).

If you have the documents titles in your snapshot.data.documents then it would be something like :

class DocumentUtils {

  static String getDocumentDescriptionFromTitle(AsyncSnapshot<YourObject> snapshot, String title) {
    return snapshot.data.documents.firstWhere((Document d) => d.title == title)['desc'].replaceAll("/n", "\n");
  }

}


来源: stackexchange

问:
javascript remove "disabled" attribute from html input
How can I remove the "disabled" attribute from an HTML input using javascript?

```<code><input id="edit" disabled>
</code>```

at onClick I want my input tag to not consist of "disabled" attribute.

答:
Best answer is just removeAttribute</p>

```<code>element.removeAttribute("disabled");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I remove the "disabled" attribute from an HTML input using javascript?

<input id="edit" disabled>

at onClick I want my input tag to not consist of "disabled" attribute.

Body:
Best answer is just removeAttribute

element.removeAttribute("disabled");


问:
Force screen redraw after drawing to screen's DC C++
I'm creating a Windows Mobile custom SIP and as the user presses or "hovers" over a button on the keyboard I draw it's corresponding selected image (iPhone-esque) to the screen's DC using ::GetDC(NULL).  It is developed in Win32 C++.

My problem is that I can never get the screen to repaint itself, erasing the previously drawn key.  I've tried everything I could think of to force it, ::RedrawWindow() with all different combos of params using NULL or any of the Get..Window functions as the HWND, and all combo of flags (INVALIDATE | UPDATENOW | ERASENOW | ALLCHILDREN etc).  I've also tried invalidating the rect and forcing a repaint of the underlying app using ::GetActiveWindow and ::GetForegroundWindow, variations using ::GetDesktopWindow, etc.  I've essentially run out of ideas and it's the last thing holding me up from using it on my Windows Mobile device.  Does anyone have any ideas? Any help would be greatly appreciated.

I've included some screenshots to illustrate my dilemma.

Before Screenshot

After Screenshot

Before http://img13.imageshack.us/img13/9861/cezoom1.png After http://img3.imageshack.us/img3/7481/cezoom2.png

Thanks in advance!

答:
Rather than drawing to the background DC, why don't you create a temporary window and draw into that? When you destroy the window, the background should get repainted automatically.

I'm just guessing, because I don't know Windows Mobile, but it could be that Windows is caching the last thing that was drawn into the DC and repainting it every time you invalidate the window.

OwnerDisplayName: MrPerphekt

LastEditorDisplayName: MrPerphekt

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Ransom


问:
Java Date rounding
I would like an elegant way to round a java Date up or down to the nearest minute (or second, hour, day).

For example a date of "Wed Jan 25 10:36:34 GMT 2012" rounded up to the nearest minute would be "Wed Jan 25 10:37:00 GMT 2012"

答:
```<code>   //How about if we represent the window to round to in Duration
   // like this
   Duration duration = Duration.of(14, ChronoUnit.MINUTES);

   // example of any time
   ZonedDateTime time = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
   long s = duration.getSeconds();
   long st = time.toEpochSecond();
   st = st - st%s;

   time = ZonedDateTime.ofInstant(Instant.ofEpochSecond(st), time.getZone());

   // this trims the nanos and round to secons
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java Date rounding


问:
unique constraint on the basis of foreign model field value django
I have three model in django applications.

for example:

```<code>class A(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class B(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)
</code>```

Now I want to make sure that value of field1 and field2 is unique together. I know i can use unique_togher = ('field1', 'field2'). but it only compare object id of model A and object id of model B.

But here actually i want to compare with actual field2 value of modelB

somethings like,

```<code>unique_together = ('field1', 'field2.field2')
</code>```

After suggestion of @Arvind Kumar i edited my model but still I'm facing error.
Here is my model after edit.

答:
You can not put unique constraints across the relations. You can only put columns belonging to the current Model only in unique constraints or unique_together. However, you can try the following approach

```<code>class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)

def validate_unique(self, exclude=None):
        qs = C.objects.filter(field1=self.field1)
        if qs.filter(B__field2=self.field2).exists():
            raise ValidationError('Fields must be unique')

        models.Model.validate_unique(self, exclude=exclude)
</code>```

Also, note that this function will not be called automatically while saving the objects of model C, so you will have to call it explicitly.

Body:
I have three model in django applications.

for example:

class A(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class B(models.Model):
    field1 = models.CharField(..)
    field2 = models.CharField(...)

class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)

Now I want to make sure that value of field1 and field2 is unique together. I know i can use unique_togher = ('field1', 'field2'). but it only compare object id of model A and object id of model B.

But here actually i want to compare with actual field2 value of modelB

somethings like,

unique_together = ('field1', 'field2.field2')

After suggestion of @Arvind Kumar i edited my model but still I'm facing error.
Here is my model after edit.

Body:
You can not put unique constraints across the relations. You can only put columns belonging to the current Model only in unique constraints or unique_together. However, you can try the following approach

class C(models.Model):
    field1 = models.ForeignKey(A, ..)
    field2 = models.ForeginKey(B, ..)

def validate_unique(self, exclude=None):
        qs = C.objects.filter(field1=self.field1)
        if qs.filter(B__field2=self.field2).exists():
            raise ValidationError('Fields must be unique')

        models.Model.validate_unique(self, exclude=exclude)

Also, note that this function will not be called automatically while saving the objects of model C, so you will have to call it explicitly.


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause'
Title

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from outcomes where (user_id = 37 and todos.outcome_id = outcomes.id) and outcomes.deleted_at is null)

In my laravel project I want to get the list of all task there corresponding Outcome values but this gives an error

```<code>  public function kanban()
    {
        $outcomes = Outcome::with('todos')
        ->where(function ($query) {
            $query->select(DB::raw(1))
                  ->from('todos')
                  ->where('user_id','=',Auth::user()->id)
                  ->whereRaw('todos.outcome_id = outcomes.id');
        })
        ->get();
        return view('taskmanagement.cruds.user.kanban',compact('outcomes'));
    }
</code>```

Here My Todo model

```<code>
<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Todo extends Model
{
    use SoftDeletes;

    //Table Name
    protected $table = 'todos';
    //Primary key
    public $primaryKey = 'id';

    protected $fillable = [

        'todoable_id',
        'todoable_type',
        'title',
        'description',
        'admin_id',
        'user_id',
        'project_id',
        'priority',
        'outcome_id',
        'tasktype_id',
        'started_at',
        'due_time',
        'completed_at',
    ];
    public function outcome() {

        return $this->belongsTo('App\Outcome');
    }

    public function user() {

        return $this->belongsTo('App\User');
    }

    public function todoable()
    {
        return $this->morphTo();
    }

}
</code>```

Outcome Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Outcome extends Model
{
    use SoftDeletes;

    //Table Name
    protected $table = 'outcomes';
    //Primary key
    public $primaryKey = 'id';

    protected $fillable = [

        'name'

    ];

    public function todos() {

        return $this->hasMany('App\Todo');
    }
}

</code>```

Output I want basically

答:
```<code>  public function kanban()
    {
        $outcomes = Outcome::with('todos')
        ->where(function ($query) {
            $query->select(DB::raw(1))
                  ->from('todos')
                  ->where('todos.user_id','=',Auth::user()->id)
                  ->whereRaw('todos.outcome_id','outcomes.id');
        })
        ->get();
        return view('taskmanagement.cruds.user.kanban',compact('outcomes'));
    }
</code>```

Body:
Title

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause' (SQL: select * from outcomes where (user_id = 37 and todos.outcome_id = outcomes.id) and outcomes.deleted_at is null)

In my laravel project I want to get the list of all task there corresponding Outcome values but this gives an error

  public function kanban()
    {
        $outcomes = Outcome::with('todos')
        ->where(function ($query) {
            $query->select(DB::raw(1))
                  ->from('todos')
                  ->where('user_id','=',Auth::user()->id)
                  ->whereRaw('todos.outcome_id = outcomes.id');
        })
        ->get();
        return view('taskmanagement.cruds.user.kanban',compact('outcomes'));
    }

Here My Todo model

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Todo extends Model
{
    use SoftDeletes;

    //Table Name
    protected $table = 'todos';
    //Primary key
    public $primaryKey = 'id';

    protected $fillable = [

        'todoable_id',
        'todoable_type',
        'title',
        'description',
        'admin_id',
        'user_id',
        'project_id',
        'priority',
        'outcome_id',
        'tasktype_id',
        'started_at',
        'due_time',
        'completed_at',
    ];
    public function outcome() {

        return $this->belongsTo('App\Outcome');
    }

    public function user() {

        return $this->belongsTo('App\User');
    }

    public function todoable()
    {
        return $this->morphTo();
    }

}

Outcome Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Outcome extends Model
{
    use SoftDeletes;

    //Table Name
    protected $table = 'outcomes';
    //Primary key
    public $primaryKey = 'id';

    protected $fillable = [

        'name'

    ];

    public function todos() {

        return $this->hasMany('App\Todo');
    }
}

Output I want basically


问:
IdentityServer4 automatically logout after 30 minutes
I have IdentityServer4 with Angular. Every 5 minutes the token is silent refreshed. But after 30minutes the user is automatically logged out. I was trying to set lifetime cookies somehow, without any success.

This is my current configuration:

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Identity")));

        services.AddIdentity<AppUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = false;
                options.SignIn.RequireConfirmedEmail = true;
                options.User.RequireUniqueEmail = true;
                options.User.AllowedUserNameCharacters = null;
            })
            .AddEntityFrameworkStores<AppIdentityDbContext>()
            .AddDefaultTokenProviders();

        services.AddIdentityServer(options => options.Authentication.CookieLifetime = TimeSpan.FromHours(10))
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(Configuration["AppUrls:ClientUrl"]))
            .AddAspNetIdentity<AppUser>();

        services.AddTransient<IProfileService, IdentityClaimsProfileService>();

        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader()));

        services.AddRazorPages().AddRazorRuntimeCompilation();
    }
</code>```

@EDIT

If I will add

```<code>services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromHours(24);
});
</code>```

Then it working fine, but I bet this is not correct solution for my issue.

@EDIT2

I found this
https://github.com/IdentityModel/oidc-client-js/issues/911#issuecomment-617724445
and this helped me, but still not sure whether is proper way to solve it or it just next hack.

答:
As far as I know this is neither Identity Server 4 nor OpenID Connect issue.

It is the logic of Asp.Net Identity cookies. This should be configurable at the Startup.cs.

You need to add following cookie configuration:

```<code>services.ConfigureApplicationCookie(o =>
{
    o.ExpireTimeSpan = TimeSpan.FromHours(24);
    o.SlidingExpiration = true;
});
</code>```

This answer is inspired from following answers:

Why doesn't cookie ExpireTimeSpan setting work?

ASP.NET Identity Session Timeout

Why does my IdentityServer4 based server timeout in 30 minutes and only support SSO in the first 30 minutes?

Body:
I have IdentityServer4 with Angular. Every 5 minutes the token is silent refreshed. But after 30minutes the user is automatically logged out. I was trying to set lifetime cookies somehow, without any success.

This is my current configuration:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Identity")));

        services.AddIdentity<AppUser, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = false;
                options.SignIn.RequireConfirmedEmail = true;
                options.User.RequireUniqueEmail = true;
                options.User.AllowedUserNameCharacters = null;
            })
            .AddEntityFrameworkStores<AppIdentityDbContext>()
            .AddDefaultTokenProviders();

        services.AddIdentityServer(options => options.Authentication.CookieLifetime = TimeSpan.FromHours(10))
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(Configuration["AppUrls:ClientUrl"]))
            .AddAspNetIdentity<AppUser>();

        services.AddTransient<IProfileService, IdentityClaimsProfileService>();

        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader()));

        services.AddRazorPages().AddRazorRuntimeCompilation();
    }

@EDIT

If I will add

services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromHours(24);
});

Then it working fine, but I bet this is not correct solution for my issue.

@EDIT2

I found this
https://github.com/IdentityModel/oidc-client-js/issues/911#issuecomment-617724445
and this helped me, but still not sure whether is proper way to solve it or it just next hack.

Body:
As far as I know this is neither Identity Server 4 nor OpenID Connect issue.

It is the logic of Asp.Net Identity cookies. This should be configurable at the Startup.cs.

You need to add following cookie configuration:

services.ConfigureApplicationCookie(o =>
{
    o.ExpireTimeSpan = TimeSpan.FromHours(24);
    o.SlidingExpiration = true;
});

This answer is inspired from following answers:

Why doesn't cookie ExpireTimeSpan setting work?

ASP.NET Identity Session Timeout

Why does my IdentityServer4 based server timeout in 30 minutes and only support SSO in the first 30 minutes?


问:
My javascript function for clearing a form text input field is not working
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

```<code><!DOCTYPE html>
<html>

<head>

<script>
  function insert(num) {
    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clear() {
    document.view.viewer.value = "";
  }
</script>

<style>
body {
  background-image: url("peepee.png");
}
*{
  margin: 0px;
  padding: 0px;
}
.button {
  height:100px;
  width:100px;
  background-color:grey;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.clear {
  height:100px;
  width:400px;
  background-color: red;
  text-align:center;
  margin:2px;
  font-size: 50px;
  cursor: pointer;
  border: 0px;
}
.viewer {
  height: 100px;
  width: 430px;
  font-size: 50px;
  margin: 2px
}
</style>

</head>

<body>
  <div class= "main">
    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>
    <table>
      <tr>
        <td><input class="button" value="7" onclick= "insert(7)"></td>
        <td><input class="button" value="8" onclick= "insert(8)"></td>
        <td><input class="button" value="9" onclick= "insert(9)"></td>
        <td><input class="button" value="-" onclick= "insert('/')"></td>
      </tr>
      <tr>
        <td><input class="button" value="4" onclick= "insert(4)"></td>
        <td><input class="button" value="5" onclick= "insert(5)"></td>
        <td><input class="button" value="6" onclick= "insert(6)"></td>
        <td><input class="button" value="x" onclick= "insert('*')"></td>
      </tr>
      <tr>
        <td><input class="button" value="1" onclick= "insert(1)"></td>
        <td><input class="button" value="2" onclick= "insert(2)"></td>
        <td><input class="button" value="3" onclick= "insert(3)"></td>
        <td><input class="button" value="-" onclick= "insert('-')"></td>
      </tr>
      <tr>
        <td><input class="button" value="0" onclick= "insert(0)"></td>
        <td><input class="button" value="." onclick= "insert('.')"></td>
        <td><input class="button" value="=" onclick= "equal()"></td>
        <td><input class="button" value="+" onclick= "insert('+')"></td>
      </tr>
    </table>
    <table>
      <tr>
        <td><input class= "clear" value="Clear" onclick= "clear()"></td>
      </tr>
    </table>
  </div>
</body>

</html>
</code>```

答:
I agree with Sajjan Karn. The JavaScript clear function is an default function which clears the JavaScript console.

In this case, simply rename the function to clearView for example:

```<code><script>
  function insert(num) {
    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clearView() {
    document.view.viewer.value = "";
  }
</script>
</code>```

And the HTML for the button:

```<code><input class= "clear" value="Clear" onclick= "clearView()">
</code>```

In the future, I would try using the addEventListener function instead of manually adding the onclick attribute to buttons, like this:

```<code><script>
    document.querySelector('input.clear').addEventListener('click', function() {
        document.view.viewer.value = '';
    });
</script>
</code>```

I hope this answers your question, and good luck with the calculator!

Body:
Even though a lot of work is left, the basic calculator is done, everything is working just fine except the clear function. I can not get it to clear the viewer. need immediate help please.

(i put everything in one file so it is easy for everyone to understand the full thing)

Please avoid the styling tho.

So basically i made this extremely simple calculator with the function clear()
Any ideas on how i can make this function in order to clear the viewer?

<!DOCTYPE html>

    <form name= "view">
      <input class="viewer" name= "viewer">
    </form>

        <input class="button" value="7" onclick= "insert(7)">
        <input class="button" value="8" onclick= "insert(8)">
        <input class="button" value="9" onclick= "insert(9)">
        <input class="button" value="-" onclick= "insert('/')">

        <input class="button" value="4" onclick= "insert(4)">
        <input class="button" value="5" onclick= "insert(5)">
        <input class="button" value="6" onclick= "insert(6)">
        <input class="button" value="x" onclick= "insert('*')">

        <input class="button" value="1" onclick= "insert(1)">
        <input class="button" value="2" onclick= "insert(2)">
        <input class="button" value="3" onclick= "insert(3)">
        <input class="button" value="-" onclick= "insert('-')">

        <input class="button" value="0" onclick= "insert(0)">
        <input class="button" value="." onclick= "insert('.')">
        <input class="button" value="=" onclick= "equal()">
        <input class="button" value="+" onclick= "insert('+')">

        <input class= "clear" value="Clear" onclick= "clear()">

Body:
I agree with Sajjan Karn. The JavaScript clear function is an default function which clears the JavaScript console.

In this case, simply rename the function to clearView for example:

<script>
  function insert(num) {
    document.view.viewer.value = document.view.viewer.value+num
  }
  function equal() {
    document.view.viewer.value = eval(document.view.viewer.value);
  }
  function clearView() {
    document.view.viewer.value = "";
  }
</script>

And the HTML for the button:

<input class= "clear" value="Clear" onclick= "clearView()">

In the future, I would try using the addEventListener function instead of manually adding the onclick attribute to buttons, like this:

<script>
    document.querySelector('input.clear').addEventListener('click', function() {
        document.view.viewer.value = '';
    });
</script>

I hope this answers your question, and good luck with the calculator!


问:
Problem integrating a toolbar into an recyclerview
I have a problem and I need your help. I have created a RecyclerView and it was okay. Now I want to have a toolbar at the top with a black background and red text. The RecyclerView, which is basically a list of items, should start under the toolbar. I inserted a toolbar but unfortunately it is not displayed at all, altough in the blueprint of Android Studio it can be seen. However, on the normal layout screen you can't see it and also on the editor you can't see it. Here I have some screenshots:

Here is the XML layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyDrinks">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="432dp"
        android:layout_height="135dp"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp"
            android:text="Test Toolbar" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dp"
        android:scrollbars="vertical"
        android:background="@android:color/white"
        ></androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>
</code>```

Does anyone know what the problem might be? So basically the toolbar is not displayed at all and secondly the recyclerview list starts at the very top which I do not want. I'd appreciate every feedback.

答:
The Recyclerview is overlapped with the Toolbar. Add this to the RecyclerView

```<code>android:layout_below="@+id/toolbar_mainActivity"
</code>```

You XML should be like this:

```<code><androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar_mainActivity"
    android:layout_width="432dp"
    android:layout_height="135dp"
    android:background="@android:color/black"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:titleTextColor="@android:color/holo_red_dark">

    <TextView
        android:id="@+id/textView_ToolBar_ActivityTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:layout_gravity="center"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="24sp"
        android:text="Test Toolbar" />
</androidx.appcompat.widget.Toolbar>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    android:scrollbars="vertical"
    android:layout_below="@+id/toolbar_mainActivity"
    android:background="@android:color/white"
    ></androidx.recyclerview.widget.RecyclerView>
</code>```

Body:
I have a problem and I need your help. I have created a RecyclerView and it was okay. Now I want to have a toolbar at the top with a black background and red text. The RecyclerView, which is basically a list of items, should start under the toolbar. I inserted a toolbar but unfortunately it is not displayed at all, altough in the blueprint of Android Studio it can be seen. However, on the normal layout screen you can't see it and also on the editor you can't see it. Here I have some screenshots:

Here is the XML layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyDrinks">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="432dp"
        android:layout_height="135dp"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp"
            android:text="Test Toolbar" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dp"
        android:scrollbars="vertical"
        android:background="@android:color/white"
        ></androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>

Does anyone know what the problem might be? So basically the toolbar is not displayed at all and secondly the recyclerview list starts at the very top which I do not want. I'd appreciate every feedback.

Body:
The Recyclerview is overlapped with the Toolbar. Add this to the RecyclerView

android:layout_below="@+id/toolbar_mainActivity"

You XML should be like this:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar_mainActivity"
    android:layout_width="432dp"
    android:layout_height="135dp"
    android:background="@android:color/black"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:titleTextColor="@android:color/holo_red_dark">

    <TextView
        android:id="@+id/textView_ToolBar_ActivityTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:layout_gravity="center"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="24sp"
        android:text="Test Toolbar" />
</androidx.appcompat.widget.Toolbar>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    android:scrollbars="vertical"
    android:layout_below="@+id/toolbar_mainActivity"
    android:background="@android:color/white"
    ></androidx.recyclerview.widget.RecyclerView>


问:
Is it better to have an "ORDER BY" column in a different table?
I have the following table which stores images:

```<code>id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows
</code>```

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

```<code>id        image_id       priority
1            1              1
2            12             2
3            22             1
</code>```

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?

答:
Please use below query, there is no need of having one more table. You can create appropriate index and utilize same table</p>

```<code>select image from images order by id, priority;
</code>```

Body:
I have the following table which stores images:

id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

id        image_id       priority
1            1              1
2            12             2
3            22             1

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?

Body:
Please use below query, there is no need of having one more table. You can create appropriate index and utilize same table

select image from images order by id, priority;


问:
problem in Laravel to show vueJs component
I'm using VueJs in my laravel blade. i define component to use as a child in one of components ,now component is not defined.

defined component in app.js

```<code>Vue.component('phoneSearch', require('./components/admin/booking/PhoneSearch').default);
</code>```

my component code :

<template>

</template>

```
</div>
</div>
</p>

<p>and that parent component that i want call child in:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> <template>

    </template>

    <script>
        export default {
            name: "add-passenger",

        components: {  phoneSearch },
        }
    </script>

    <style scoped>

    </style></code>```

finally i got this error in console after run:

```<code>Uncaught ReferenceError: phoneSearch is not defined
at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:7878)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:144061)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue (app_admin.js:144025)
at __webpack_require__ (app_admin.js:20)
at Object../resources/js/app_admin.js (app_admin.js:141625)
at __webpack_require__ (app_admin.js:20)
at Object.1 (app_admin.js:144544)
at __webpack_require__ (app_admin.js:20)
</code>```

anyone can help me?

答:
You need to import the child component locally inside the parent component to display it</p>
```<code> <template>
    <div>
       <your-component></your-component>
    </div>
 </template>

 <script>
      import yourComponent from './components/child-component.vue';

      export default {
                 components: {  yourComponent },
               }
 </script>
</code>```

Body:
I'm using VueJs in my laravel blade. i define component to use as a child in one of components ,now component is not defined.

defined component in app.js

Vue.component('phoneSearch', require('./components/admin/booking/PhoneSearch').default);

my component code :

<template>

</template>

and that parent component that i want call child in:

 <template>

    </template>

finally i got this error in console after run:

Uncaught ReferenceError: phoneSearch is not defined
at Module../node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:7878)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue?vue&type=script&lang=js& (app_admin.js:144061)
at __webpack_require__ (app_admin.js:20)
at Module../resources/js/components/admin/booking/AddPassenger.vue (app_admin.js:144025)
at __webpack_require__ (app_admin.js:20)
at Object../resources/js/app_admin.js (app_admin.js:141625)
at __webpack_require__ (app_admin.js:20)
at Object.1 (app_admin.js:144544)
at __webpack_require__ (app_admin.js:20)

anyone can help me?

Body:
You need to import the child component locally inside the parent component to display it

 <template>
    <div>
       <your-component></your-component>
    </div>
 </template>

 <script>
      import yourComponent from './components/child-component.vue';

      export default {
                 components: {  yourComponent },
               }
 </script>


问:
Flutter: how to prevent device orientation changes and force portrait?
I would like to prevent my application from changing its orientation and force the layout to stick to "portrait".

In the main.dart, I put:

```<code>void main(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(new MyApp());
}
</code>```

but when I use the Android Simulator rotate buttons, the layout "follows" the new device orientation...

How could I solve this?

Thanks

答:
As of new flutter versions along with setting the preferred Orientation we need to add one extra line i.e

```<code> WidgetsFlutterBinding.ensureInitialized();
</code>```

So working code for this is -

```<code>import 'package:flutter/services.dart';
    void main() {
          WidgetsFlutterBinding.ensureInitialized();
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.portraitUp,
            DeviceOrientation.portraitDown
          ]);
          runApp(MyApp());
        }
</code>```

Body:
I would like to prevent my application from changing its orientation and force the layout to stick to "portrait".

In the main.dart, I put:

void main(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(new MyApp());
}

but when I use the Android Simulator rotate buttons, the layout "follows" the new device orientation...

How could I solve this?

Thanks

Body:
As of new flutter versions along with setting the preferred Orientation we need to add one extra line i.e

 WidgetsFlutterBinding.ensureInitialized();

So working code for this is -

import 'package:flutter/services.dart';
    void main() {
          WidgetsFlutterBinding.ensureInitialized();
          SystemChrome.setPreferredOrientations([
            DeviceOrientation.portraitUp,
            DeviceOrientation.portraitDown
          ]);
          runApp(MyApp());
        }


问:
jqGrid multiselect "check all" in header: how to hide it?
I use jqGrid with the multiselect option set to true.

I'm looking for a way to hide or disable the first checkbox (the one in the row of the column names) so that users can't use the "check all/uncheck all" feature.

How to do it?

答:
The checkbox in the header has the id which is combined from the "cb_" prefix and the grid id. So you can hide the element with</p>

```<code>var myGrid = $("#list");
$("#cb_"+myGrid[0].id).hide();
</code>```

Body:
The checkbox in the header has the id which is combined from the "cb_" prefix and the grid id. So you can hide the element with

var myGrid = $("#list");
$("#cb_"+myGrid[0].id).hide();


问:
How to find the size of a C string without using a while loop?
I was recently trying to find the size of an input C string buffer for using it in memcpy to copy the contents of the input buffers to the output buffer without overlapping.
The following is the code snippet.

```<code>char * func(char *buff1, char *buff2, char *outbuff)
{
    int size = 0;
    while(*buff1 != '\0')
     {
       size++;
       buff1++;
     }
   memcpy(outbuff, buff1, sizeof(char)*size);
   memcpy(outbuff + size, buff2, sizeof(char)*size);
   return outbuff;
}
</code>```

However, I found out that this is a very inefficient way of finding size. If you guys know about any other alternatives it would be very helpful to me.

Edit: I am not allowed to pass their sizes as separate parameters.

答:
There's no solution to your problem. You ask for something like a vector, but vectors only know their size because they store it. Since it seems you aren't allowed to change the signature of your function then a loop is your only alternative. In any case it doesn't seem that inefficient to me.

Your code does have bugs, when you are calculating the size of buff1 you adjust the buff1 pointer, so that is no longer points to the start of the block when you do the copy. You need to substract the size of the buffer before you copy. Also you seem to be assuming that your two input buffers are the same size.

This would seem to be a better version of your code.

```<code>char* func(char *buff1, char *buff2, char *outbuff)
{
    int size1 = 0;
    while (*buff1 != '\0')
    {
        size1++;
        buff1++;
    }
    int size2 = 0;
    while (*buff2 != '\0')
    {
        size2++;
        buff2++;
    }
    memcpy(outbuff, buff1 - size1, sizeof(char)*size1);
    memcpy(outbuff + size1, buff2 - size2, sizeof(char)*size2);
    return outbuff;
}
</code>```

You could use strlen which does the same thing as the code above, but strlen is a loop as well. So the advantage of using strlen is not that you are avoiding a loop, only that the code is a little easier to understand.

```<code>#include <cstring>

char* func(char *buff1, char *buff2, char *outbuff)
{
    int size1 = strlen(buff1);
    int size2 = strlen(buff2);
    memcpy(outbuff, buff1, sizeof(char)*size1);
    memcpy(outbuff + size1, buff2, sizeof(char)*size2);
    return outbuff;
}
</code>```

Then finally you could use strcpy and strcat, which also have similar effect

```<code>#include <cstring>

char* func(char *buff1, char *buff2, char *outbuff)
{
    strcpy(outbuff, buff1);
    strcat(outbuff, buff2);
    return outbuff;
}
</code>```

This apparently avoids any loops and size calculations at all. But of course they are still happening, just internally to the strcpy and strcat functions.

There is one difference between this latest version and the two previous versions. The version with strcpy and strcat also copies the terminating '\0' character to outbuff, so outbuff will be null temrinated just ilke you are assuming that buff1 abd buff2 are. This seems like an advantage to me, but you might not agree.

Body:
I was recently trying to find the size of an input C string buffer for using it in memcpy to copy the contents of the input buffers to the output buffer without overlapping.
The following is the code snippet.

char * func(char *buff1, char *buff2, char *outbuff)
{
    int size = 0;
    while(*buff1 != '\0')
     {
       size++;
       buff1++;
     }
   memcpy(outbuff, buff1, sizeof(char)*size);
   memcpy(outbuff + size, buff2, sizeof(char)*size);
   return outbuff;
}

However, I found out that this is a very inefficient way of finding size. If you guys know about any other alternatives it would be very helpful to me.

Edit: I am not allowed to pass their sizes as separate parameters.

Body:
There's no solution to your problem. You ask for something like a vector, but vectors only know their size because they store it. Since it seems you aren't allowed to change the signature of your function then a loop is your only alternative. In any case it doesn't seem that inefficient to me.

Your code does have bugs, when you are calculating the size of buff1 you adjust the buff1 pointer, so that is no longer points to the start of the block when you do the copy. You need to substract the size of the buffer before you copy. Also you seem to be assuming that your two input buffers are the same size.

This would seem to be a better version of your code.

char* func(char *buff1, char *buff2, char *outbuff)
{
    int size1 = 0;
    while (*buff1 != '\0')
    {
        size1++;
        buff1++;
    }
    int size2 = 0;
    while (*buff2 != '\0')
    {
        size2++;
        buff2++;
    }
    memcpy(outbuff, buff1 - size1, sizeof(char)*size1);
    memcpy(outbuff + size1, buff2 - size2, sizeof(char)*size2);
    return outbuff;
}

You could use strlen which does the same thing as the code above, but strlen is a loop as well. So the advantage of using strlen is not that you are avoiding a loop, only that the code is a little easier to understand.

#include <cstring>

char* func(char *buff1, char *buff2, char *outbuff)
{
    int size1 = strlen(buff1);
    int size2 = strlen(buff2);
    memcpy(outbuff, buff1, sizeof(char)*size1);
    memcpy(outbuff + size1, buff2, sizeof(char)*size2);
    return outbuff;
}

Then finally you could use strcpy and strcat, which also have similar effect

#include <cstring>

char* func(char *buff1, char *buff2, char *outbuff)
{
    strcpy(outbuff, buff1);
    strcat(outbuff, buff2);
    return outbuff;
}

This apparently avoids any loops and size calculations at all. But of course they are still happening, just internally to the strcpy and strcat functions.

There is one difference between this latest version and the two previous versions. The version with strcpy and strcat also copies the terminating '\0' character to outbuff, so outbuff will be null temrinated just ilke you are assuming that buff1 abd buff2 are. This seems like an advantage to me, but you might not agree.


问:
Transform array of arrays to a single array
I would like to expand a list of arrays into a single array, so for example:

```<code>a = [array([1,2,3]), array([4,5,6]), array([7,8,9,])]
</code>```

To become:

```<code>a = [array([1,2,3,4,5,6,7,8,9])]
</code>```

How do I do this?

答:
Try using

```<code>list.extend
</code>```

It will work
Maybe you want this

```<code>from numpy import array
k=[array([1,2,3]), array([4,5,6]), array([7,8,9,])]
l=[]
for i in range(len(k)):
  l.extend(k[i])
print(array(l))
</code>```

Output:

```<code>array([1, 2, 3, 4, 5, 6, 7, 8, 9])

</code>```

Body:
I would like to expand a list of arrays into a single array, so for example:

a = [array([1,2,3]), array([4,5,6]), array([7,8,9,])]

To become:

a = [array([1,2,3,4,5,6,7,8,9])]

How do I do this?

Body:
Try using

list.extend

It will work
Maybe you want this

from numpy import array
k=[array([1,2,3]), array([4,5,6]), array([7,8,9,])]
l=[]
for i in range(len(k)):
  l.extend(k[i])
print(array(l))

Output:

array([1, 2, 3, 4, 5, 6, 7, 8, 9])


问:
Collecting and comparing ruby hashes inside array
I have a ruby Array that has multiple hashes inside it. Looks as follows:

```<code>arr_hsh = [
      {
        'name': 'Outdoor',
        'game_code': 'C5',
        'score': '61.68',
      },
      {
        'name': 'Indoor',
        'game_code': 'C6',
        'score': '37.54',
      }
]
</code>```

I want to return game_code and score pair with the highest score value.

How can I achieve this without doing multiple iterations.

If I do

```<code>arr_hsh.collect {|p| "#{p[:game_code]}: #{p[:score]}"}
</code>```

Its just returning this

```<code>["C5: 61.68", "C6: 37.54"]
</code>```

but I want [C5 => 61.68]

How can I get this?

答:
You can use the Enumerable#max_by method in this way and Object#then (or Object#yield_self for older versions of Ruby):

```<code>arr_hsh.max_by { |h| h['score'] }.then { |res| { res[:game_code] => res[:score] } }
#=> {"C5"=>"61.68"}
</code>```

The first part is working this way:

```<code>arr_hsh.max_by { |h| h['score'] }
#=> {:name=>"Outdoor", :game_code=>"C5", :score=>"61.68"}
</code>```

The second part takes this output and builds the final Hash, if this is the object you want or whathever.

Consider to convert the score to float, currently is a string.

Body:
I have a ruby Array that has multiple hashes inside it. Looks as follows:

arr_hsh = [
      {
        'name': 'Outdoor',
        'game_code': 'C5',
        'score': '61.68',
      },
      {
        'name': 'Indoor',
        'game_code': 'C6',
        'score': '37.54',
      }
]

I want to return game_code and score pair with the highest score value.

How can I achieve this without doing multiple iterations.

If I do

arr_hsh.collect {|p| "#{p[:game_code]}: #{p[:score]}"}

Its just returning this

["C5: 61.68", "C6: 37.54"]

but I want [C5 => 61.68]

How can I get this?

Body:
You can use the Enumerable#max_by method in this way and Object#then (or Object#yield_self for older versions of Ruby):

arr_hsh.max_by { |h| h['score'] }.then { |res| { res[:game_code] => res[:score] } }
#=> {"C5"=>"61.68"}

The first part is working this way:

arr_hsh.max_by { |h| h['score'] }
#=> {:name=>"Outdoor", :game_code=>"C5", :score=>"61.68"}

The second part takes this output and builds the final Hash, if this is the object you want or whathever.

Consider to convert the score to float, currently is a string.


问:
rails webpack-dev-server "Invalid configuration object"
When I try to run ./bin/webpack-dev-server I get this:

```<code>Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration has an unknown property 'mode'. These properties are valid:
   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
   For typos: please correct them.
   For loader options: webpack 2 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           mode: ...
         }
       })
     ]
</code>```

I'm pretty sure this is yarn messing up with package versions. Is there a "reinstall everything" command I can run?

My versions are

webpack-dev-server@3.4.1

@rails/webpacker@3.5.5

答:
Most likely a problems with webpacker.yml.

In my case source_path was incorrect.

See this: Invalid configuration object when starting webpack-dev-server

Body:
When I try to run ./bin/webpack-dev-server I get this:

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration has an unknown property 'mode'. These properties are valid:
   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
   For typos: please correct them.
   For loader options: webpack 2 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           mode: ...
         }
       })
     ]

I'm pretty sure this is yarn messing up with package versions. Is there a "reinstall everything" command I can run?

My versions are

webpack-dev-server@3.4.1

@rails/webpacker@3.5.5


问:
retain unique combinations from a list of tuples in python
I have a list of tuples that contain int and str values in them:

```<code>Listex:
[23,'item1','item2']
[23,'item2','item1']
[67,'item3','item2']
[55,'item3','item4']
[67,'item2','item3']
[55,'item4','item3']
</code>```

What I need is to get unique tuples:

```<code>Listex output:
[23,'item1','item2']
[67,'item2','item3']
[55,'item3','item4']
</code>```

I have tried sort() but I get the error that '<' cannot be used with str and int.
Appreciate any help in this regard.
Thank you in advance.

答:
First of all use frozenset so that comparisons wont take into account the order of the strings, then use a set to remove duplicates, finally convert back to list of lists:

```<code>In [1]: data = [[23,'item1','item2'],
   ...: [23,'item2','item1'],
   ...: [67,'item3','item2'],
   ...: [55,'item3','item4'],
   ...: [67,'item2','item3'],
   ...: [55,'item4','item3']]

In [2]: list(map(list, set(map(frozenset, data))))
Out[2]: [[67, 'item2', 'item3'], ['item1', 'item2', 23], ['item3', 'item4', 55]]
</code>```

You cannot directly apply set to your original collection because set requires its elements to be hashable, which lists are not. Converting the inner lists into frozenset makes them hashable and has the added bonus of being order-independent. Using a tuple would make the elements hashable but order of the elements would matter.

Depending on what you want to do with the data maybe you can simply use a set of frozensets and avoid the lists altogether:

```<code>In [3]: set(map(frozenset, data))
Out[3]:
{frozenset({67, 'item2', 'item3'}),
 frozenset({23, 'item1', 'item2'}),
 frozenset({55, 'item3', 'item4'})}
</code>```

If you want to keep the number as the first element you can replace list with some function like:

```<code>In [5]: def keep_number_first(seq):
   ...:     return sorted(seq, key=lambda x: 1 if not isinstance(x, (int, float)) else 0)
   ...:
</code>```

which sorts by type:

```<code>In [6]: list(map(keep_number_first, set(map(frozenset, data))))
Out[6]: [[67, 'item2', 'item3'], [23, 'item1', 'item2'], [55, 'item3', 'item4']]
</code>```

This said: if you have to keep data structured in this way, IMHO, it's probably better to come up with your own class or use a namedtuple and give some meaning to the different pieces. For example instead of having [23, 'item1', 'item2'] why not (23, ['item1', 'item2'])?

Body:
I have a list of tuples that contain int and str values in them:

Listex:
[23,'item1','item2']
[23,'item2','item1']
[67,'item3','item2']
[55,'item3','item4']
[67,'item2','item3']
[55,'item4','item3']

What I need is to get unique tuples:

Listex output:
[23,'item1','item2']
[67,'item2','item3']
[55,'item3','item4']

I have tried sort() but I get the error that '<' cannot be used with str and int.
Appreciate any help in this regard.
Thank you in advance.

Body:
First of all use frozenset so that comparisons wont take into account the order of the strings, then use a set to remove duplicates, finally convert back to list of lists:

In [1]: data = [[23,'item1','item2'],
   ...: [23,'item2','item1'],
   ...: [67,'item3','item2'],
   ...: [55,'item3','item4'],
   ...: [67,'item2','item3'],
   ...: [55,'item4','item3']]

In [2]: list(map(list, set(map(frozenset, data))))
Out[2]: [[67, 'item2', 'item3'], ['item1', 'item2', 23], ['item3', 'item4', 55]]

You cannot directly apply set to your original collection because set requires its elements to be hashable, which lists are not. Converting the inner lists into frozenset makes them hashable and has the added bonus of being order-independent. Using a tuple would make the elements hashable but order of the elements would matter.

Depending on what you want to do with the data maybe you can simply use a set of frozensets and avoid the lists altogether:

In [3]: set(map(frozenset, data))
Out[3]:
{frozenset({67, 'item2', 'item3'}),
 frozenset({23, 'item1', 'item2'}),
 frozenset({55, 'item3', 'item4'})}

If you want to keep the number as the first element you can replace list with some function like:

In [5]: def keep_number_first(seq):
   ...:     return sorted(seq, key=lambda x: 1 if not isinstance(x, (int, float)) else 0)
   ...:

which sorts by type:

In [6]: list(map(keep_number_first, set(map(frozenset, data))))
Out[6]: [[67, 'item2', 'item3'], [23, 'item1', 'item2'], [55, 'item3', 'item4']]

This said: if you have to keep data structured in this way, IMHO, it's probably better to come up with your own class or use a namedtuple and give some meaning to the different pieces. For example instead of having [23, 'item1', 'item2'] why not (23, ['item1', 'item2'])?


问:
Numpy flatten RGB image array
I have 1,000 RGB images (64X64) which I want to convert to an (m, n) array.

I use this:

```<code>import numpy as np
from skdata.mnist.views import OfficialImageClassification
from matplotlib import pyplot as plt
from PIL import Image
import glob
import cv2

x_data = np.array( [np.array(cv2.imread(imagePath[i])) for i in range(len(imagePath))] )
print x_data.shape
</code>```

Which gives me: (1000, 64, 64, 3)

Now if I do:

```<code>pixels = x_data.flatten()
print pixels.shape
</code>```

I get: (12288000,)

However, I require an array with these dimensions: (1000, 12288)

How can I achieve that?

答:
Assuming you have an array image_array you can use the reshape() method.

```<code>image_array = image_array.reshape(1000, 12288)
</code>```

Title: Numpy flatten RGB image array

Body:
I have 1,000 RGB images (64X64) which I want to convert to an (m, n) array.

I use this:

import numpy as np
from skdata.mnist.views import OfficialImageClassification
from matplotlib import pyplot as plt
from PIL import Image
import glob
import cv2

x_data = np.array( [np.array(cv2.imread(imagePath[i])) for i in range(len(imagePath))] )
print x_data.shape

Which gives me: (1000, 64, 64, 3)

Now if I do:

pixels = x_data.flatten()
print pixels.shape

I get: (12288000,)

However, I require an array with these dimensions: (1000, 12288)

How can I achieve that?

Body:
Assuming you have an array image_array you can use the reshape() method.

image_array = image_array.reshape(1000, 12288)