问:
Is there any way to mock private functions with Jest?
The ES6 module that I want to test looks as follows:

```<code>function privateFunction() {
   ...
}
export function publicFunction() {
   ... does something ...
   privateFunction()
   ... does something else ...
}
</code>```

I am using JEST for my unit tests and I am trying to find a way to test publicFunction and avoiding the execution of privateFunction by mocking it but I couldn't succeed in the mock attempt. Any idea?

答:
Another option would be an explicit cast:

const spy = jest.spyOn((someInstance as unknown) as { privateMethod: SomeClass['privateMethod'] }, 'privateMethod');
```

It's a bit lengthy, but it has the advantage of keeping the typing of the private method for subsequent checks like spy.hasBeenCalledWith(...).

Body:
The ES6 module that I want to test looks as follows:

function privateFunction() {
   ...
}
export function publicFunction() {
   ... does something ...
   privateFunction()
   ... does something else ...
}

I am using JEST for my unit tests and I am trying to find a way to test publicFunction and avoiding the execution of privateFunction by mocking it but I couldn't succeed in the mock attempt. Any idea?

Body:
Another option would be an explicit cast:

const spy = jest.spyOn((someInstance as unknown) as { privateMethod: SomeClass['privateMethod'] }, 'privateMethod');

It's a bit lengthy, but it has the advantage of keeping the typing of the private method for subsequent checks like spy.hasBeenCalledWith(...).


来源: stackexchange

问:
I want to go to another page when I click on the image in Flutter
I'm a newbie in Flutter and I'm trying to design a page to let the user choose the user type.
And I'm trying to use onTap method so that when I click on the picture I go to the selected user type page but when I used the onTap method the user type image disappears.
I don't know if I'm using the right method or if I'm using it in a wrong way.
But here is what my code looks like you maybe able to help me :)
thank you</p>
```<code>import 'package:flutter/material.dart';

class ChooseUser extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Container(
          padding: const EdgeInsets.fromLTRB(0, 250, 0, 0),
          child: new Column(
            children: [
              new Container(
                alignment: Alignment(0.4, 0.2),
                child: new Text(
                  "فضلًا أختر نوع المستخدم",
                  style: TextStyle(
                      fontSize: 30,
                      fontFamily: 'Cairo',
                      color: Color(0xFF403E3E),
                      shadows: [
                        Shadow(
                            color: Color(0xFF403E3E),
                            offset: Offset(1, 1),
                            blurRadius: 1)
                      ]),
                ),
              ),
              new Container(
                  height: 300.0,
                  width: 300.0,
                  padding: const EdgeInsets.fromLTRB(15, 120, 0, 0),
                  child: new Row(children: [
                    new Column(
                      children: [
                        new Container(
                          margin: const EdgeInsets.only(right: 40.0),
                          height: 100.0,
                          width: 100.0,
                          decoration: new BoxDecoration(
                            image: DecorationImage(
                                image: new AssetImage(
                                    'assets/images/elderly-icon.png'),
                                fit: BoxFit.fill),
                          ),
                        ),
                        new Container(
                            margin: const EdgeInsets.only(right: 40.0, top: 10),
                            child: new Text(
                              "كبير سن",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            )),
                      ],
                    ),
                    new Column(children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).pushNamed('medical-choose');
                          new Container(
                            margin: const EdgeInsets.only(left: 20.0),
                            height: 100.0,
                            width: 100.0,
                            decoration: new BoxDecoration(
                              image: DecorationImage(
                                  image: new AssetImage(
                                      'assets/images/staff-icon.png'),
                                  fit: BoxFit.fill),
                            ),
                          );
                          new Container(
                            margin: const EdgeInsets.only(left: 10.0, top: 10),
                            child: new Text(
                              "طاقم طبي",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            ),
                          );
                        },
                      ),
                    ]),
                  ])),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
first of all the new keyword are optional, second there is no need to use GestureDetector instead use InkWell widget which is the basic of all clickable widget.

InkWell(
      child: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(
                          'assets/images/staff-icon.png'
                      ),
                      fit: BoxFit.fill
                  )
              )
          )
      ),
      onTap: () {
        Navigator.of(context).pushNamed('medical-choose');
      },
    );
```

ContentLicense: CC BY-SA 4.0

Body:
I'm a newbie in Flutter and I'm trying to design a page to let the user choose the user type.
And I'm trying to use onTap method so that when I click on the picture I go to the selected user type page but when I used the onTap method the user type image disappears.
I don't know if I'm using the right method or if I'm using it in a wrong way.
But here is what my code looks like you maybe able to help me :)
thank you

import 'package:flutter/material.dart';

class ChooseUser extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Container(
          padding: const EdgeInsets.fromLTRB(0, 250, 0, 0),
          child: new Column(
            children: [
              new Container(
                alignment: Alignment(0.4, 0.2),
                child: new Text(
                  "فضلًا أختر نوع المستخدم",
                  style: TextStyle(
                      fontSize: 30,
                      fontFamily: 'Cairo',
                      color: Color(0xFF403E3E),
                      shadows: [
                        Shadow(
                            color: Color(0xFF403E3E),
                            offset: Offset(1, 1),
                            blurRadius: 1)
                      ]),
                ),
              ),
              new Container(
                  height: 300.0,
                  width: 300.0,
                  padding: const EdgeInsets.fromLTRB(15, 120, 0, 0),
                  child: new Row(children: [
                    new Column(
                      children: [
                        new Container(
                          margin: const EdgeInsets.only(right: 40.0),
                          height: 100.0,
                          width: 100.0,
                          decoration: new BoxDecoration(
                            image: DecorationImage(
                                image: new AssetImage(
                                    'assets/images/elderly-icon.png'),
                                fit: BoxFit.fill),
                          ),
                        ),
                        new Container(
                            margin: const EdgeInsets.only(right: 40.0, top: 10),
                            child: new Text(
                              "كبير سن",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            )),
                      ],
                    ),
                    new Column(children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).pushNamed('medical-choose');
                          new Container(
                            margin: const EdgeInsets.only(left: 20.0),
                            height: 100.0,
                            width: 100.0,
                            decoration: new BoxDecoration(
                              image: DecorationImage(
                                  image: new AssetImage(
                                      'assets/images/staff-icon.png'),
                                  fit: BoxFit.fill),
                            ),
                          );
                          new Container(
                            margin: const EdgeInsets.only(left: 10.0, top: 10),
                            child: new Text(
                              "طاقم طبي",
                              style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Cairo',
                                  color: Color(0xFF403E3E),
                                  shadows: [
                                    Shadow(
                                        color: Color(0xFF403E3E),
                                        offset: Offset(1, 1),
                                        blurRadius: 1)
                                  ]),
                            ),
                          );
                        },
                      ),
                    ]),
                  ])),
            ],
          ),
        ),
      ),
    );
  }
}


问:
The named parameter child is required but there's no corresponding argument
After upgrade my Flutter app is now producing this error at

```<code>return BaseWidget<BillsModel>(
</code>```

The named parameter child is required but there's no corresponding
argument.

My BaseWidget has a child parameter but I don't know how to specify the child. This code previously worked but now doesn't. I realise there are many similar questions but they are sufficiently different that I can't figure this out. I have many similar errors in my project which all extend from BaseWidget

```<code>class Bills extends StatelessWidget {

  const Bills({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    Tbl _table = Provider.of<Tbl>(context, listen: false);

    return BaseWidget<BillsModel>(

        model: BillsModel(api: Provider.of(context, listen: false)),

        onModelReady: (model) => model.fetchBills(context, _table.id),

        builder: (context, model, child) => model.busy

            ? Center(

                child: CircularProgressIndicator(),

              )

            : Expanded(

                child: ListView.builder(

                          shrinkWrap: true,

                          itemCount: model.bills.length,

                          itemBuilder: (context, index) => BillListItem(

                               bill: model.bills[index],
                          ),
                )
            )
    );
  }
}
</code>```

Here is my BillsModel

```<code>class BillsModel extends BaseModel {

  Api _api;

  BillsModel({required Api api}) : _api = api;

  List<Bill> bills = [];

  Future fetchBills(BuildContext context, int tableId) async {
    setBusy(true);
    bills = await _api.getBills(context, tableId);
    setBusy(false);
  }

 ...

  @override
  void dispose() {
    print('Bills has been disposed!!');
    super.dispose();
  }
}
</code>```

Here is my BaseWidget:

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

class BaseWidget<T extends ChangeNotifier> extends StatefulWidget {
  final Widget Function(BuildContext context, T model, Widget? child) builder;
  final T model;
  final Widget child;
  final Function(T) onModelReady;

  BaseWidget({
    Key? key,
    required this.builder,
    required this.model,
    required this.child,
    required this.onModelReady,
  }) : super(key: key);

  _BaseWidgetState<T> createState() => _BaseWidgetState<T>();
}

class _BaseWidgetState<T extends ChangeNotifier> extends State<BaseWidget<T>> {
  late T model;

  @override
  void initState() {

    model = widget.model;

      widget.onModelReady(model);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>(
      create: (context) => model,
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}
</code>```

答:
You should pass child parameters with any widget as your BaseWidget according to BaseWidget class.

Add an example code line, check it please

class Bills extends StatelessWidget {

  const Bills({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    Tbl _table = Provider.of<Tbl>(context, listen: false);

    return BaseWidget<BillsModel>(

        model: BillsModel(api: Provider.of(context, listen: false)),

        onModelReady: (model) => model.fetchBills(context, _table.id),
        child: const Sizedbox.shrink(), // Added This Line !
        builder: (context, model, child) => model.busy

            ? Center(

                child: CircularProgressIndicator(),

              )

            : Expanded(

                child: ListView.builder(

                          shrinkWrap: true,

                          itemCount: model.bills.length,

                          itemBuilder: (context, index) => BillListItem(

                               bill: model.bills[index],
                          ),
                )
            )
    );
  }
}
```

Body:
After upgrade my Flutter app is now producing this error at

return BaseWidget<BillsModel>(

The named parameter child is required but there's no corresponding
argument.

My BaseWidget has a child parameter but I don't know how to specify the child. This code previously worked but now doesn't. I realise there are many similar questions but they are sufficiently different that I can't figure this out. I have many similar errors in my project which all extend from BaseWidget

class Bills extends StatelessWidget {

  const Bills({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    Tbl _table = Provider.of<Tbl>(context, listen: false);

    return BaseWidget<BillsModel>(

        model: BillsModel(api: Provider.of(context, listen: false)),

        onModelReady: (model) => model.fetchBills(context, _table.id),

        builder: (context, model, child) => model.busy

            ? Center(

                child: CircularProgressIndicator(),

              )

            : Expanded(

                child: ListView.builder(

                          shrinkWrap: true,

                          itemCount: model.bills.length,

                          itemBuilder: (context, index) => BillListItem(

                               bill: model.bills[index],
                          ),
                )
            )
    );
  }
}

Here is my BillsModel

class BillsModel extends BaseModel {

  Api _api;

  BillsModel({required Api api}) : _api = api;

  List<Bill> bills = [];

  Future fetchBills(BuildContext context, int tableId) async {
    setBusy(true);
    bills = await _api.getBills(context, tableId);
    setBusy(false);
  }

 ...

  @override
  void dispose() {
    print('Bills has been disposed!!');
    super.dispose();
  }
}

Here is my BaseWidget:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class BaseWidget<T extends ChangeNotifier> extends StatefulWidget {
  final Widget Function(BuildContext context, T model, Widget? child) builder;
  final T model;
  final Widget child;
  final Function(T) onModelReady;

  BaseWidget({
    Key? key,
    required this.builder,
    required this.model,
    required this.child,
    required this.onModelReady,
  }) : super(key: key);

  _BaseWidgetState<T> createState() => _BaseWidgetState<T>();
}

class _BaseWidgetState<T extends ChangeNotifier> extends State<BaseWidget<T>> {
  late T model;

  @override
  void initState() {

    model = widget.model;

      widget.onModelReady(model);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>(
      create: (context) => model,
      child: Consumer<T>(
        builder: widget.builder,
        child: widget.child,
      ),
    );
  }
}


问:
Enable binary mode while restoring a Database from an SQL dump
I am  extremely new to MySQL and am running it on Windows. I am trying to restore a Database from a dumpfile in MySQL, but I get the following error:

```<code>$ >mysql -u root -p -h localhost -D database -o < dump.sql
ERROR: ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mode is enabled and mysql is run in non-interactive mode. Set --binary-mode to 1 if ASCII '\0' is expected. Query: 'SQLite format 3'.
</code>```

I have tried putting --binary-mode in the ini file but it still gives the same error. What should I do? Please help.

UPDATE

As suggested by Nick in his comment I tried $ > mysql -u root -p -h localhost -D database --binary-mode -o < dump.sql but it gave me the following ERROR at line 1: Unknown command '\☻'.
It is a 500 Mb dump file, and when I view its contents using gVIM, all I can see is expressions and data which is not comprehensible.

答:
I had a similar problem. I exported all databases with mysqldump on a PowerShell:

mysqldump -u root -p --all-databases

When I tried to import it on a PowerShell:

mysql -u root -p < .\all-databases.sql

I got an error saying something with < being reserved for future versions.

So I tried the above command with cmd and got the same error like OP.

The solution was to use PowerShell and the following command:

Get-Content '.\all-databases.sql' | &mysql.exe -u user -p

ContentLicense: CC BY-SA 3.0

Body:
I am  extremely new to MySQL and am running it on Windows. I am trying to restore a Database from a dumpfile in MySQL, but I get the following error:

$ >mysql -u root -p -h localhost -D database -o < dump.sql
ERROR: ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mode is enabled and mysql is run in non-interactive mode. Set --binary-mode to 1 if ASCII '\0' is expected. Query: 'SQLite format 3'.

I have tried putting --binary-mode in the ini file but it still gives the same error. What should I do? Please help.

UPDATE

As suggested by Nick in his comment I tried $ > mysql -u root -p -h localhost -D database --binary-mode -o < dump.sql but it gave me the following ERROR at line 1: Unknown command '\☻'.
It is a 500 Mb dump file, and when I view its contents using gVIM, all I can see is expressions and data which is not comprehensible.


问:
Original css styling is overriding my media query and vise versa
My media query which i set for (max-width 915px) changes the height of the css which i created for desktop even though the query comes after the original css, and when i change something in the original css, it reflects on the media query even though the values are different and should be overwritten.
please check the "form element" which created and try tinker the top and left positioning properties in the original part of css

body{
    font-family: Verdana, Geneva, Tahoma, sans-serif;

}

.content {
    width: 1400px;
    margin: auto;

    padding: 10px;
}

p {
    color: rgb(97, 87, 226);
}

p.foots {
    color:black ;

}

.para2 {
    color: black;
}

.logo {
    width: 100%;
    height: 300px;
    background-color: rgb(147, 235, 238);
}

div.navi {

    background-color: rgb(228, 226, 217);
    width: 100%;
    height: 50px;
    margin-top: 15px;
    text-align: center;
    font-size: 20px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    padding-top: 1px;
    margin-bottom: 1px;
}

p.nav {
    position: relative;
    bottom: 5px;
    border-style: solid;
}

a:link {
    text-decoration: none;
    color: rgb(97, 87, 226);
}

.navi3:link {
    color: rgb(7, 7, 7);
}

.logo-top {
    margin-left: 20px;
    width: 600px;
}

/* inner body styling */

div.inner-body {
    background-image: url(image/bk.png);
    margin-bottom: 20px;
    border-style: solid;
    margin-top: 20px;
    height: 1800px;
  position: relative;
}

.header {

    width: 700px;
    position: relative;
    left: 338px;
    font-size: 30px;
    top:100px;

}

.para {

    width: 800px;
    position: relative;
    left:345px;
    top:200px;
    background-color: rgb(206, 200, 180);
    font-size: 25px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 20px;
    padding: 5px;
}

form {
    padding: 20px;
    border-radius: 20px;
    width: 725px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    position: relative;
    left:350px;
    top:225px;
    background-color: rgb(206, 200, 180);
}

.field {
    width: 300px;
    font-size: 18px;

}

.field2 {
    width: 600px;
    font-size: 18px;
}
.field3 {
    width: 300px;
    height: 30px;
    border-radius: 10px;
    margin-top: 10px;
    background-color: rgb(193, 211, 205);

    cursor: pointer;
}

.field4 {
    width: 300px;
    font-size: 18px;
    cursor: pointer;
}

.error {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.error1 {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.navi2 {

    width: fit-content;
    width: 300px;
    height: 600px;
    position:absolute;

    background-color: cadetblue;
    font-size: 20px;
    border-radius: 20px;
    top:228px;
}

.user-links {
    position: relative;
    left:20px;
    bottom:30px;
}

.user-links:link{
    color: brown;
}

.userlogo {
    width: 200px;
    border-radius: 100px;
    position: relative;
    left: 50px;
    bottom: 100px;
}

/* footer styling */

.emaillogo, .telelogo {
    width: 20px;
}

footer{
    background-color: rgb(126, 226, 230);
    height: 200px;
}

.footimage {
    width: 400px;

    margin: 0;
}
div.contact{
    width: fit-content;
    height: 200px;

    position: relative;
    left: 400px;
    bottom: 185px;
    font-size: 12px;

}

.usefullinks {
    width: fit-content;
    font-size: 12px;
    position: relative;
    left:750px;
    bottom:400px;

}

.connect {
    width: fit-content;
    position: relative;
    left: 1100px ;
    bottom: 524px;
    font-size: 12px;
}

.fb, .tw, .yt, .ln {
    width: 50px;
    border-radius: 10px;

}

/* Media Queries */

@media screen and (max-width:915px) {

    div.logo {
        width: 900px;
        height: 400px;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }

    .logo-top {
        width: 800px;
    }

    .content {
        width: 100%;
       height: 100vh;
        padding: 0;

    }

    .inner-body {
        background-image: url(image/book2.png);
        height: 1800px;
        border-style: solid;
        margin-top: 15px;
        margin-bottom: 15px;
        width: 900px;
        position: relative;

    }

    div.navi {
        width: 900px;
        font-size: 28px;
        padding-bottom: 90px;
    }

    .header {
        left: 50px;
    }

    .para {
        width: 680px;
        display: block;
        left: 80px;
        font-size: 35px;
        padding: 30px;
        top: 10px;
        align-items: center;
    }

    form {
        width: 700px;
        left: 80px;
        font-size: 30px;
        border-style: solid;

    }

    .field {
        width: 400px;
        font-size: 30px;
    }

    .field2 {
        width: 600px;
        font-size: 30px;
    }
    .field3 {
        width: 300px;
        height: 30px;
        border-radius: 10px;
        margin-top: 10px;
        background-color: rgb(193, 211, 205);
        font-size: 25px;
        cursor: pointer;
    }

    .field4 {
        width: 300px;
        font-size: 30px;
        cursor: pointer;
    }
    .navi2 {

        display: none;
    }
    footer {
        display: none;

        padding: 0;
        list-style: none;
        background-color: rgb(126, 226, 230);
        font-size: 20px;
      }

      .contact {
          display: none;
      }

      .connect {
          display: none;
      }

      .usefullinks{
          display: none;

      }

      .footimage {
          width: 300px;
      }

      .error {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

    .error1 {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

  }

@media screen and (max-width:415px) {

    div.logo {
        width: 920px;
        height: 400px;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }

    .logo-top {
        width: 800px;
    }

    .content {
        width: 100%;
       height: 100vh;
        padding: 0;

    }

    .inner-body {
        background-image: url(image/book2.png);
        height: 100%;
        border-style: solid;
        margin-top: 15px;
        margin-bottom: 15px;
        width: 920px;
        position: relative;
        align-items:center;

    }

    div.navi {
        width: 920px;
        font-size: 28px;
        padding-bottom: 90px;
    }

    .header {
        left: 50px;
    }

    .para {
        width: 680px;
        display: block;
        left: 80px;
        font-size: 35px;
        padding: 30px;
        top: 10px;
        align-items: center;
    }

    form {
        width: 700px;
        left: 80px;
        font-size: 30px;
        border-style: solid;

    }

    .field {
        width: 400px;
        font-size: 30px;
    }

    .field2 {
        width: 600px;
        font-size: 30px;
    }
    .field3 {
        width: 300px;
        height: 30px;
        border-radius: 10px;
        margin-top: 10px;
        background-color: rgb(193, 211, 205);
        font-size: 25px;
        cursor: pointer;
    }

    .field4 {
        width: 300px;
        font-size: 30px;
        cursor: pointer;
    }
    .navi2 {

        display: none;
    }
    footer {
        display: none;

        padding: 0;
        list-style: none;
        background-color: rgb(126, 226, 230);
        font-size: 20px;
      }

      .contact {
          display: none;
      }

      .connect {
          display: none;
      }

      .usefullinks{
          display: none;

      }

      .footimage {
          width: 300px;
      }

      .error {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

    .error1 {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports2.css">
    <script src="log-it-reports.js"></script>
    <title>Document</title>
</head>

<body>
    <div class= "content">
        <div class="logo">
        <img class="logo-top" src="image/logo1.png" alt="Logo Top: WearviewAcademy Logo" >
        </div>
        <div class="navi">
            <nav>
            <p class>
                 Home |
                Academics |
                Services |
                Covid-19 |
                Students & Parents |
                Transcripts  |
                Staff |
                Career |
                Events |
                Student Account |
        </p>
    </nav>
        </div>
       <div class="inner-body">
           <div class = "header" >
            <h1>Steps For IT-Issues Logging:</h1>
           </div>

       <div class="para">
           <p class="para2">Please read the following instructions before submitting a report:</p>
           <ol>
               <li>Fill out all of the fields.</li>
               <li>Use a valid email.</li>
               <li>Select a problem type.</li>
               <li>Be as detailed as possible so that the IT staff could address the issue properly (100 characters minumum).</li>
               <li>Normally most issues get addressed within 2 hours, please be patient.</li>
           </ol>
       </div>
       <div class="form1">
        <form  method="GET" onsubmit=" return formValidations() " action="log-it-reports.html">
          <div class="error1" id= "errorMsg"></div>
          <div>
          <label for="subject"><b>Subject:</label>
          <input  class="field" id="subject" type="text" placeholder="Subject Title"  >
          </div><br>
          <div class="error" id= "errorMsg2"></div>
          <div>
          <label for="email"><b>Email:</label>
          <input class="field" id="email" type="email" placeholder="staff@wearview.com">
          </div><br>
          <div class="error" id= "errorMsg3"></div>
          <div>
            <select class="field4" name="techtype" id="problemtypes">
                <option value="">Problem Type</option>
                <option value="Hardware">Hardware</option>
                <option value="Software">Software</option>
                <option value="Other">Other</option>
              </select>
          </div><br>
          <div class="error" id= "errorMsg4"></div>
          <div>
          <textarea class="field2" id="description" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>
          </div>

          <div>
            <button class="field3" type="submit" class="btn">Submit</button>
            <input type="checkbox" id="notify" name="notify" value="">
            <label for="notify">Inform me by email when issue is resolved.</label>
        </div>
        </form>
       </div>
       <div class="navi2">
           <div class="userimage">
               <img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
           </div>
           <div class="user-links">
               <navi class="navi3">
                Staff Name <br><br>
                Inbox <br><br>
                Notifications <br><br>
                Files <br><br>
                Settings <br><br>
                Help  <br><br>
                QR For Mobile <br><br>
                Log Out
               </navi>
           </div>
       </div>
    </div>
       <div class="foot">
           <footer id = "footy">
           <div>
            <img class="footimage" src="image/logo1.png" alt="bottom logo- Wearview Academy"  width="400px">
           </div>
           <div class="contact">
               <h3>Contact Us</h3>
                <p class="foots"><img class="emaillogo" src="image/email (2).png" alt="logo-email"> :wearview_academy@wearview.com</p>
              <p class="foots"><img class="telelogo" src="image/tele.png" alt="logo-telephone"> :+2499100000000</p>
           </div>
           <div class="usefullinks">
            <h3>Useful Links</h3>
            <ul>
                <li>Career</li>
                <li>Report A Website Issue</li>
                <li>About Us</li>
                <li>Covid-19</li>
                <li>Events</li>
            </ul>
           </div>
           <div class="connect">
            <h3>Connect With Us </h3><br>
                <img class="fb" src="image/fb.png" alt = "logo-social media-Facebook" />
                <img class="tw" src="image/tw.jpg" alt = "logo-social media -Twitter" />
                <img class="yt" src="image/you.png" alt = "logo-social media-Youtube" />
                <img class="ln" src="image/linkd.png" alt = "logo-social-media-LinkedIn" />
           </div>
           </footer>
       </div>
    </div>
</body>
</html></code>```

, you would notice it takes effect on the media query as well.

答:
Have you tried using the !important rule to the properties?

Like:

div.logo {
        width: 900px!important;
        height: 400px!important;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }
```

Also try to look more into @MediaQueries

Body:
My media query which i set for (max-width 915px) changes the height of the css which i created for desktop even though the query comes after the original css, and when i change something in the original css, it reflects on the media query even though the values are different and should be overwritten.
please check the "form element" which created and try tinker the top and left positioning properties in the original part of css

body{
    font-family: Verdana, Geneva, Tahoma, sans-serif;

}

.content {
    width: 1400px;
    margin: auto;

    padding: 10px;
}

p {
    color: rgb(97, 87, 226);
}

p.foots {
    color:black ;

}

.para2 {
    color: black;
}

.logo {
    width: 100%;
    height: 300px;
    background-color: rgb(147, 235, 238);
}

div.navi {

    background-color: rgb(228, 226, 217);
    width: 100%;
    height: 50px;
    margin-top: 15px;
    text-align: center;
    font-size: 20px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    padding-top: 1px;
    margin-bottom: 1px;
}

p.nav {
    position: relative;
    bottom: 5px;
    border-style: solid;
}

a:link {
    text-decoration: none;
    color: rgb(97, 87, 226);
}

.navi3:link {
    color: rgb(7, 7, 7);
}

.logo-top {
    margin-left: 20px;
    width: 600px;
}

/* inner body styling */

div.inner-body {
    background-image: url(image/bk.png);
    margin-bottom: 20px;
    border-style: solid;
    margin-top: 20px;
    height: 1800px;
  position: relative;
}

.header {

    width: 700px;
    position: relative;
    left: 338px;
    font-size: 30px;
    top:100px;

}

.para {

    width: 800px;
    position: relative;
    left:345px;
    top:200px;
    background-color: rgb(206, 200, 180);
    font-size: 25px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 20px;
    padding: 5px;
}

form {
    padding: 20px;
    border-radius: 20px;
    width: 725px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    position: relative;
    left:350px;
    top:225px;
    background-color: rgb(206, 200, 180);
}

.field {
    width: 300px;
    font-size: 18px;

}

.field2 {
    width: 600px;
    font-size: 18px;
}
.field3 {
    width: 300px;
    height: 30px;
    border-radius: 10px;
    margin-top: 10px;
    background-color: rgb(193, 211, 205);

    cursor: pointer;
}

.field4 {
    width: 300px;
    font-size: 18px;
    cursor: pointer;
}

.error {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.error1 {
    color: red;
    font-size: 15px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.navi2 {

    width: fit-content;
    width: 300px;
    height: 600px;
    position:absolute;

    background-color: cadetblue;
    font-size: 20px;
    border-radius: 20px;
    top:228px;
}

.user-links {
    position: relative;
    left:20px;
    bottom:30px;
}

.user-links:link{
    color: brown;
}

.userlogo {
    width: 200px;
    border-radius: 100px;
    position: relative;
    left: 50px;
    bottom: 100px;
}

/* footer styling */

.emaillogo, .telelogo {
    width: 20px;
}

footer{
    background-color: rgb(126, 226, 230);
    height: 200px;
}

.footimage {
    width: 400px;

    margin: 0;
}
div.contact{
    width: fit-content;
    height: 200px;

    position: relative;
    left: 400px;
    bottom: 185px;
    font-size: 12px;

}

.usefullinks {
    width: fit-content;
    font-size: 12px;
    position: relative;
    left:750px;
    bottom:400px;

}

.connect {
    width: fit-content;
    position: relative;
    left: 1100px ;
    bottom: 524px;
    font-size: 12px;
}

.fb, .tw, .yt, .ln {
    width: 50px;
    border-radius: 10px;

}

/* Media Queries */

@media screen and (max-width:915px) {

    div.logo {
        width: 900px;
        height: 400px;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }

    .logo-top {
        width: 800px;
    }

    .content {
        width: 100%;
       height: 100vh;
        padding: 0;

    }

    .inner-body {
        background-image: url(image/book2.png);
        height: 1800px;
        border-style: solid;
        margin-top: 15px;
        margin-bottom: 15px;
        width: 900px;
        position: relative;

    }

    div.navi {
        width: 900px;
        font-size: 28px;
        padding-bottom: 90px;
    }

    .header {
        left: 50px;
    }

    .para {
        width: 680px;
        display: block;
        left: 80px;
        font-size: 35px;
        padding: 30px;
        top: 10px;
        align-items: center;
    }

    form {
        width: 700px;
        left: 80px;
        font-size: 30px;
        border-style: solid;

    }

    .field {
        width: 400px;
        font-size: 30px;
    }

    .field2 {
        width: 600px;
        font-size: 30px;
    }
    .field3 {
        width: 300px;
        height: 30px;
        border-radius: 10px;
        margin-top: 10px;
        background-color: rgb(193, 211, 205);
        font-size: 25px;
        cursor: pointer;
    }

    .field4 {
        width: 300px;
        font-size: 30px;
        cursor: pointer;
    }
    .navi2 {

        display: none;
    }
    footer {
        display: none;

        padding: 0;
        list-style: none;
        background-color: rgb(126, 226, 230);
        font-size: 20px;
      }

      .contact {
          display: none;
      }

      .connect {
          display: none;
      }

      .usefullinks{
          display: none;

      }

      .footimage {
          width: 300px;
      }

      .error {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

    .error1 {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

  }

@media screen and (max-width:415px) {

    div.logo {
        width: 920px;
        height: 400px;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }

    .logo-top {
        width: 800px;
    }

    .content {
        width: 100%;
       height: 100vh;
        padding: 0;

    }

    .inner-body {
        background-image: url(image/book2.png);
        height: 100%;
        border-style: solid;
        margin-top: 15px;
        margin-bottom: 15px;
        width: 920px;
        position: relative;
        align-items:center;

    }

    div.navi {
        width: 920px;
        font-size: 28px;
        padding-bottom: 90px;
    }

    .header {
        left: 50px;
    }

    .para {
        width: 680px;
        display: block;
        left: 80px;
        font-size: 35px;
        padding: 30px;
        top: 10px;
        align-items: center;
    }

    form {
        width: 700px;
        left: 80px;
        font-size: 30px;
        border-style: solid;

    }

    .field {
        width: 400px;
        font-size: 30px;
    }

    .field2 {
        width: 600px;
        font-size: 30px;
    }
    .field3 {
        width: 300px;
        height: 30px;
        border-radius: 10px;
        margin-top: 10px;
        background-color: rgb(193, 211, 205);
        font-size: 25px;
        cursor: pointer;
    }

    .field4 {
        width: 300px;
        font-size: 30px;
        cursor: pointer;
    }
    .navi2 {

        display: none;
    }
    footer {
        display: none;

        padding: 0;
        list-style: none;
        background-color: rgb(126, 226, 230);
        font-size: 20px;
      }

      .contact {
          display: none;
      }

      .connect {
          display: none;
      }

      .usefullinks{
          display: none;

      }

      .footimage {
          width: 300px;
      }

      .error {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

    .error1 {
        color: red;
        font-size: 20px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
    }

  }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="log-it-reports2.css">

    <title>Document</title>

                 Home |
                Academics |
                Services |
                Covid-19 |
                Students & Parents |
                Transcripts  |
                Staff |
                Career |
                Events |
                Student Account |

Steps For IT-Issues Logging:

Please read the following instructions before submitting a report:

Fill out all of the fields.

Use a valid email.

Select a problem type.

Be as detailed as possible so that the IT staff could address the issue properly (100 characters minumum).

Normally most issues get addressed within 2 hours, please be patient.

        <form  method="GET" onsubmit=" return formValidations() " action="log-it-reports.html">

          Subject:
          <input  class="field" id="subject" type="text" placeholder="Subject Title"  >

          Email:
          <input class="field" id="email" type="email" placeholder="staff@wearview.com">

            <select class="field4" name="techtype" id="problemtypes">
                <option value="">Problem Type</option>
                <option value="Hardware">Hardware</option>
                <option value="Software">Software</option>
                <option value="Other">Other</option>
              </select>

          <textarea class="field2" id="description" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>

            <button class="field3" type="submit" class="btn">Submit</button>
            <input type="checkbox" id="notify" name="notify" value="">
            Inform me by email when issue is resolved.

        </form>

               <navi class="navi3">
                Staff Name

                Inbox

                Notifications

                Files

                Settings

                Help

                QR For Mobile

                Log Out
               </navi>

Contact Us

 :wearview_academy@wearview.com

 :+2499100000000

Useful Links

Career

Report A Website Issue

About Us

Covid-19

Events

Connect With Us

, you would notice it takes effect on the media query as well.

Body:
Have you tried using the !important rule to the properties?

Like:

div.logo {
        width: 900px!important;
        height: 400px!important;
        background-color: rgb(147, 235, 238);
        -ms-flex-item-align: center;
    }

Also try to look more into @MediaQueries


问:
License key comparison for new and old model (key not matches)
I have 2 xml files (old and new license). One has an Enable field and the other does not. I have method to check  is license is valid. I check if the key of the delivered license is the same as the one calculated. Because the old license does not have Enabled field, the old license key never matches (because the model now has an Enabled field). I don't know how to solve this problem. The new license must have the field enabled.
to be honest I don't even know what to google...

I am using MD5.

Model (new)

```<code>public string Name {get;set;}
public bool isEnabled {get; set;}
public DateTime Date {get;set;}
</code>```

答:
You can make the Enable field as nullable. And change the logic of the check method so that if Enable is null, then do not use it. To do this, provide two ways - the old and the new checking method.</p>
```<code>class License
{
   [XmlElement("Enable")]
   bool? Enable { get; set; } = null; // '?' means that value can be true, false or null.
   // ...
}

bool Check(License license)
{
   if (license.Enable == null)
   {
      // Old checking method...
   }
   else
   {
      bool enable = (bool) license.Enable;
      // New checking method...
   }
}
</code>```

Body:
I have 2 xml files (old and new license). One has an Enable field and the other does not. I have method to check  is license is valid. I check if the key of the delivered license is the same as the one calculated. Because the old license does not have Enabled field, the old license key never matches (because the model now has an Enabled field). I don't know how to solve this problem. The new license must have the field enabled.
to be honest I don't even know what to google...

I am using MD5.

Model (new)

public string Name {get;set;}
public bool isEnabled {get; set;}
public DateTime Date {get;set;}

Body:
You can make the Enable field as nullable. And change the logic of the check method so that if Enable is null, then do not use it. To do this, provide two ways - the old and the new checking method.

class License
{
   [XmlElement("Enable")]
   bool? Enable { get; set; } = null; // '?' means that value can be true, false or null.
   // ...
}

bool Check(License license)
{
   if (license.Enable == null)
   {
      // Old checking method...
   }
   else
   {
      bool enable = (bool) license.Enable;
      // New checking method...
   }
}


问:
Redirect to last browser history location in React
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

```<code>// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page
</code>```

And here is ProtectedRoute.js

```<code>import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}
</code>```

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

```<code> const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);
</code>```

答:
In simpler terms, you will have to make the browser remember that the user is now authenticated. That can be simply achieved by adding a specific token or isValid = true to the session storage and then you will have to use the value from session storage as your reference.

Updating user status in the state cannot persist it on reload. You would have to use persistor then. However, the easier way is to update session storage.

You can create a new JS file, say session.js and create the following functions:

```<code>export const setToken = (value) => {
    sessionStorage.setItem('token', value)
}

export const getToken = () => {
    return sessionStorage.getItem('token') || null
}

export const removeToken = () => {
    sessionStorage.removeItem('token')
}
</code>```

You can call setToken(true) on successful authentication and remove the token removeToken() on log out. You can then call getToken() to check your user's authentication in your if statement. I hope it helps!

Body:
I am working on my personal React project.
The React app has a login page. After successfully logging in, the user is redirected to homepage i.e. on path / . And if the user again tries to navigate to login page i.e.  path
/login , then the user will be redirected back to homepage

The app also has protected route on path /profile which is accessible only if the user is authenticated.

But the problem is, when the user navigates to protected route and then refreshes the page, it is redirecting to the  homepage.
How can I make it redirect back to the same protected route from where the user had refreshed?

Here is Login.js

// Login.js
      if (isUserLoggedIn) {
        return <Redirect to="/" />;
      }
      // else render login page

And here is ProtectedRoute.js

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Redirect, Route } from "react-router";

export default function ProtectedRoute({ component: Component, ...rest }) {

  const { isUserLoggedIn } = useSelector((state) => state.common);

  return (
    <Route
      {...rest}
      render={(props) =>
        !isUserLoggedIn ? <Redirect to="/login" /> : <Component {...props} />
      }
    />
  );
}

And this is how I'm getting the value of isUserLoggedIn  from cookies and then setting it to the Redux state.

 const [authenticated] = useState(() =>
    Boolean(Number(Cookies.get("isUserLoggedIn")))
  );
  useEffect(() => {
    if (!authenticated) {
      return dispatch({
        type: NOT_AUTHENTICATED,
      });
    } else {
      return dispatch({
        type: AUTHENTICATED,
      });
    }
  }, [authenticated]);

Body:
In simpler terms, you will have to make the browser remember that the user is now authenticated. That can be simply achieved by adding a specific token or isValid = true to the session storage and then you will have to use the value from session storage as your reference.

Updating user status in the state cannot persist it on reload. You would have to use persistor then. However, the easier way is to update session storage.

You can create a new JS file, say session.js and create the following functions:

export const setToken = (value) => {
    sessionStorage.setItem('token', value)
}

export const getToken = () => {
    return sessionStorage.getItem('token') || null
}

export const removeToken = () => {
    sessionStorage.removeItem('token')
}

You can call setToken(true) on successful authentication and remove the token removeToken() on log out. You can then call getToken() to check your user's authentication in your if statement. I hope it helps!


问:
Get CSS content from a rule using regex
For example, I have a stylesheet:

```<code>.foo {
 background-color: #fff;
}

.bar {
 font-size: 20px;
}
</code>```

What regex could I use to get background-color: #fff; from .foo?

UPD: There could be anything in .foo so no need to hard code background-color

答:
Most of regex characters are string literals, and a valid string is also a valid regex if it does not include meta characters, so you can use this:

If you want to get any value for the background color you can use this:

If you want to get the background color only for .foo you can use a positive lookbehind, like this:

If you want to match any css rule with any value that comes before a .foo + space + { + newline + space you can use something like this:

Just note, that this regex is specifically designed for your usecase and might need to be generalized for be able to fit in with more examples.

Title: Get CSS content from a rule using regex

Body:
For example, I have a stylesheet:

.foo {
 background-color: #fff;
}

.bar {
 font-size: 20px;
}

What regex could I use to get background-color: #fff; from .foo?

UPD: There could be anything in .foo so no need to hard code background-color


问:
Click "Exit" button through our Application It need to go Phones's Home page & remove SharedPreferences also
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

```<code>  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}
</code>```

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance

答:
try this,</p>

```<code>Intent myIntent = new Intent(view.getContext(), firstActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();
</code>```

Body:
My question is when I click the "Exit" button through our application It need to go to Phones's Home screen.I have Tried like this

  public void onExitAction(View botton){
          // finish();
          // super.finish();
           // System.runFinalizersOnExit(true)

            //android.os.Process.killProcess(android.os.Process.myPid());

     System.exit(0);

}

Not working.

When I put finish() its closing that particular activity & its go to previous screen.

seconds one is When we exit the system need to remove SharedPreferences also?

Please help me on this...

Thanks in advance

Body:
try this,

Intent myIntent = new Intent(view.getContext(), firstActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();


问:
In ggplot2, how to add a white hole in the middle of the pie chart
In ggplot2, how to add a white hole in the middle of the pie chart?
Please refer to below code for current plot (the left plot) . Thanks!

```<code>library(tidyverse)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))

pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 coord_polar(theta = 'y')+
  theme_void()
</code>```

答:
Just widen the limits of your x axis (it's easier to do this if you don't convert the year into a factor):

pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') +
  lims(x = c(2019, 2022)) +
  theme_void()
```
<p><img src="https://i.stack.imgur.com/EEBOO.png" alt="enter image description here" /></p>
<p>You can control the size of the white hole by changing 2019 in the above code. The earlier the year, the larger the hole:</p>
<pre class="lang-r prettyprint-override"><code>pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') +
  lims(x = c(2017, 2022)) +
  theme_void()
</code>```

Body:
In ggplot2, how to add a white hole in the middle of the pie chart?
Please refer to below code for current plot (the left plot) . Thanks!

library(tidyverse)
pie_data <- data.frame(category=c('A','B','C','A','B','C'),
                       year=c(2020,2020,2020,2021,2021,2021),
                       sales=c(40,30,20,10,15,10))

pie_data %>% ggplot(aes(x=factor(year),y=sales,fill=category))+
  geom_col(position='fill',width=1,color='white')+
 coord_polar(theta = 'y')+
  theme_void()

Body:
Just widen the limits of your x axis (it's easier to do this if you don't convert the year into a factor):

pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') +
  lims(x = c(2019, 2022)) +
  theme_void()

You can control the size of the white hole by changing 2019 in the above code. The earlier the year, the larger the hole:

pie_data %>% ggplot(aes(x = year, y = sales, fill = category))+
  geom_col(position = 'fill', width = 1, color = 'white') +
  coord_polar(theta = 'y') +
  lims(x = c(2017, 2022)) +
  theme_void()


问:
How to read json file with node.js using P5.js
I just want the word "flower" to show up

I have test terminal for Node and using the preload() and loadJSON(), it work just fine but the word flower not show up, meaning the "js file" does not run on "json file", but the terminal said on console it work for node(meaning it read the json file on terminal)

How do I debug this?

The below is what I use for learning and working on this project
>

The Coding Train

10.2: What is JSON? Part I - p5.js Tutorial
https://www.youtube.com/watch?v=_NFkzw6oFtQ

8.5: Saving Data to JSON File with Node.js - Programming with Text
https://www.youtube.com/watch?v=6iZiqQZBQJY

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

```
</div>
</div>
</p>
<p><strong>infoJSON5.js</strong></p>

<pre class="lang-js prettyprint-override"><code>//var flower;

//function preload() {
//    flower = loadJSON("Data3.json")
    var fs = require('fs');
    var data = fs.readFileSync('Data3.json');
    var flower = JSON.parse(data);
    console.log(flower);
//}
    //Test Terminal
  /*
  node infoJSON5.js
  */

function setup() {
    createCanvas(400, 400);
}

  function draw() {
    background(0);

    fill(flower.r, flower.g, flower.b);
    text(flower.name, 10, 50);
  }

</code>```

Data3.json

```<code>    {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}
</code>```

答:
```<code>const myJSON =  {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}
const myObj = JSON.parse(myJSON);

function setup() {
  createCanvas(400, 400);
}

function draw() {
   background(0);

    fill(myJSON.r, myJSON.g, myJSON.b);
    text(myJSON.name, 10, 50);
}
</code>```

Body:
I just want the word "flower" to show up

I have test terminal for Node and using the preload() and loadJSON(), it work just fine but the word flower not show up, meaning the "js file" does not run on "json file", but the terminal said on console it work for node(meaning it read the json file on terminal)

How do I debug this?

The below is what I use for learning and working on this project
>

The Coding Train

10.2: What is JSON? Part I - p5.js Tutorial
https://www.youtube.com/watch?v=_NFkzw6oFtQ

8.5: Saving Data to JSON File with Node.js - Programming with Text
https://www.youtube.com/watch?v=6iZiqQZBQJY

index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

infoJSON5.js

//var flower;

//function preload() {
//    flower = loadJSON("Data3.json")
    var fs = require('fs');
    var data = fs.readFileSync('Data3.json');
    var flower = JSON.parse(data);
    console.log(flower);
//}
    //Test Terminal
  /*
  node infoJSON5.js
  */

function setup() {
    createCanvas(400, 400);
}

  function draw() {
    background(0);

    fill(flower.r, flower.g, flower.b);
    text(flower.name, 10, 50);
  }

Data3.json

    {
"name":"sunflower",
"r":255,
"g":200,
"b":0
}


问:
How to out of while and for loop combined
I am trying to write a code that is capturing number 3. using while loop as the condition, so that the for statement will be the evaluation condition of $x, of the while loop statement, and by the same time, using if statement to evaluate the value of $x=3 and so it can echo 'three..'; . please enlighten me. thank you

```<code><?php
$x = 0;
$y = 5;

while ($x <= $y) {
    for ($z = 0; $z < 3; $z++) {
        if ($x = 3) {
            echo 'three..' . "\n";
        }
    }
    $y++;
}
</code>```

答:
In while loop, you should increment x variable.
If you increment y variable, it will always "true". So it will be endless loop.

```<code><?php
 $x = 0;
 $y = 5;

while ($x <= $y) {
   // code
    $x++;
}
</code>```

Body:
I am trying to write a code that is capturing number 3. using while loop as the condition, so that the for statement will be the evaluation condition of $x, of the while loop statement, and by the same time, using if statement to evaluate the value of $x=3 and so it can echo 'three..'; . please enlighten me. thank you

<?php
$x = 0;
$y = 5;

while ($x <= $y) {
    for ($z = 0; $z < 3; $z++) {
        if ($x = 3) {
            echo 'three..' . "\n";
        }
    }
    $y++;
}

Body:
In while loop, you should increment x variable.
If you increment y variable, it will always "true". So it will be endless loop.

<?php
 $x = 0;
 $y = 5;

while ($x <= $y) {
   // code
    $x++;
}


问:
Weird behaviour of loops in python
So I was trying to do some basic stuff list stuff in a different way, and I came across weird behaviour in this code. I'm not sure if its a compiler/machine dependent result and I can't even google this because I'm just so lost.

Edit: In response to some people, I get that my code is incorrect in its semantics, but the behaviour of the code after the mistake is what I wanted to understand. Thanks for the corrections though!

Here is the code:

```<code>import random

L = (int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = (int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))

common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)
</code>```

From my limited understanding, line 3 and 5 should have just resulted in L and L1 having the last entered integer stored in them, but when I execute the program it just flits between line 3 and 5. Furthermore, if I try to print L and L1 it just prints its object type (genexpr) and location in memory, before the prompts for inputs. Why is the code behaving that way?

答:
I think what you want to do is to use a list comprehension with square brackets instead of curved brackets.

```<code>import random

L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)
</code>```

If you instead want to do a tuple comprehension, you could do it as follows:

```<code>import random

L = tuple(int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = tuple(int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)
</code>```

Title: Weird behaviour of loops in python

Body:
So I was trying to do some basic stuff list stuff in a different way, and I came across weird behaviour in this code. I'm not sure if its a compiler/machine dependent result and I can't even google this because I'm just so lost.

Edit: In response to some people, I get that my code is incorrect in its semantics, but the behaviour of the code after the mistake is what I wanted to understand. Thanks for the corrections though!

Here is the code:

import random

L = (int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = (int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))

common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)

From my limited understanding, line 3 and 5 should have just resulted in L and L1 having the last entered integer stored in them, but when I execute the program it just flits between line 3 and 5. Furthermore, if I try to print L and L1 it just prints its object type (genexpr) and location in memory, before the prompts for inputs. Why is the code behaving that way?

Body:
I think what you want to do is to use a list comprehension with square brackets instead of curved brackets.

import random

L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)

If you instead want to do a tuple comprehension, you could do it as follows:

import random

L = tuple(int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5)))
L1 = tuple(int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6)))
common = []

for i in L:
  if i in L1:
    common.append(i)

print(common)


答:
The unexpected bahavior is caused by the generator expressions, which are evaluated lazily.

This means that the values for L and L1 will be generated as needed, one value at a time.

The loop

```<code>for i in L:
</code>```

can be executed by creating a single value for L in each iteration.
This is why you will see one prompt "For List 1, enter a number: " for each iteration of the outer for loop!

However, the if statement

```<code>if i in L1:
</code>```

requires values to be created for L1 until i is found or until there are no more values to generate for L1.

Example:

```<code>>>> L1 = (x for x in (1, 2, 3, 4))
>>> 3 in L1
True
>>> next(L1)
4
>>> next(L1)
Traceback (most recent call last):
[...]
StopIteration
</code>```

To avoid the lazy evaluation, use lists instead of generator expressions, i.e.

```<code>L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]
</code>```

Title: Weird behaviour of loops in python

Body:
The unexpected bahavior is caused by the generator expressions, which are evaluated lazily.

This means that the values for L and L1 will be generated as needed, one value at a time.

The loop

for i in L:

can be executed by creating a single value for L in each iteration.
This is why you will see one prompt "For List 1, enter a number: " for each iteration of the outer for loop!

However, the if statement

if i in L1:

requires values to be created for L1 until i is found or until there are no more values to generate for L1.

Example:

>>> L1 = (x for x in (1, 2, 3, 4))
>>> 3 in L1
True
>>> next(L1)
4
>>> next(L1)
Traceback (most recent call last):
[...]
StopIteration

To avoid the lazy evaluation, use lists instead of generator expressions, i.e.

L = [int(input("For List 1, enter a number: ")) for i in range(random.randint(2, 5))]
L1 = [int(input("For List 2, enter a number: ")) for i in range(random.randint(2, 6))]


问:
map() function throwing null error for response in Angular 6
I am trying to implement Angular 2 code in Angular 6 app and below is the code I am trying to implement.

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

In the below code, I am getting error as null for json

private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
        .map(response => response.json())
        .map(response => (<GridDataResult>{
            data: response.EmployeeList,
            total: response.Count
        }));

}
```
<p>The error is as below when I run the app</p>
<p><img src="https://i.stack.imgur.com/kR7le.jpg" alt="Json Error" /></p>
<p>Could you please tell me why it is throwing these 2 errors</p>
<p>Here is the subscription for the above code snippet.</p>
```public query(state): void {
    this.getEmployee(state)
        .subscribe(x =>super.next(x));
}
```
<p>In the <code>C#</code> code, I am return the <code>data</code> and <code>total</code> as below...</p>
```if (resultList.Count > 0)
{
    var result = new
    {
        data = resultList.ToArray(),
        total= resultList[0].TotalRecords
    };
    var jsonData = JsonConvert.SerializeObject(result);
    return jsonData;
}
```

I get the below error when I implemented as you suggested @StepUp

EDIT

It is not able to recognize the data we get from dataJson as mentioned in the Answer because it is a constant. Should we need to create a mapping class in Angular side?

答:
There is no need to call .json method. In addition, it is possible to use  pipe method to compose operators. The code can look like this:

```<code>return this.http
    .get(this.BASE_URL, { search: params })
        pipe(
            map(response => (<GridDataResult>{
               data: response.EmployeeList,
               total: response.Count
            })), catchError( error => {
            return throwError( 'Something went wrong!' )
       });
    )
</code>```

If you want to map items from array, then it is necessary to call map method of array:

```<code>mapToPerson(): Observable<Address[]> {
    this.getPersons
        .pipe(
            map((persons: Person[]) => persons.map(person =>
               person.address)))
        )
}
</code>```

UPDATE:

It is necessary to understand why it throws error. So we an debug and find the problem. Let's try to simplify your code:

```<code>private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
}
</code>```

and then see in console what you've got in .subscribe method:

```<code>public query(state): void {
    this.getEmployee(state)
        .subscribe(yourResponse => console.log(yourResponse ));
}
</code>```

After error will be figured out, you can add code from the reply.

Body:
I am trying to implement Angular 2 code in Angular 6 app and below is the code I am trying to implement.

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

In the below code, I am getting error as null for json

private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
        .map(response => response.json())
        .map(response => (<GridDataResult>{
            data: response.EmployeeList,
            total: response.Count
        }));

}

The error is as below when I run the app

Could you please tell me why it is throwing these 2 errors

Here is the subscription for the above code snippet.

public query(state): void {
    this.getEmployee(state)
        .subscribe(x =>super.next(x));
}

In the C# code, I am return the data and total as below...

if (resultList.Count > 0)
{
    var result = new
    {
        data = resultList.ToArray(),
        total= resultList[0].TotalRecords
    };
    var jsonData = JsonConvert.SerializeObject(result);
    return jsonData;
}

I get the below error when I implemented as you suggested @StepUp

EDIT

It is not able to recognize the data we get from dataJson as mentioned in the Answer because it is a constant. Should we need to create a mapping class in Angular side?

Body:
There is no need to call .json method. In addition, it is possible to use  pipe method to compose operators. The code can look like this:

return this.http
    .get(this.BASE_URL, { search: params })
        pipe(
            map(response => (<GridDataResult>{
               data: response.EmployeeList,
               total: response.Count
            })), catchError( error => {
            return throwError( 'Something went wrong!' )
       });
    )

If you want to map items from array, then it is necessary to call map method of array:

mapToPerson(): Observable<Address[]> {
    this.getPersons
        .pipe(
            map((persons: Person[]) => persons.map(person =>
               person.address)))
        )
}

UPDATE:

It is necessary to understand why it throws error. So we an debug and find the problem. Let's try to simplify your code:

private getEmployee(state: any): Observable<GridDataResult>{
    let params = new URLSearchParams();
    params.set('Skip', state.skip);
    params.set('Take', state.take)
    return this.http
        .get(this.BASE_URL, { search: params })
}

and then see in console what you've got in .subscribe method:

public query(state): void {
    this.getEmployee(state)
        .subscribe(yourResponse => console.log(yourResponse ));
}

After error will be figured out, you can add code from the reply.


问:
R plotly: Customize Hover (Info and Text)
I would like to customize what I see in plotly when I hover on a bar.

Please have a look at the reprex at the end of the post.
I had a look at

How to set different text and hoverinfo text

https://community.rstudio.com/t/changing-hovertext-in-plotly/71736

But I must be making some mistake.
What I would like is to see only the variables "macro_sector" and "amount" when I hover on a bar and no static text on the bar at all.
How can I achieve that? Many thanks

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(plotly)
#> Loading required package: ggplot2
#>
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#>
#>     last_plot
#> The following object is masked from 'package:stats':
#>
#>     filter
#> The following object is masked from 'package:graphics':
#>
#>     layout

df <- structure(list(macro_sector = c("U Activities of extraterritorial organisations and bodies",
"T Activities of households as employers; u0ndifferentiated goods- and services-producing activities of households for own use",
"P Education", "O Public administration and defence; compulsory social security",
"K Financial and insurance activities", "S Other service activities",
"A Agriculture, forestry and fishing", "L Real estate activities",
"Q Human health and social work activities", "B Mining and quarrying ",
"E Water supply; sewerage, waste management and remediation activities",
"R Arts, entertainment and recreation", "F Construction", "I Accommodation and food service activities",
"M Professional, scientific and technical activities", "J Information and communication",
"N Administrative and support service activities", "G Wholesale and retail trade; repair of motor vehicles and motorcycles",
"D Electricity, gas, steam and air conditioning supply", "H Transportation and storage",
"C Manufacturing"), amount = c(2.2935, 17.6690005, 204.47243683,
347.24800021, 400.12333973, 613.6673475, 657.3337123, 672.74723757,
736.05549391, 828.06106689, 961.82905534, 1538.40117934, 1918.77325865,
2397.02875187, 3941.39973575, 4735.36088945, 5025.39834121, 5913.94010435,
10267.76691901, 12407.11032805, 35782.07991161), macro_sector1 = structure(1:21, .Label = c("U",
"T", "P", "O", "K", "S", "A", "L", "Q", "B", "E", "R", "F", "I",
"M", "J", "N", "G", "D", "H", "C"), class = "factor")), class = c("tbl_df",
                                                                  "tbl", "data.frame"), row.names = c(NA, -21L)) %>%
    mutate(amount=round(amount, 2))

       fig <-  plot_ly(df,
                       x = ~amount, y = ~macro_sector1,
                       type = 'bar' ,
                       text= ~paste0(macro_sector, "
", amount),
                       hoverinfo= text ## ,
                       ## hovertext = text
                       )
```

Created on 2022-02-08 by the reprex package (v2.0.1)

答:
The hoverinfo parameter "text" needs to be quoted:

```<code>library(dplyr)
library(plotly)

DF <- structure(list(macro_sector = c("U Activities of extraterritorial
                     organisations and bodies", "T Activities of households as employers;
                     u0ndifferentiated goods- and services-producing activities of households for
                     own use", "P Education", "O Public administration and defence; compulsory
                     social security", "K Financial and insurance activities", "S Other service
                     activities", "A Agriculture, forestry and fishing", "L Real estate
                     activities", "Q Human health and social work activities", "B Mining and
                     quarrying ", "E Water supply; sewerage, waste management and remediation
                     activities", "R Arts, entertainment and recreation", "F Construction", "I
                     Accommodation and food service activities", "M Professional, scientific and
                     technical activities", "J Information and communication", "N Administrative
                     and support service activities", "G Wholesale and retail trade; repair of
                     motor vehicles and motorcycles", "D Electricity, gas, steam and air
                     conditioning supply", "H Transportation and storage", "C Manufacturing"),
                     amount = c(2.2935, 17.6690005, 204.47243683, 347.24800021, 400.12333973,
                     613.6673475, 657.3337123, 672.74723757, 736.05549391, 828.06106689,
                     961.82905534, 1538.40117934, 1918.77325865, 2397.02875187, 3941.39973575,
                     4735.36088945, 5025.39834121, 5913.94010435, 10267.76691901, 12407.11032805,
                     35782.07991161), macro_sector1 = structure(1:21, .Label = c("U", "T", "P",
                     "O", "K", "S", "A", "L", "Q", "B", "E", "R", "F", "I", "M", "J", "N", "G",
                     "D", "H", "C"), class = "factor")), class = c("tbl_df", "tbl", "data.frame"),
                     row.names = c(NA, -21L)) %>% mutate(amount=round(amount, 2))

fig <-  plot_ly(DF,
                x = ~ amount,
                y = ~ macro_sector1,
                type = 'bar',
                hovertext = ~ paste0(macro_sector, "<br>", amount),
                hoverinfo = "text")
fig
</code>```

From the docs:

text:

Sets text elements associated with each (x,y) pair. If a single
string, the same string appears over all the data points. If an array
of string, the items are mapped in order to the this trace's (x,y)
coordinates. If trace hoverinfo contains a "text" flag and
"hovertext" is not set, these elements will be seen in the hover
labels.

hovertext:

Sets hover text elements associated with each (x,y) pair. If a single
string, the same string appears over all the data points. If an array
of string, the items are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace hoverinfo must contain a "text" flag.

Body:
I would like to customize what I see in plotly when I hover on a bar.

Please have a look at the reprex at the end of the post.
I had a look at

How to set different text and hoverinfo text

https://community.rstudio.com/t/changing-hovertext-in-plotly/71736

But I must be making some mistake.
What I would like is to see only the variables "macro_sector" and "amount" when I hover on a bar and no static text on the bar at all.
How can I achieve that? Many thanks

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(plotly)
#> Loading required package: ggplot2
#>
#> Attaching package: 'plotly'
#> The following object is masked from 'package:ggplot2':
#>
#>     last_plot
#> The following object is masked from 'package:stats':
#>
#>     filter
#> The following object is masked from 'package:graphics':
#>
#>     layout

df <- structure(list(macro_sector = c("U Activities of extraterritorial organisations and bodies",
"T Activities of households as employers; u0ndifferentiated goods- and services-producing activities of households for own use",
"P Education", "O Public administration and defence; compulsory social security",
"K Financial and insurance activities", "S Other service activities",
"A Agriculture, forestry and fishing", "L Real estate activities",
"Q Human health and social work activities", "B Mining and quarrying ",
"E Water supply; sewerage, waste management and remediation activities",
"R Arts, entertainment and recreation", "F Construction", "I Accommodation and food service activities",
"M Professional, scientific and technical activities", "J Information and communication",
"N Administrative and support service activities", "G Wholesale and retail trade; repair of motor vehicles and motorcycles",
"D Electricity, gas, steam and air conditioning supply", "H Transportation and storage",
"C Manufacturing"), amount = c(2.2935, 17.6690005, 204.47243683,
347.24800021, 400.12333973, 613.6673475, 657.3337123, 672.74723757,
736.05549391, 828.06106689, 961.82905534, 1538.40117934, 1918.77325865,
2397.02875187, 3941.39973575, 4735.36088945, 5025.39834121, 5913.94010435,
10267.76691901, 12407.11032805, 35782.07991161), macro_sector1 = structure(1:21, .Label = c("U",
"T", "P", "O", "K", "S", "A", "L", "Q", "B", "E", "R", "F", "I",
"M", "J", "N", "G", "D", "H", "C"), class = "factor")), class = c("tbl_df",
                                                                  "tbl", "data.frame"), row.names = c(NA, -21L)) %>%
    mutate(amount=round(amount, 2))

       fig <-  plot_ly(df,
                       x = ~amount, y = ~macro_sector1,
                       type = 'bar' ,
                       text= ~paste0(macro_sector, "
", amount),
                       hoverinfo= text ## ,
                       ## hovertext = text
                       )

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
The hoverinfo parameter "text" needs to be quoted:

library(dplyr)
library(plotly)

DF <- structure(list(macro_sector = c("U Activities of extraterritorial
                     organisations and bodies", "T Activities of households as employers;
                     u0ndifferentiated goods- and services-producing activities of households for
                     own use", "P Education", "O Public administration and defence; compulsory
                     social security", "K Financial and insurance activities", "S Other service
                     activities", "A Agriculture, forestry and fishing", "L Real estate
                     activities", "Q Human health and social work activities", "B Mining and
                     quarrying ", "E Water supply; sewerage, waste management and remediation
                     activities", "R Arts, entertainment and recreation", "F Construction", "I
                     Accommodation and food service activities", "M Professional, scientific and
                     technical activities", "J Information and communication", "N Administrative
                     and support service activities", "G Wholesale and retail trade; repair of
                     motor vehicles and motorcycles", "D Electricity, gas, steam and air
                     conditioning supply", "H Transportation and storage", "C Manufacturing"),
                     amount = c(2.2935, 17.6690005, 204.47243683, 347.24800021, 400.12333973,
                     613.6673475, 657.3337123, 672.74723757, 736.05549391, 828.06106689,
                     961.82905534, 1538.40117934, 1918.77325865, 2397.02875187, 3941.39973575,
                     4735.36088945, 5025.39834121, 5913.94010435, 10267.76691901, 12407.11032805,
                     35782.07991161), macro_sector1 = structure(1:21, .Label = c("U", "T", "P",
                     "O", "K", "S", "A", "L", "Q", "B", "E", "R", "F", "I", "M", "J", "N", "G",
                     "D", "H", "C"), class = "factor")), class = c("tbl_df", "tbl", "data.frame"),
                     row.names = c(NA, -21L)) %>% mutate(amount=round(amount, 2))

fig <-  plot_ly(DF,
                x = ~ amount,
                y = ~ macro_sector1,
                type = 'bar',
                hovertext = ~ paste0(macro_sector, "<br>", amount),
                hoverinfo = "text")
fig

From the docs:

text:

Sets text elements associated with each (x,y) pair. If a single
string, the same string appears over all the data points. If an array
of string, the items are mapped in order to the this trace's (x,y)
coordinates. If trace hoverinfo contains a "text" flag and
"hovertext" is not set, these elements will be seen in the hover
labels.

hovertext:

Sets hover text elements associated with each (x,y) pair. If a single
string, the same string appears over all the data points. If an array
of string, the items are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace hoverinfo must contain a "text" flag.


问:
How to Remove a frame from an HEVC bitstream?
I have an HEVC encoded bitstream (.bin and equivalent .mp4 file). I want to remove some frames from the bitstream to see how a decoder (or media player) behaves when a particular frame is lost.

enter image description here

How I can remove a frame (or a NAL unit) from the bitstream? What tools can be used?

Thanks

答:
With ffmpeg, you can use the drop option of the noise bitstream filter.

```<code>ffmpeg -i IN -c copy -bsf:v noise=drop=between(n\,20\,30) OUT
</code>```

This will drop packets #20-30 from the video stream. This bsf is codec-agnostic.

For a few codecs (H.264, H.265, MJPEG, MPEG2, VP9, AV1), you have the filter_units bsf.

e.g.

```<code>ffmpeg -i IN -c copy -bsf:v 'filter_units=remove_types=35|38-40' OUT
</code>```

The unit type values will depend on the codec. Consult the codec standard document for nal_unit_type or a similar parameter.

Body:
With ffmpeg, you can use the drop option of the noise bitstream filter.

ffmpeg -i IN -c copy -bsf:v noise=drop=between(n\,20\,30) OUT

This will drop packets #20-30 from the video stream. This bsf is codec-agnostic.

For a few codecs (H.264, H.265, MJPEG, MPEG2, VP9, AV1), you have the filter_units bsf.

e.g.

ffmpeg -i IN -c copy -bsf:v 'filter_units=remove_types=35|38-40' OUT

The unit type values will depend on the codec. Consult the codec standard document for nal_unit_type or a similar parameter.


问:
ExpressJS not showing debug messages
I am using ExpressJS and would like to display internal debug messages, like here https://expressjs.com/en/guide/debugging.html.

When I am using this command in VS Code (Windows Powershell) "`set DEBUG=express:*; node ./dist/app.js" it is starting my Node/Express Server, however it does not display any debug messages. Do I have to add something to my code so it works?

答:
I tried the same in windows command prompt and it worked there just exchanged the semicolon for an ampersand.</p>
```<code>set DEBUG=express:* & node ./dist/app.js
</code>```

Title: ExpressJS not showing debug messages

Body:
I tried the same in windows command prompt and it worked there just exchanged the semicolon for an ampersand.

set DEBUG=express:* & node ./dist/app.js


问:
error TS2554: Expected 1 arguments, but got 2. State, React
I am working on a InfiniteScroll with React and TypeScript.
When I am setting Posts state using setPosts and setting there a page using setPage I have an error Expected 1 arguments, but got 2. How can I declare in state that I am going to use two parameters and one of them is a setPage?

```<code>  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const lastItemRef = useRef(null);
  const observer = useRef<IntersectionObserver>();

  useEffect(() => {
    fetchPosts().then((res: any) => {
      setPosts([...res.posts], setPage(res.page));
    });
  }, []);

</code>```

答:
You need to pass a single object with two properties like below to setPosts

```<code>setPosts({ posts: [...res.posts], page: res.page});
</code>```

Alternatively, you need to set Posts and Page separately.

```<code>setPosts([...res.posts]);
setPage(res.page);
</code>```

Body:
I am working on a InfiniteScroll with React and TypeScript.
When I am setting Posts state using setPosts and setting there a page using setPage I have an error Expected 1 arguments, but got 2. How can I declare in state that I am going to use two parameters and one of them is a setPage?

  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const lastItemRef = useRef(null);
  const observer = useRef<IntersectionObserver>();

  useEffect(() => {
    fetchPosts().then((res: any) => {
      setPosts([...res.posts], setPage(res.page));
    });
  }, []);

Body:
You need to pass a single object with two properties like below to setPosts

setPosts({ posts: [...res.posts], page: res.page});

Alternatively, you need to set Posts and Page separately.

setPosts([...res.posts]);
setPage(res.page);


问:
Image field related problems while using in django admin
I have a following Banner class. Which is editable by admin.

```<code>class Banner(models.Model):
    name        = models.CharField(max_length = 128)
    link        = models.TextField(max_length = 450)
    image       = models.ImageField(upload_to = 'banner_images')
</code>```

There are two problems.

When saving image it is saved with original file name. I would like to change it with some unique name so that is not clashed when image with the same name is uploaded again in the specified directory.

While updating the image, the first image file must be deleted. It is not happening...

Any suggestion will be helpful. Thanks in advance.

答:
Since I was having problem related to savings of image through admin I got following solution which answers all my queries...

First I found that even though admin keeps the original file name, if the file with same name already exists, it keeps on appending a count as a suffix to prevent duplicate file name... for example, if same file is uploaded it is stored as image, image_2, image_3 etc...

Second, while changing image through admin, it was not removing the original file. For that I wrote following code in admin.py. And it does the job well...

Code:

```<code>class BannerAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        #Remove the previous file if the object is not new
        #and new file supplied.
        if obj.id != None and len(request.FILES) > 0:

            import os
            old_obj = m.Banner.objects.get(id = obj.id)
            os.remove(old_obj.image.path)
</code>```

Hope this helps you if you have got the similar problem.

Body:
I have a following Banner class. Which is editable by admin.

class Banner(models.Model):
    name        = models.CharField(max_length = 128)
    link        = models.TextField(max_length = 450)
    image       = models.ImageField(upload_to = 'banner_images')

There are two problems.

When saving image it is saved with original file name. I would like to change it with some unique name so that is not clashed when image with the same name is uploaded again in the specified directory.

While updating the image, the first image file must be deleted. It is not happening...

Any suggestion will be helpful. Thanks in advance.

Body:
Since I was having problem related to savings of image through admin I got following solution which answers all my queries...

First I found that even though admin keeps the original file name, if the file with same name already exists, it keeps on appending a count as a suffix to prevent duplicate file name... for example, if same file is uploaded it is stored as image, image_2, image_3 etc...

Second, while changing image through admin, it was not removing the original file. For that I wrote following code in admin.py. And it does the job well...

Code:

class BannerAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        #Remove the previous file if the object is not new
        #and new file supplied.
        if obj.id != None and len(request.FILES) > 0:

            import os
            old_obj = m.Banner.objects.get(id = obj.id)
            os.remove(old_obj.image.path)

Hope this helps you if you have got the similar problem.


答:
If your styles are written in the CSS file, you need to get the computed style. To do so, you can use getComputedStyle.

In this case you can get all styles, no needs to use regex.

const element = document.querySelector('.foo');
const style = getComputedStyle(element);
console.log('styles', style.padding, style.background, style);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
  background: tomato;
  padding: 1rem;
}</code>```

Text
```

Title: Get CSS content from a rule using regex

Body:
For example, I have a stylesheet:

.foo {
 background-color: #fff;
}

.bar {
 font-size: 20px;
}

What regex could I use to get background-color: #fff; from .foo?

UPD: There could be anything in .foo so no need to hard code background-color

Body:
If your styles are written in the CSS file, you need to get the computed style. To do so, you can use getComputedStyle.

In this case you can get all styles, no needs to use regex.

const element = document.querySelector('.foo');
const style = getComputedStyle(element);
console.log('styles', style.padding, style.background, style);

.foo {
  background: tomato;
  padding: 1rem;
}

<div class="foo">Text</div>


问:
Running multiple config files with Bppancestor
I need to run Bppancestor with multiple config files, I have tried different approaches but none of them worked. I have around 150 files, so doing it one by one is not an efficient solution.

The syntax to run bppancestor is the following one:

bppancestor params=config_file
```
<p>I tried doing:</p>
<pre class="lang-sh prettyprint-override"><code>bppancestor params=directory_of_config_files/*
</code>```

and using a Snakefile to try to automatize the workflow:

ARCHIVE_FILE = 'bpp_output.tar.gz'

# a single config file
CONFIG_FILE = 'config_files/{sims}.conf'

# Build the list of input files.
CONF = glob_wildcards(CONFIG_FILE).sims

# pseudo-rule that tries to build everything.
# Just add all the final outputs that you want built.
rule all:
    input: ARCHIVE_FILE

# run bppancestor
rule bpp:
    input:
        CONF,
    shell:
        'bppancestor params={input}'

# create an archive with all results
rule create_archive:
    input: CONF,
    output: ARCHIVE_FILE
    shell: 'tar -czvf {output} {input}'
```

Could someone give me advice on this?

答:
You're very close. Rule bpp should use as input a specific config file and specify concrete output (not sure if the output is a file or a folder). If I understand the syntax correctly, this link suggests that output files can be specified using output.sites.file and output.nodes.file:

rule bpp:
    input:
        CONFIG_FILE,
    output:
        sites='sites.{sims}',
        nodes='nodes.{sims}',
    shell:
        'bppancestor params={input} output.sites.file={output.sites} output.nodes.file={output.nodes}'
```
<p>Rule <code>create_archive</code> will collect all the outputs and archive them:</p>
<pre class="lang-py prettyprint-override"><code>rule create_archive:
    input: expand('sites.{sims}', CONF), expand('nodes.{sims}', CONF)
    output: ARCHIVE_FILE
    shell: 'tar -czvf {output} {input}'
</code>```

Body:
I need to run Bppancestor with multiple config files, I have tried different approaches but none of them worked. I have around 150 files, so doing it one by one is not an efficient solution.

The syntax to run bppancestor is the following one:

bppancestor params=config_file

I tried doing:

bppancestor params=directory_of_config_files/*

and using a Snakefile to try to automatize the workflow:

ARCHIVE_FILE = 'bpp_output.tar.gz'

# a single config file
CONFIG_FILE = 'config_files/{sims}.conf'

# Build the list of input files.
CONF = glob_wildcards(CONFIG_FILE).sims

# pseudo-rule that tries to build everything.
# Just add all the final outputs that you want built.
rule all:
    input: ARCHIVE_FILE

# run bppancestor
rule bpp:
    input:
        CONF,
    shell:
        'bppancestor params={input}'

# create an archive with all results
rule create_archive:
    input: CONF,
    output: ARCHIVE_FILE
    shell: 'tar -czvf {output} {input}'

Could someone give me advice on this?

Body:
You're very close. Rule bpp should use as input a specific config file and specify concrete output (not sure if the output is a file or a folder). If I understand the syntax correctly, this link suggests that output files can be specified using output.sites.file and output.nodes.file:

rule bpp:
    input:
        CONFIG_FILE,
    output:
        sites='sites.{sims}',
        nodes='nodes.{sims}',
    shell:
        'bppancestor params={input} output.sites.file={output.sites} output.nodes.file={output.nodes}'

Rule create_archive will collect all the outputs and archive them:

rule create_archive:
    input: expand('sites.{sims}', CONF), expand('nodes.{sims}', CONF)
    output: ARCHIVE_FILE
    shell: 'tar -czvf {output} {input}'