问:
No MaterialLocalizations found in flutter
I'm new to flutter and struggling to correct below error.  No MaterialLocalizations found. error in code. am I missing a library? or any code ? how can I fix this. appriciate your help on this.

error suggesion >>> To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically, or add a Localization widget with a MaterialLocalizations delegate.

createProfile.dart

```<code>import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;
import 'package:flutter/material.dart';

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

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

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),
            nameTextField(),
            SizedBox(
              height: 20,
            ),
            professionTextField(),
            SizedBox(
              height: 20,
            ),
            dobField(),
            SizedBox(
              height: 20,
            ),
            titleTextField(),
            SizedBox(
              height: 20,
            ),
            aboutTextField(),
            SizedBox(
              height: 20,
            ),

            InkWell(
              onTap: (){
                if (_globalkey.currentState!.validate()){
                  print("validated");
                }
              },

              child: Center(
                child: Container(
                  width: 200,
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.teal,
                    borderRadius: BorderRadius.circular(10),
                  ),

                  child: Center(
                    child: circular
                        ? CircularProgressIndicator()
                        : Text(
                      "Submit",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  Widget imageProfile() {
    return Center(
      child: Stack(children: <Widget>[
        CircleAvatar(
          radius: 80.0,
          backgroundImage: _imageFile == null
              ? AssetImage("assets/pic.jpg") as ImageProvider
              : FileImage(File(_imageFile!.path)),

        ),
        Positioned(
          bottom: 20.0,
          right: 20.0,
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                context: context,
                builder: ((builder) => bottomSheet()),
              );
            },
            child: Icon(
              Icons.camera_alt,
              color: Colors.teal,
              size: 28.0,
            ),
          ),
        ),
      ]),
    );
  }

  Widget bottomSheet() {
    return Container(
      height: 100.0,
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(
        horizontal: 20,
        vertical: 20,
      ),
      child: Column(
        children: <Widget>[
          Text(
            "Choose Profile photo",
            style: TextStyle(
              fontSize: 20.0,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
            TextButton.icon(
              icon: Icon(Icons.camera),
              onPressed: () {
                takePhoto(ImageSource.camera);
              },
              label: Text("Camera", ),
            ),
            TextButton.icon(
              icon: Icon(Icons.image),
              onPressed: () {
                takePhoto(ImageSource.gallery);
              },
              label: Text("Gallery"),
            ),
          ])
        ],
      ),
    );
  }

  void takePhoto(ImageSource source) async {
    final pickedFile = await _picker.pickImage(
      source: source,
    );
    setState(() {
      _imageFile = pickedFile as PickedFile;

    });
  }

  //starting text fields

  Widget nameTextField() {
    return TextFormField(
      controller: _name,
      validator: (value) {
        if (value!.isEmpty) return "Name can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Name",
        helperText: "Name can't be empty",
        hintText: "Anne Perera",
      ),
    );
  }

  Widget professionTextField() {
    return TextFormField(
      controller: _profession,
      validator: (value) {
        if (value!.isEmpty) return "Profession can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Profession",
        helperText: "Profession can't be empty",
        hintText: "Full Stack Developer",
      ),
    );
  }

  Widget dobField() {
    return TextFormField(
      controller: _dob,
      validator: (value) {
        if (value!.isEmpty) return "DOB can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Date Of Birth",
        helperText: "Provide DOB on dd/mm/yyyy",
        hintText: "01/01/2020",
      ),
    );
  }

  Widget titleTextField() {
    return TextFormField(
      controller: _title,
      validator: (value) {
        if (value!.isEmpty) return "Title can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Title",
        helperText: "It can't be empty",
        hintText: "Flutter Developer",
      ),
    );
  }

  Widget aboutTextField() {
    return TextFormField(
      controller: _about,
      validator: (value) {
        if (value!.isEmpty) return "About can't be empty";

        return null;
      },
      maxLines: 4,
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        labelText: "About",
        helperText: "Write about yourself",
        hintText: "I am Ann Perera",
      ),
    );
  }
}
</code>```

main.dart

```<code>Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  if (USE_EMULATOR) {
    _connectToFirebaseEmulator();
  }
  runApp(const MyApp());
}

Future _connectToFirebaseEmulator() async {
  final fireStorePort = "8080";
  final authPort = 9099;
  final localHost = Platform.isAndroid ? '10.0.2.2' : 'localhost';
  FirebaseFirestore.instance.settings = Settings(
      host: "$localHost:$fireStorePort",
      sslEnabled: false,
      persistenceEnabled: false);

  await FirebaseAuth.instance.useAuthEmulator('http://$localHost:', authPort);
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(

      home: CreateProfile(key: UniqueKey()),

      debugShowCheckedModeBanner: false,
      theme: CupertinoThemeData(
          brightness: Brightness.light, primaryColor: Color(0xff08c187)),
    );
  }
}
</code>```

答:
The error basically says that to use material widgets in a cupertino app you will have to add this:</p>
```<code>CupertinoApp(
    localizationsDelegates: [
        DefaultMaterialLocalizations.delegate,
        DefaultCupertinoLocalizations.delegate,
        DefaultWidgetsLocalizations.delegate,
    ],
),
</code>```

Body:
I'm new to flutter and struggling to correct below error.  No MaterialLocalizations found. error in code. am I missing a library? or any code ? how can I fix this. appriciate your help on this.

error suggesion >>> To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically, or add a Localization widget with a MaterialLocalizations delegate.

createProfile.dart

import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;
import 'package:flutter/material.dart';

class CreateProfile extends StatefulWidget {
  CreateProfile({required Key key}) : super(key: key);

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

class _CreateProfileState extends State<CreateProfile> {

  bool circular = false;
  PickedFile? _imageFile;
  final ImagePicker _picker = ImagePicker();

  final _globalkey = GlobalKey<FormState>();

  TextEditingController _name = TextEditingController();
  TextEditingController _profession = TextEditingController();
  TextEditingController _dob = TextEditingController();
  TextEditingController _title = TextEditingController();
  TextEditingController _about = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _globalkey,
        child: ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          children: <Widget>[
            imageProfile(),
            SizedBox(
              height: 20,
            ),
            nameTextField(),
            SizedBox(
              height: 20,
            ),
            professionTextField(),
            SizedBox(
              height: 20,
            ),
            dobField(),
            SizedBox(
              height: 20,
            ),
            titleTextField(),
            SizedBox(
              height: 20,
            ),
            aboutTextField(),
            SizedBox(
              height: 20,
            ),

            InkWell(
              onTap: (){
                if (_globalkey.currentState!.validate()){
                  print("validated");
                }
              },

              child: Center(
                child: Container(
                  width: 200,
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.teal,
                    borderRadius: BorderRadius.circular(10),
                  ),

                  child: Center(
                    child: circular
                        ? CircularProgressIndicator()
                        : Text(
                      "Submit",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  Widget imageProfile() {
    return Center(
      child: Stack(children: <Widget>[
        CircleAvatar(
          radius: 80.0,
          backgroundImage: _imageFile == null
              ? AssetImage("assets/pic.jpg") as ImageProvider
              : FileImage(File(_imageFile!.path)),

        ),
        Positioned(
          bottom: 20.0,
          right: 20.0,
          child: InkWell(
            onTap: () {
              showModalBottomSheet(
                context: context,
                builder: ((builder) => bottomSheet()),
              );
            },
            child: Icon(
              Icons.camera_alt,
              color: Colors.teal,
              size: 28.0,
            ),
          ),
        ),
      ]),
    );
  }

  Widget bottomSheet() {
    return Container(
      height: 100.0,
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(
        horizontal: 20,
        vertical: 20,
      ),
      child: Column(
        children: <Widget>[
          Text(
            "Choose Profile photo",
            style: TextStyle(
              fontSize: 20.0,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
            TextButton.icon(
              icon: Icon(Icons.camera),
              onPressed: () {
                takePhoto(ImageSource.camera);
              },
              label: Text("Camera", ),
            ),
            TextButton.icon(
              icon: Icon(Icons.image),
              onPressed: () {
                takePhoto(ImageSource.gallery);
              },
              label: Text("Gallery"),
            ),
          ])
        ],
      ),
    );
  }

  void takePhoto(ImageSource source) async {
    final pickedFile = await _picker.pickImage(
      source: source,
    );
    setState(() {
      _imageFile = pickedFile as PickedFile;

    });
  }

  //starting text fields

  Widget nameTextField() {
    return TextFormField(
      controller: _name,
      validator: (value) {
        if (value!.isEmpty) return "Name can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Name",
        helperText: "Name can't be empty",
        hintText: "Anne Perera",
      ),
    );
  }

  Widget professionTextField() {
    return TextFormField(
      controller: _profession,
      validator: (value) {
        if (value!.isEmpty) return "Profession can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Profession",
        helperText: "Profession can't be empty",
        hintText: "Full Stack Developer",
      ),
    );
  }

  Widget dobField() {
    return TextFormField(
      controller: _dob,
      validator: (value) {
        if (value!.isEmpty) return "DOB can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Date Of Birth",
        helperText: "Provide DOB on dd/mm/yyyy",
        hintText: "01/01/2020",
      ),
    );
  }

  Widget titleTextField() {
    return TextFormField(
      controller: _title,
      validator: (value) {
        if (value!.isEmpty) return "Title can't be empty";

        return null;
      },
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        prefixIcon: Icon(
          Icons.person,
          color: Colors.green,
        ),
        labelText: "Title",
        helperText: "It can't be empty",
        hintText: "Flutter Developer",
      ),
    );
  }

  Widget aboutTextField() {
    return TextFormField(
      controller: _about,
      validator: (value) {
        if (value!.isEmpty) return "About can't be empty";

        return null;
      },
      maxLines: 4,
      decoration: InputDecoration(
        border: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.teal,
            )),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              color: Colors.orange,
              width: 2,
            )),
        labelText: "About",
        helperText: "Write about yourself",
        hintText: "I am Ann Perera",
      ),
    );
  }
}

main.dart

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  if (USE_EMULATOR) {
    _connectToFirebaseEmulator();
  }
  runApp(const MyApp());
}

Future _connectToFirebaseEmulator() async {
  final fireStorePort = "8080";
  final authPort = 9099;
  final localHost = Platform.isAndroid ? '10.0.2.2' : 'localhost';
  FirebaseFirestore.instance.settings = Settings(
      host: "$localHost:$fireStorePort",
      sslEnabled: false,
      persistenceEnabled: false);

  await FirebaseAuth.instance.useAuthEmulator('http://$localHost:', authPort);
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(

      home: CreateProfile(key: UniqueKey()),

      debugShowCheckedModeBanner: false,
      theme: CupertinoThemeData(
          brightness: Brightness.light, primaryColor: Color(0xff08c187)),
    );
  }
}

Body:
The error basically says that to use material widgets in a cupertino app you will have to add this:

CupertinoApp(
    localizationsDelegates: [
        DefaultMaterialLocalizations.delegate,
        DefaultCupertinoLocalizations.delegate,
        DefaultWidgetsLocalizations.delegate,
    ],
),


来源: stackexchange

问:
How to add firebase security rules for Flutter collection that hasn't been created yet
I'm using Firebase Auth and Firestore Database.  I'm trying to add security rules to Firebase Database that allow users to read, update, create and delete posts.  When I test my rules in the Rules Playground access is denied so I know that I have not written the rules correctly.  This is an image of the database prior to adding security rules.

Now that I have added the security rules the posts collection isn't created and I get error messages in the Rules Playground of:

```<code>> Simulated write denied
> Simulated read denied
</code>```

And I get console error of:

The following _CastError was thrown building CommunityPage(dirty,
dependencies: [_InheritedProviderScope<UserProvider?>], state:
_CommunityPageState#f5d54): type 'Null' is not a subtype of type 'String' in type cast

In the app all users should be able to create posts to add to their profile.  When a user has a newly created account they do not have any posts that exist yet so I am trying to figure out how to include security rules that allow the page where posts will be displayed to appear even though it doesn't have any content when a new user is created.  I have reviewed SO threads and Firebase documentation but since I am new to Flutter and Firebase I can't figure things out.

Any help would be greatly appreciated.  Thank you.

答:
We can see in the Rules Playground that:

The read and write rules that are denied use the isSignedIn() function which checks if the request.auth object is not null;

But you don't simulate the user's authentication while using the Rules Playground: see the "Authenticated" switch above the "Run" button in the left pane of the Rules Playground

You should activate the authentication simulation in the Rules Playground for your isSignedIn() function to be evaluated to true.

Note that most probably the error shown in the right part of the Playground shows a message corresponding to this problem but we don't see it in your screenshot.

Update following your comment:

Note that request.resource shall only be used in a write rule (see the doc): this probably explains the problem with the read rule (screenshot at the bottom in your question). You have to do:

```<code>allow read: if isSignedIn() && request.auth.uid == resource.data.uid
</code>```

Note that the above rules means that there is a field named uid in the post document.

For the create rule error: are you sure you pass the user's uid as the value of the field named uid in the newly created document?

ContentLicense: CC BY-SA 4.0

Body:
I'm using Firebase Auth and Firestore Database.  I'm trying to add security rules to Firebase Database that allow users to read, update, create and delete posts.  When I test my rules in the Rules Playground access is denied so I know that I have not written the rules correctly.  This is an image of the database prior to adding security rules.

Now that I have added the security rules the posts collection isn't created and I get error messages in the Rules Playground of:

> Simulated write denied
> Simulated read denied

And I get console error of:

The following _CastError was thrown building CommunityPage(dirty,
dependencies: [_InheritedProviderScope<UserProvider?>], state:
_CommunityPageState#f5d54): type 'Null' is not a subtype of type 'String' in type cast

In the app all users should be able to create posts to add to their profile.  When a user has a newly created account they do not have any posts that exist yet so I am trying to figure out how to include security rules that allow the page where posts will be displayed to appear even though it doesn't have any content when a new user is created.  I have reviewed SO threads and Firebase documentation but since I am new to Flutter and Firebase I can't figure things out.

Any help would be greatly appreciated.  Thank you.

Body:
We can see in the Rules Playground that:

The read and write rules that are denied use the isSignedIn() function which checks if the request.auth object is not null;

But you don't simulate the user's authentication while using the Rules Playground: see the "Authenticated" switch above the "Run" button in the left pane of the Rules Playground

You should activate the authentication simulation in the Rules Playground for your isSignedIn() function to be evaluated to true.

Note that most probably the error shown in the right part of the Playground shows a message corresponding to this problem but we don't see it in your screenshot.

Update following your comment:

Note that request.resource shall only be used in a write rule (see the doc): this probably explains the problem with the read rule (screenshot at the bottom in your question). You have to do:

allow read: if isSignedIn() && request.auth.uid == resource.data.uid

Note that the above rules means that there is a field named uid in the post document.

For the create rule error: are you sure you pass the user's uid as the value of the field named uid in the newly created document?


问:
JavaFX ScrollPane - Detect when scrollbar is visible?
I have a ScrollPane as below:

```<code>    ScrollPane scroller = new ScrollPane();
    scroller.getStyleClass().add("scroller");
    scroller.setPrefWidth(width);
    scroller.setFocusTraversable(Boolean.FALSE);
    scroller.setPannable(Boolean.TRUE);
    scroller.setFitToWidth(Boolean.TRUE);
    scroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    scroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    this.setCenter(scroller);

    scroller.contentProperty().addListener((observableValue, last, now) ->
    {
        ScrollBar scrollBar = (ScrollBar) scroller.lookup(".scroll-bar:vertical");

        if (scrollBar != null)
        {
            if (scrollBar.isVisible())
            {
                log.info("Scrollbar visible, setting lower card width..");
            }
            else
            {
                log.info("Scrollbar not visible, setting default card width..");
            }
        }
    });
</code>```

As you can see I've attached a listener to the content property to know when the content is set. I am trying to see if the scrollbar is visible when the content is updated. Even though I can see the scroll bar on the UI, it always goes to else part - "Scrollbar not visible".

Not sure if there is any other way to do this? Checked a lot on StackOverflow and Oracle docs - nothing solid found to suggest otherwise.

-- Adding context to the problem to better understand:

Just trying to explain what the problem is not sure if I should put it as a reply comment or edit the question, please advise and will change it:

So I have this view that brings up records from Firebase that need to be loaded on the TilePane that is hosted in ScrollPane which goes into the Center of the BorderPane.

The time by which I get the response from the Firebase is unpredictable as its async. So the UI gets loaded up with the empty TilePane and then the async call goes to fetch data. When the data is available, I need to prepare Cards (which is HBox) but the number of columns is fixed. So have to adjust the width of the cards to keep the gap (16px) and padding (16px) consistent on the TilePane at the same time maintain 5 columns. The width of each card needs to be recalculated based on the fact that whether or not there is a scrollbar on the display. Because if the scrollbar is displayed it takes some space and the TilePane will down it to 4 columns leaving a lot of empty space. Happy to explain further if this is not clear.

答:
As @James_D said, used GridPane and it worked without any listeners:

```<code>    GridPane cards = new GridPane();
    cards.setVgap(16);
    cards.setHgap(16);

    cards.setAlignment(Pos.CENTER);
    cards.setPadding(new Insets(16));

    ColumnConstraints constraints = new ColumnConstraints();
    constraints.setPercentWidth(20);
    constraints.setHgrow(Priority.ALWAYS);
    constraints.setFillWidth(Boolean.TRUE);

    cards.getColumnConstraints().addAll(constraints, constraints, constraints, constraints, constraints);
</code>```

I have 5 columns, so 5 times constraints. Worked just fine.

Body:
I have a ScrollPane as below:

    ScrollPane scroller = new ScrollPane();
    scroller.getStyleClass().add("scroller");
    scroller.setPrefWidth(width);
    scroller.setFocusTraversable(Boolean.FALSE);
    scroller.setPannable(Boolean.TRUE);
    scroller.setFitToWidth(Boolean.TRUE);
    scroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    scroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    this.setCenter(scroller);

    scroller.contentProperty().addListener((observableValue, last, now) ->
    {
        ScrollBar scrollBar = (ScrollBar) scroller.lookup(".scroll-bar:vertical");

        if (scrollBar != null)
        {
            if (scrollBar.isVisible())
            {
                log.info("Scrollbar visible, setting lower card width..");
            }
            else
            {
                log.info("Scrollbar not visible, setting default card width..");
            }
        }
    });

As you can see I've attached a listener to the content property to know when the content is set. I am trying to see if the scrollbar is visible when the content is updated. Even though I can see the scroll bar on the UI, it always goes to else part - "Scrollbar not visible".

Not sure if there is any other way to do this? Checked a lot on StackOverflow and Oracle docs - nothing solid found to suggest otherwise.

-- Adding context to the problem to better understand:

Just trying to explain what the problem is not sure if I should put it as a reply comment or edit the question, please advise and will change it:

So I have this view that brings up records from Firebase that need to be loaded on the TilePane that is hosted in ScrollPane which goes into the Center of the BorderPane.

The time by which I get the response from the Firebase is unpredictable as its async. So the UI gets loaded up with the empty TilePane and then the async call goes to fetch data. When the data is available, I need to prepare Cards (which is HBox) but the number of columns is fixed. So have to adjust the width of the cards to keep the gap (16px) and padding (16px) consistent on the TilePane at the same time maintain 5 columns. The width of each card needs to be recalculated based on the fact that whether or not there is a scrollbar on the display. Because if the scrollbar is displayed it takes some space and the TilePane will down it to 4 columns leaving a lot of empty space. Happy to explain further if this is not clear.

Body:
As @James_D said, used GridPane and it worked without any listeners:

    GridPane cards = new GridPane();
    cards.setVgap(16);
    cards.setHgap(16);

    cards.setAlignment(Pos.CENTER);
    cards.setPadding(new Insets(16));

    ColumnConstraints constraints = new ColumnConstraints();
    constraints.setPercentWidth(20);
    constraints.setHgrow(Priority.ALWAYS);
    constraints.setFillWidth(Boolean.TRUE);

    cards.getColumnConstraints().addAll(constraints, constraints, constraints, constraints, constraints);

I have 5 columns, so 5 times constraints. Worked just fine.


问:
Get timezone from users browser using moment(timezone).js
What is the best way to get client's timezone and convert it to some other timezone when using moment.js and moment-timezone.js

I want to find out what is clients timezone and later convert his date and time into some other timezone.

Does anybody has experience with this?

答:
First, you can find out the clients time zone using the following

let zoneVal =  moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('Z')

it will return you the GMT zone format for example +5:30 (colombo/srilanka & Delhi/India) or +6:00(Dhaka Bangladesh)  depending on the region you are in.

secondly,
if you want to find out the time of a particular time zone , then do the following

moment.tz("Asia/Dhaka").format()

which will return you the time zone value in ISO format of Dhaka.

ContentLicense: CC BY-SA 3.0


问:
What's the best practice to keep all the constants in Flutter?
What's the best programming practice to create a constant class in Flutter to keep all the application constants for easy reference?

I know that there is const keyword in Dart for creating constant fields, but is it okay to use static along with const, or will it create memory issues during runtime.

```<code>class Constants {
  static const String SUCCESS_MESSAGE = "You will be contacted by us very soon.";
}
</code>```

This question is not only based on getting a proper structure but also on knowing how to save resources and memory leakage prevention while creating constants.

答:
i personally like this package flutter_gen 4.1.5  to add constant not only limited to string, this package also help you colors, assets, fonts etc (In short you can handle all const)

The Flutter code generator for your assets, fonts, colors, — Get rid of all String-based APIs.

Here is the example flutter_gen/example

Body:
What's the best programming practice to create a constant class in Flutter to keep all the application constants for easy reference?

I know that there is const keyword in Dart for creating constant fields, but is it okay to use static along with const, or will it create memory issues during runtime.

class Constants {
  static const String SUCCESS_MESSAGE = "You will be contacted by us very soon.";
}

This question is not only based on getting a proper structure but also on knowing how to save resources and memory leakage prevention while creating constants.


问:
my HTML Shortcuts in VS Code are not working
I started studying HTML on YouTube not long ago and have been using visual studio code. Whenever specific shortcuts are used, mine does not work. An example would be typing the exclamation mark and then the tab button("!" + tab) to automatically give you the default HTML skeletal template.
Also, tag suggestions do not work. Whenever I start to type a tag like , I don't get any suggestions whatsoever and it leads to a lot of mistakes and confusion for me. Can someone help me, please?</p>

答:
You only need to change languague on status bar (below) from Django html to html.

Now retype the shortcut i.e. "!+Enter"


问:
How to add/update an attribute to an HTML element using JavaScript?
I'm trying to find a way that will add / update attribute using JavaScript.  I know I can do it with setAttribute() function but that doesn't work in IE.

答:
What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

OwnerDisplayName: annakata

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: annakata


问:
how to hide html button when disabled
GOOD MORNING, I'm editing on this code... someone can solve this: how to hide the button when it is disabled?

function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;
}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;
}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="q">
<dl id="1">
    <dd><b>TEXT.</b><br>
      <label><input type="radio" name="q1" value="1a"> 1. </label><br>
      <label><input type="radio" name="q1" value="1b"> 2. </label><br>
      <label><input type="radio" name="q1" value="1c"> 3. </label>
    <hr></dd>
 </dl>

<div><input type="button" value="BUTTON" disabled="" id="scoreButton"></div>
</div></code>```

答:
Using simple CSS:</p>
```<code>button[disabled] { display: none; }
</code>```

Title: how to hide html button when disabled

Body:
GOOD MORNING, I'm editing on this code... someone can solve this: how to hide the button when it is disabled?

function Selected() {
  return document.querySelectorAll('input[type=radio]:checked').length;
}

function onChange() {
  console.log(Selected());
  document.getElementById('scoreButton').disabled = Selected() < 1;
}

document.querySelectorAll('input[type=radio]').forEach(node => {
  node.addEventListener('change', onChange, false);
});

TEXT.

      <input type="radio" name="q1" value="1a"> 1.

      <input type="radio" name="q1" value="1b"> 2.

      <input type="radio" name="q1" value="1c"> 3.

<input type="button" value="BUTTON" disabled="" id="scoreButton">

Body:
Using simple CSS:

button[disabled] { display: none; }


问:
How to Create a Custom Scrollbar in UWP?
I need to create a custom Scrollbar in UWP ? But I can't find any clear logic to calculate Scrollbar thumb width and Position.
What I have tried ?

```<code>ThumbWidth=(VisibleLength/TotalLength)*ScrollRegionWidth;
ThumbPosition=(ScrollLeft/TotalLength)*ScrollRegionWidth;
</code>```

where,

```<code>VisibleLength -> viewable area width
TotalLength -> Total Content width
ScrollRegionWidth -> Scrollbar width - (2 x ArrowWidth)  (or) Thumb Track width
ScrollLeft -> how much content scrolled !!
</code>```

Is it correct ? I tried like this . But the scrollbar thumb won't goes to end of thumb track while my whole content is scrolled to end !

I need to create a custom Scrollbar and how to do it ? I need complete logic for thumb width and position .

答:
How to Create a Custom Scrollbar in UWP?

```<code>ThumbWidth=(VisibleLength/TotalLength)*ScrollRegionWidth;
</code>```

Your first line is correct. and you could verify it with VisibleLength = TotalLength, then ThumbWidth will fill all the ScrollRegion.

```<code>ThumbPosition=(ScrollLeft/TotalLength)*ScrollRegionWidth;
</code>```

But the second line looks not correct, Thumb's start position should be left top, the ScrollRegion should be (ScrollRegionWidth - ThumbWidth).

```<code>ThumbPosition=(ScrollLeft/TotalLength)*(ScrollRegionWidth-ThumbWidth);
</code>```

Body:
I need to create a custom Scrollbar in UWP ? But I can't find any clear logic to calculate Scrollbar thumb width and Position.
What I have tried ?

ThumbWidth=(VisibleLength/TotalLength)*ScrollRegionWidth;
ThumbPosition=(ScrollLeft/TotalLength)*ScrollRegionWidth;

where,

VisibleLength -> viewable area width
TotalLength -> Total Content width
ScrollRegionWidth -> Scrollbar width - (2 x ArrowWidth)  (or) Thumb Track width
ScrollLeft -> how much content scrolled !!

Is it correct ? I tried like this . But the scrollbar thumb won't goes to end of thumb track while my whole content is scrolled to end !

I need to create a custom Scrollbar and how to do it ? I need complete logic for thumb width and position .

Body:
How to Create a Custom Scrollbar in UWP?

ThumbWidth=(VisibleLength/TotalLength)*ScrollRegionWidth;

Your first line is correct. and you could verify it with VisibleLength = TotalLength, then ThumbWidth will fill all the ScrollRegion.

ThumbPosition=(ScrollLeft/TotalLength)*ScrollRegionWidth;

But the second line looks not correct, Thumb's start position should be left top, the ScrollRegion should be (ScrollRegionWidth - ThumbWidth).

ThumbPosition=(ScrollLeft/TotalLength)*(ScrollRegionWidth-ThumbWidth);


问:
how to obtain execution plan from a PLSQL
I have a code snippet like :

```<code>declare
    cursor c is select ....
begin
    for i in c loop
        update table t1 where ti.c1 = i.column ...
    end loop;
end;
</code>```

I am wondering how to obtain an execution plan from the update statement since there is involved a condition between a column from a table and a column from cursor.

Can anyone give me a hint, please?

Thank you.

答:
That's just an ordinary UPDATE statement. As it is in a loop, it executes row-by-row (returned from the cursor) (it might, though, update multiple rows at once, depending on its (UPDATE's) WHERE clause).

Therefore, you'd just "extract" it from the loop and explain it, alone, e.g. if it is

```<code>cursor c is
  select id, job from emp_2;
begin
  for i in c loop
    update emp e set e.job = i.job where e.id = i.id;
  end loop;
end;
</code>```

Suppose one of rows returned by cursor has id = 7369, job = CLERK; then

```<code>explain plan for update emp e set e.job = 'CLERK' where e.id = 7369;

select * from plan_table;
</code>```

Body:
I have a code snippet like :

declare
    cursor c is select ....
begin
    for i in c loop
        update table t1 where ti.c1 = i.column ...
    end loop;
end;

I am wondering how to obtain an execution plan from the update statement since there is involved a condition between a column from a table and a column from cursor.

Can anyone give me a hint, please?

Thank you.

Body:
That's just an ordinary UPDATE statement. As it is in a loop, it executes row-by-row (returned from the cursor) (it might, though, update multiple rows at once, depending on its (UPDATE's) WHERE clause).

Therefore, you'd just "extract" it from the loop and explain it, alone, e.g. if it is

cursor c is
  select id, job from emp_2;
begin
  for i in c loop
    update emp e set e.job = i.job where e.id = i.id;
  end loop;
end;

Suppose one of rows returned by cursor has id = 7369, job = CLERK; then

explain plan for update emp e set e.job = 'CLERK' where e.id = 7369;

select * from plan_table;


问:
Database design: Simplicity in query vs simplicity in schema
There is an assignments table, and every assignment has a target GUID and a serial number. There are two processes: one inserts assignments and another one queries them and executes them. Assignments for one target must be processed strictly in serial number order, without any gaps.

If there is a gap in serial numbers sequence, the executing process should wait for this gap to be filled before processing further assignments for this target

We identified two approaches to solve this.
The first one is to have a boolean flag "is_ready", and set it on each insert in the following way:

```<code>UPDATE assignments
SET is_ready = true
FROM (
    SELECT ROW_NUMBER () OVER (ORDER BY serial_number)
    FROM assignments
    WHERE target = <#address> and serial_number >= <#last_serial_number>
) AS subquery
WHERE
    subquery.serial_number=<#last_serial_number> + subquery.row_number and
    transactions.last_serial_number =  subquery.last_serial_number and
    transactions.target = subquery.target;
</code>```

Note that if there are any gaps, we only allow at most 5 assignments that are waiting (so the subquery will reutrn at most 5 rows)

Alternatively, we can have an integer field . It would represent the number of gaps in serial numbers for this target before current serial number. This way on insert we just have to update all the records with serial_number higher than the one being inserted:

```<code>UPDATE assignments
SET number_of_serial_gaps = number_of_serial_gaps - 1
WHERE target = <#address> AND serial_number >= <#last_serial_number>
</code>```

And then on SELECT we just have to check that number_of_serial_gaps == 0.

The first approach has (arguably) cleaner DB structure - just one boolean field, while the second approach has an advantage of requiring a simpler query.

Both ways would probably do and I think the difference is not substantial, however perhaps there are some stronger arguments on either side?

答:
My recomendation would be not to keep the status in the table, but to check it in the query of the executing process.

Lets assume sample data as follows

```<code>select * from tab
order by target,serial_number;

T SERIAL_NUMBER
- -------------
x             1
x             2
x             3
x             4
x             5
x             6
x             7
x             9
x            10
</code>```

So the serial 8 is missing.

An executor that wants to get a batch of 5 row starting from 1 should suceed, but it fails to get a batch of 10 row starting from 1.

The query below performs exact that, simple selecting the allowed range of serial numbers and checks if all serials are available with the count subquery

```<code>-- get a batch of 5 row starting from 1
with dt as (
select * from tab
where target = 'x'
and serial_number >= 1
and serial_number < 1 + 5)
select * from dt
where
5 = (select count(distinct serial_number) from dt)
order by 1,2;

T SERIAL_NUMBER
- -------------
x             1
x             2
x             3
x             4
x             5

-- get a batch of 10 row starting from 1
with dt as (
select * from tab
where target = 'x'
and serial_number >= 1
and serial_number < 1 + 10)
select * from dt
where
10 = (select count(distinct serial_number) from dt)
order by 1,2;

no rows
</code>```

Body:
There is an assignments table, and every assignment has a target GUID and a serial number. There are two processes: one inserts assignments and another one queries them and executes them. Assignments for one target must be processed strictly in serial number order, without any gaps.

If there is a gap in serial numbers sequence, the executing process should wait for this gap to be filled before processing further assignments for this target

We identified two approaches to solve this.
The first one is to have a boolean flag "is_ready", and set it on each insert in the following way:

UPDATE assignments
SET is_ready = true
FROM (
    SELECT ROW_NUMBER () OVER (ORDER BY serial_number)
    FROM assignments
    WHERE target = <#address> and serial_number >= <#last_serial_number>
) AS subquery
WHERE
    subquery.serial_number=<#last_serial_number> + subquery.row_number and
    transactions.last_serial_number =  subquery.last_serial_number and
    transactions.target = subquery.target;

Note that if there are any gaps, we only allow at most 5 assignments that are waiting (so the subquery will reutrn at most 5 rows)

Alternatively, we can have an integer field . It would represent the number of gaps in serial numbers for this target before current serial number. This way on insert we just have to update all the records with serial_number higher than the one being inserted:

UPDATE assignments
SET number_of_serial_gaps = number_of_serial_gaps - 1
WHERE target = <#address> AND serial_number >= <#last_serial_number>

And then on SELECT we just have to check that number_of_serial_gaps == 0.

The first approach has (arguably) cleaner DB structure - just one boolean field, while the second approach has an advantage of requiring a simpler query.

Both ways would probably do and I think the difference is not substantial, however perhaps there are some stronger arguments on either side?

Body:
My recomendation would be not to keep the status in the table, but to check it in the query of the executing process.

Lets assume sample data as follows

select * from tab
order by target,serial_number;

T SERIAL_NUMBER
- -------------
x             1
x             2
x             3
x             4
x             5
x             6
x             7
x             9
x            10

So the serial 8 is missing.

An executor that wants to get a batch of 5 row starting from 1 should suceed, but it fails to get a batch of 10 row starting from 1.

The query below performs exact that, simple selecting the allowed range of serial numbers and checks if all serials are available with the count subquery

-- get a batch of 5 row starting from 1
with dt as (
select * from tab
where target = 'x'
and serial_number >= 1
and serial_number < 1 + 5)
select * from dt
where
5 = (select count(distinct serial_number) from dt)
order by 1,2;

T SERIAL_NUMBER
- -------------
x             1
x             2
x             3
x             4
x             5

-- get a batch of 10 row starting from 1
with dt as (
select * from tab
where target = 'x'
and serial_number >= 1
and serial_number < 1 + 10)
select * from dt
where
10 = (select count(distinct serial_number) from dt)
order by 1,2;

no rows


问:
Need help understanding an event being assigned "delegate { }"
While looking at an UWP example app, I came across this code. What I don't understand and can't seem to find in google is line 40:

```<code>        public event PropertyChangedEventHandler PropertyChanged = delegate { };
</code>```

Says in the comments that it is a multicast event. What does assigning delegate { } do? Does it have anything to do with the comment saying the event is multicast?

答:
It's just an empty delegate, but the compiler will derive delegates from MulticastDelegate. So all delegates in C# are multicast.</p>
```<code>Action d = delegate { };
// True
Console.WriteLine(d.GetType().BaseType == typeof(MulticastDelegate));
</code>```

Body:
While looking at an UWP example app, I came across this code. What I don't understand and can't seem to find in google is line 40:

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

Says in the comments that it is a multicast event. What does assigning delegate { } do? Does it have anything to do with the comment saying the event is multicast?

Body:
It's just an empty delegate, but the compiler will derive delegates from MulticastDelegate. So all delegates in C# are multicast.

Action d = delegate { };
// True
Console.WriteLine(d.GetType().BaseType == typeof(MulticastDelegate));


问:
Inner join three tables out of which one is not connected with other
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

```<code>SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;
</code>```

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)

答: Try a GROUP BY with the columns that are identified as primary items to show.</p>

Body:
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)


问:
Can I make multiple assignments within a given case_when true clause?
Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145

In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like

case when condition then var1 = x, var2 = y

Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!

Note that in the example below, var1, var2  and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  select(Petal.Length, Petal.Width, Species) %>%
  as_tibble()
data
#> # A tibble: 5 × 3
#>   Petal.Length Petal.Width Species
#>          <dbl>       <dbl> <fct>
#> 1          5.5         1.8 virginica
#> 2          5           1.9 virginica
#> 3          1.5         0.2 setosa
#> 4          5.9         2.3 virginica
#> 5          4.1         1.3 versicolor
data %>%
  mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
         var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
         var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#>   Petal.Length Petal.Width Species    var1   var2 var3
#>          <dbl>       <dbl> <fct>      <chr> <dbl> <date>
#> 1          5.5         1.8 virginica  blue    5.5 2003-12-02
#> 2          5           1.9 virginica  blue    5   2003-12-02
#> 3          1.5         0.2 setosa     green 148.  2002-12-01
#> 4          5.9         2.3 virginica  blue    5.9 2003-12-02
#> 5          4.1         1.3 versicolor blue    4.1 2003-12-02
```

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

答:
Maybe this helps:

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  as_tibble()
data
#> # A tibble: 5 x 5
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>
#> 1          6.4         3.1          5.5         1.8 virginica
#> 2          6.3         2.5          5           1.9 virginica
#> 3          5.3         3.7          1.5         0.2 setosa
#> 4          6.8         3.2          5.9         2.3 virginica
#> 5          5.7         2.8          4.1         1.3 versicolor

data %>%
  mutate(
    sepal_size = case_when(
      Sepal.Length > 6 & Sepal.Width > 3 ~ "big",
      Sepal.Width > 3 ~ "medium",
      TRUE ~ "small"
    ),
    petal_size = case_when(
      Petal.Length > 5 ~ "big",
      TRUE ~ "small"
    ),
    is_fancy = TRUE
  )
#> # A tibble: 5 x 8
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species    sepal_size
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>      <chr>
#> 1          6.4         3.1          5.5         1.8 virginica  big
#> 2          6.3         2.5          5           1.9 virginica  small
#> 3          5.3         3.7          1.5         0.2 setosa     medium
#> 4          6.8         3.2          5.9         2.3 virginica  big
#> 5          5.7         2.8          4.1         1.3 versicolor small
#> # … with 2 more variables: petal_size <chr>, is_fancy <lgl>
```
<p><sup>Created on 2022-02-08 by the reprex package (v2.0.1)</sup>
To do the reverse, you can do:</p>
```iris %>%
  mutate(
    selected = Species == "setosa",
    var1 = ifelse(selected, Petal.Length * 99, Petal.Length),
    var2 = ifelse(selected, as.Date("2002-12-01"), as.Date("2003-12-02"))
  )
```

Body:
Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145

In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like

case when condition then var1 = x, var2 = y

Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!

Note that in the example below, var1, var2  and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  select(Petal.Length, Petal.Width, Species) %>%
  as_tibble()
data
#> # A tibble: 5 × 3
#>   Petal.Length Petal.Width Species
#>          <dbl>       <dbl> <fct>
#> 1          5.5         1.8 virginica
#> 2          5           1.9 virginica
#> 3          1.5         0.2 setosa
#> 4          5.9         2.3 virginica
#> 5          4.1         1.3 versicolor
data %>%
  mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
         var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
         var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#>   Petal.Length Petal.Width Species    var1   var2 var3
#>          <dbl>       <dbl> <fct>      <chr> <dbl> <date>
#> 1          5.5         1.8 virginica  blue    5.5 2003-12-02
#> 2          5           1.9 virginica  blue    5   2003-12-02
#> 3          1.5         0.2 setosa     green 148.  2002-12-01
#> 4          5.9         2.3 virginica  blue    5.9 2003-12-02
#> 5          4.1         1.3 versicolor blue    4.1 2003-12-02

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

Body:
Maybe this helps:

library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  as_tibble()
data
#> # A tibble: 5 x 5
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>
#> 1          6.4         3.1          5.5         1.8 virginica
#> 2          6.3         2.5          5           1.9 virginica
#> 3          5.3         3.7          1.5         0.2 setosa
#> 4          6.8         3.2          5.9         2.3 virginica
#> 5          5.7         2.8          4.1         1.3 versicolor

data %>%
  mutate(
    sepal_size = case_when(
      Sepal.Length > 6 & Sepal.Width > 3 ~ "big",
      Sepal.Width > 3 ~ "medium",
      TRUE ~ "small"
    ),
    petal_size = case_when(
      Petal.Length > 5 ~ "big",
      TRUE ~ "small"
    ),
    is_fancy = TRUE
  )
#> # A tibble: 5 x 8
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species    sepal_size
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>      <chr>
#> 1          6.4         3.1          5.5         1.8 virginica  big
#> 2          6.3         2.5          5           1.9 virginica  small
#> 3          5.3         3.7          1.5         0.2 setosa     medium
#> 4          6.8         3.2          5.9         2.3 virginica  big
#> 5          5.7         2.8          4.1         1.3 versicolor small
#> # … with 2 more variables: petal_size <chr>, is_fancy <lgl>

Created on 2022-02-08 by the reprex package (v2.0.1)
To do the reverse, you can do:

iris %>%
  mutate(
    selected = Species == "setosa",
    var1 = ifelse(selected, Petal.Length * 99, Petal.Length),
    var2 = ifelse(selected, as.Date("2002-12-01"), as.Date("2003-12-02"))
  )


问:
Adding Text on the selected canvas in Fabric js
I have fabric js multiple canvases and I would like to add Text on the selected canvas, instead of the last item of the array.

If a user creates multiple canvases then I need an option to add the text on the selected canvas.

Please run the code snippet or see the codepen demo of the current approach...

Thank you!

//================== Create Canvas start =================
var createCanvas = document.getElementById("createCanvas");
var canvasInstances = [];
createCanvas.addEventListener('click',function(){
    var canvasContainer = document.getElementById("canvasContainer");
  var newcanvas = document.createElement("canvas");
  //newcanvas.classList.add("active");
  canvasContainer.append(newcanvas);
  var fabricCanvasObj =  new fabric.Canvas(newcanvas, {
    height: 400,
    width: 400,
    backgroundColor: '#ffffff',
  });
  canvasInstances.push(fabricCanvasObj);
  console.log(canvasInstances);
})
//================== Create Canvas End =================

//================== Add Text  ================
var addText = document.getElementById("addText");
addText.addEventListener('click',function(){
    canvasInstances.forEach(function(current,id,array){
    if(id === array.length - 1){
      const converText = new fabric.IText(`Type Text`,{
        type: 'text',
        width: 200,
        fontSize: 20,
        left: 20,
        top: 20,
        fill: '#444'
      });

      current.add(converText);
      current.renderAll();
      return false;
    }
  })
})
//================== Add End  =================```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  box-sizing: border-box;
}
body{
  background:#ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
 margin-bottom: 200px;
}
.canvas-container{
  margin-bottom:10px;
}
.add-text{
  margin: 20px;
  width: 400px;
  text-align: center;
  border:1px dashed red;
  padding: 15px;
  cursor:pointer;
}</code>```

Add Text

<button id="createCanvas">Create Canvas</button>
        ```

答:
Declare canvasobject globally, you can try below code</p>
```<code><script type="text/javascript">
var canvasobject;
window.onload = function () {
   canvasobject = new fabric.Canvas('myCanvas');
   canvasobject.backgroundColor = '#0056d6';
   canvasobject.renderAll();
   //
   function addtext() {
       var textvalue = "Type here";
       var fontcolor = "#333";
       var fontFamily = "Baloo 2";
       var myfont = new FontFaceObserver(fontFamily);
       myfont.load()
          .then(function () {
            // when font is loaded, use it.
            var text = new fabric.Text(textvalue, {
              left: 100,
              top: 100,
              fontFamily: fontFamily,
              fill: fontcolor,
            });
            canvasobject.add(text);
            canvasobject.renderAll();
          }).catch(function (e) {
            //console.log(e);
            console.log('font loading failed ' + fontFamily);
       });
   }
}
</code>```

Body:
I have fabric js multiple canvases and I would like to add Text on the selected canvas, instead of the last item of the array.

If a user creates multiple canvases then I need an option to add the text on the selected canvas.

Please run the code snippet or see the codepen demo of the current approach...

Thank you!

//================== Create Canvas start =================
var createCanvas = document.getElementById("createCanvas");
var canvasInstances = [];
createCanvas.addEventListener('click',function(){
    var canvasContainer = document.getElementById("canvasContainer");
  var newcanvas = document.createElement("canvas");
  //newcanvas.classList.add("active");
  canvasContainer.append(newcanvas);
  var fabricCanvasObj =  new fabric.Canvas(newcanvas, {
    height: 400,
    width: 400,
    backgroundColor: '#ffffff',
  });
  canvasInstances.push(fabricCanvasObj);
  console.log(canvasInstances);
})
//================== Create Canvas End =================

//================== Add Text  ================
var addText = document.getElementById("addText");
addText.addEventListener('click',function(){
    canvasInstances.forEach(function(current,id,array){
    if(id === array.length - 1){
      const converText = new fabric.IText(`Type Text`,{
        type: 'text',
        width: 200,
        fontSize: 20,
        left: 20,
        top: 20,
        fill: '#444'
      });

      current.add(converText);
      current.renderAll();
      return false;
    }
  })
})
//================== Add End  =================

*{
  box-sizing: border-box;
}
body{
  background:#ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
 margin-bottom: 200px;
}
.canvas-container{
  margin-bottom:10px;
}
.add-text{
  margin: 20px;
  width: 400px;
  text-align: center;
  border:1px dashed red;
  padding: 15px;
  cursor:pointer;
}

Add Text

<button id="createCanvas">Create Canvas</button>

Body:
Declare canvasobject globally, you can try below code

<script type="text/javascript">
var canvasobject;
window.onload = function () {
   canvasobject = new fabric.Canvas('myCanvas');
   canvasobject.backgroundColor = '#0056d6';
   canvasobject.renderAll();
   //
   function addtext() {
       var textvalue = "Type here";
       var fontcolor = "#333";
       var fontFamily = "Baloo 2";
       var myfont = new FontFaceObserver(fontFamily);
       myfont.load()
          .then(function () {
            // when font is loaded, use it.
            var text = new fabric.Text(textvalue, {
              left: 100,
              top: 100,
              fontFamily: fontFamily,
              fill: fontcolor,
            });
            canvasobject.add(text);
            canvasobject.renderAll();
          }).catch(function (e) {
            //console.log(e);
            console.log('font loading failed ' + fontFamily);
       });
   }
}


问:
The argument type 'Object?' can't be assigned to the parameter type 'String'
These are the errors I get

Here is my chart.dart file

```<code>import 'package:flutter/material.dart';
import 'package:udemy_expenses_app/widgets/chart_bar.dart';
import '../models/tanscations.dart';
import 'package:intl/intl.dart';
import './chart_bar.dart';

class Chart extends StatelessWidget {
  final List<Transaction> recentTransactions;
  Chart(this.recentTransactions);
  List<Map<String, Object>> get groupedTransactionValues {
  return List.generate(7, (index) {
   final weekDay = DateTime.now().subtract(
    Duration(
      days: index,
    ),
  );
  double totalSum = 0.0;
  for (var i = 0; i < recentTransactions.length; i++) {
    if (recentTransactions[i].date.day == weekDay.day &&
        recentTransactions[i].date.month == weekDay.month &&
        recentTransactions[i].date.year == weekDay.year) {
      totalSum += recentTransactions[i].amount;
    }
  }

  return {
    'day': DateFormat.E().format(weekDay).substring(0, 1),
    'amount': totalSum,
  };
});
}

double get totalSpending {
  return groupedTransactionValues.fold(0.0, (sum, item) {
  return sum + item['amount'];
  //  Error: A value of type 'Object?' can't be assigned to a variable of type 'num'.
 });
}

@override
Widget build(BuildContext context) {
  return Card(
    elevation: 6,
    margin: EdgeInsets.all(20),
    child: Row(
        children: groupedTransactionValues.map((data) {
      return ChartBar(
        data['day'],
        // Error: The argument type 'Object?' can't be assigned to the parameter type 'String'.
        data['amount'],
        // Error: The argument type 'Object?' can't be assigned to the parameter type 'String'.
        (data['amount'] as double) / totalSpending,
      );
    }).toList()));
  }
}
</code>```

I dont know where did I go wrong

答:
Change the object to dynamic in:

```<code> (List<Map<String, Object>> get groupedTransactionValues { )
</code>```

If the error is not solved, try adding:

```<code> data['day'] as String,
 data['amount'] as double,
</code>```

Body:
These are the errors I get

Here is my chart.dart file

import 'package:flutter/material.dart';
import 'package:udemy_expenses_app/widgets/chart_bar.dart';
import '../models/tanscations.dart';
import 'package:intl/intl.dart';
import './chart_bar.dart';

class Chart extends StatelessWidget {
  final List<Transaction> recentTransactions;
  Chart(this.recentTransactions);
  List<Map<String, Object>> get groupedTransactionValues {
  return List.generate(7, (index) {
   final weekDay = DateTime.now().subtract(
    Duration(
      days: index,
    ),
  );
  double totalSum = 0.0;
  for (var i = 0; i < recentTransactions.length; i++) {
    if (recentTransactions[i].date.day == weekDay.day &&
        recentTransactions[i].date.month == weekDay.month &&
        recentTransactions[i].date.year == weekDay.year) {
      totalSum += recentTransactions[i].amount;
    }
  }

  return {
    'day': DateFormat.E().format(weekDay).substring(0, 1),
    'amount': totalSum,
  };
});
}

double get totalSpending {
  return groupedTransactionValues.fold(0.0, (sum, item) {
  return sum + item['amount'];
  //  Error: A value of type 'Object?' can't be assigned to a variable of type 'num'.
 });
}

@override
Widget build(BuildContext context) {
  return Card(
    elevation: 6,
    margin: EdgeInsets.all(20),
    child: Row(
        children: groupedTransactionValues.map((data) {
      return ChartBar(
        data['day'],
        // Error: The argument type 'Object?' can't be assigned to the parameter type 'String'.
        data['amount'],
        // Error: The argument type 'Object?' can't be assigned to the parameter type 'String'.
        (data['amount'] as double) / totalSpending,
      );
    }).toList()));
  }
}

I dont know where did I go wrong

Body:
Change the object to dynamic in:

 (List<Map<String, Object>> get groupedTransactionValues { )

If the error is not solved, try adding:

 data['day'] as String,
 data['amount'] as double,


问:
How can I call a JavaScript function embedded inside an html page using flex?
I know there are ways to invoke javascript inside the html wrapper template for the flex application using ExternalInterface, but is it possible to reference an external html page?</p>

答:
i think its not possible to reference an external html page.
you call function in AS3

```<code>ExternalInterface.call("MyFun");
</code>```

in html wrapper file of flex within javascript you have to define function MyFun

```<code> function MyFun()
    {
    ............
    ..........
    }
</code>```

Body:
i think its not possible to reference an external html page.
you call function in AS3

ExternalInterface.call("MyFun");

in html wrapper file of flex within javascript you have to define function MyFun

 function MyFun()
    {
    ............
    ..........
    }


问:
seaborn plot diffrent histogram and distrubtion on the same plot
I want to compare two distributions- one from real data- just plot histogram of cases and function of date and the other from predict model- plot the distribution.
I have two codes, one for each distribution:

only KDE without hist-

ax=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))

histogram from real data-

ax=sns.displot(df['DATE'].sort_values(),stat="density")
plt.xticks(rotation=90, fontsize=10)
plt.show()

I want to show those two on the same plot. I tried this code but in return 2 different plots:

```<code>ax1=sns.displot(df_2013['DATE'].sort_values(),stat="density")
ax2=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax1.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))
ax2.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))

plt.show()
</code>```

thanks for helping

答:
You need to define the figure first and add subplots to it.

```<code>with sns.axes_style("whitegrid"):
    fig = plt.figure(figsize=(15,10))
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)

    ax1.plot(df1['Column1'])
    ax2.plot(df2['Column1'])
</code>```

This way you can also plot on the same axis and overlay your plots if you want to. Or you can make plots align under each other in seperate subplots.

Here is an example of superimposed distplots that might be useful to you.

```<code>fig = plt.figure(figsize=(7.5,7.5))
ax1 = fig.add_subplot(211)
sns.distplot(Fnormal,ax = ax1, label="Normal Distribution from Filter");
sns.distplot(FilteredReturns, ax =ax1, label="Filtered Returns");
ax1.set_title('Comparison of Filtered Returns and Normal Distribution')
ax1.legend()
</code>```

Body:
I want to compare two distributions- one from real data- just plot histogram of cases and function of date and the other from predict model- plot the distribution.
I have two codes, one for each distribution:

only KDE without hist-

ax=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))

histogram from real data-

ax=sns.displot(df['DATE'].sort_values(),stat="density")
plt.xticks(rotation=90, fontsize=10)
plt.show()

I want to show those two on the same plot. I tried this code but in return 2 different plots:

ax1=sns.displot(df_2013['DATE'].sort_values(),stat="density")
ax2=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax1.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))
ax2.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))

plt.show()

thanks for helping

Body:
You need to define the figure first and add subplots to it.

with sns.axes_style("whitegrid"):
    fig = plt.figure(figsize=(15,10))
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)

    ax1.plot(df1['Column1'])
    ax2.plot(df2['Column1'])

This way you can also plot on the same axis and overlay your plots if you want to. Or you can make plots align under each other in seperate subplots.

Here is an example of superimposed distplots that might be useful to you.

fig = plt.figure(figsize=(7.5,7.5))
ax1 = fig.add_subplot(211)
sns.distplot(Fnormal,ax = ax1, label="Normal Distribution from Filter");
sns.distplot(FilteredReturns, ax =ax1, label="Filtered Returns");
ax1.set_title('Comparison of Filtered Returns and Normal Distribution')
ax1.legend()


问:
Spring Cloud function cannot read function definition from Message header
I've created an AWS Lambda based Spring Cloud Function with multiple functions and it works fine when I define exactly one "spring_cloud_function_definition" environment variable in the AWS Lambda Configuration panel. These functions' input and output is a Message<?>, so the payload and http headers can be accessed runtime as well.

I'd like to use this AWS Lambda function in different API Gateway methods, so for example:

/item [POST] -> saveItem should be called

/item [DELETE] -> deleteItem should be called

... and so on...

https://cloud.spring.io/spring-cloud-static/spring-cloud-function/3.0.0.RC1/reference/html/spring-cloud-function.html#_function_catalog_and_flexible_function_signatures

I found this documentation on Spring.io which says it's feasible:

If the input argument is of type Message<?>, you can communicate routing instruction by setting one of spring.cloud.function.definition or spring.cloud.function.routing-expression Message headers. For more static cases you can use spring.cloud.function.definition header which allows you to provide the name of a single function (e.g., …definition=foo) or a composition instruction (e.g., …definition=foo|bar|baz)

So the following test event should run in AWS Lambda without any failure:

{
"method": "POST",
"body": "{ "key" : "value" }",
"headers": {
"spring.cloud.function.definition": "saveItem"
}
}

but of course it throws an exception:

```<code> No function defined: java.lang.IllegalStateException
 java.lang.IllegalStateException: No function defined
    at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.apply(AbstractSpringFunctionAdapterInitializer.java:187)
    at org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler.handleRequest(SpringBootRequestHandler.java:51)
    at org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler.handleRequest(SpringBootApiGatewayRequestHandler.java:140)
    at org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler.handleRequest(SpringBootApiGatewayRequestHandler.java:43)
</code>```

I've tried many configurations (application.properties, AWS Lambda env property, header, etc.) but nothing happened:

spring.cloud.function.routing-expression=headers.function_name

setting spring.cloud.function.definition=saveItem

What could be the problem? What is the best configuration in this case? Any help would be appreciated!

Used technologies:

Cloud: AWS

Cloud components: Lambda + API Gateway

AWS Lambda handler class: org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler

AWS Lambda input and output events: APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent

Java: 8

Spring Cloud Function version: 3.0.6.RELEASE

答:
I've updated to v3.1.3 and switched to FunctionInvoker and I've added the function definition to the request template mapping header, and it worked fine.

Anyways, thanks for the help. :)

Body:
I've created an AWS Lambda based Spring Cloud Function with multiple functions and it works fine when I define exactly one "spring_cloud_function_definition" environment variable in the AWS Lambda Configuration panel. These functions' input and output is a Message<?>, so the payload and http headers can be accessed runtime as well.

I'd like to use this AWS Lambda function in different API Gateway methods, so for example:

/item [POST] -> saveItem should be called

/item [DELETE] -> deleteItem should be called

... and so on...

https://cloud.spring.io/spring-cloud-static/spring-cloud-function/3.0.0.RC1/reference/html/spring-cloud-function.html#_function_catalog_and_flexible_function_signatures

I found this documentation on Spring.io which says it's feasible:

If the input argument is of type Message<?>, you can communicate routing instruction by setting one of spring.cloud.function.definition or spring.cloud.function.routing-expression Message headers. For more static cases you can use spring.cloud.function.definition header which allows you to provide the name of a single function (e.g., …definition=foo) or a composition instruction (e.g., …definition=foo|bar|baz)

So the following test event should run in AWS Lambda without any failure:

{
"method": "POST",
"body": "{ "key" : "value" }",
"headers": {
"spring.cloud.function.definition": "saveItem"
}
}

but of course it throws an exception:

 No function defined: java.lang.IllegalStateException
 java.lang.IllegalStateException: No function defined
    at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.apply(AbstractSpringFunctionAdapterInitializer.java:187)
    at org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler.handleRequest(SpringBootRequestHandler.java:51)
    at org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler.handleRequest(SpringBootApiGatewayRequestHandler.java:140)
    at org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler.handleRequest(SpringBootApiGatewayRequestHandler.java:43)

I've tried many configurations (application.properties, AWS Lambda env property, header, etc.) but nothing happened:

spring.cloud.function.routing-expression=headers.function_name

setting spring.cloud.function.definition=saveItem

What could be the problem? What is the best configuration in this case? Any help would be appreciated!

Used technologies:

Cloud: AWS

Cloud components: Lambda + API Gateway

AWS Lambda handler class: org.springframework.cloud.function.adapter.aws.SpringBootApiGatewayRequestHandler

AWS Lambda input and output events: APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent

Java: 8

Spring Cloud Function version: 3.0.6.RELEASE


问:
how to install cronie that requires dailyjobs
I'm installing HDP 2.6 on centos 6(no internet access on that machine) and its required redhat-lsb-core->crontabs->cronie->dailyjobs.
I googled for dailyjobs (cronie-anacron), but yum localinstall says:

needs cronie = 1.4.4-16.el6_8.2.

This is vicious circle.
Please help me find out how to localinstall cronie

答:
Install cronie and cronie-anacron at same time. They have dependencies crossed.

rpm -i cronie-xxxx.rpm cronie-anacron-xxxx.rpm


问:
Receive numbers till the input is number that % 7 is without remainder
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

```<code>let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }
</code>```

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

答:
```<code>let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        if(num % 7 == 0) {
        break;
    } else {
        num = +prompt("give us a number")
    }
    } else if (num < 0) {
        document.write("negative ")
        if(num % 7 == 0) {
        break;
    } else {
        num = +prompt("give us a number")
    }
    } else if (num === 0) {
        document.write("zero ")
        if(num % 7 == 0) {
        break;
    } else {
        num = +prompt("give us a number")
    }
    }
}
</code>```

Body:
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?


问:
Sharded MongoDb collection with ~1 million records - Aggregation $group is
I am using Mongo Atlas as a service. We have a collection of around 1 million records. I have sharded the collection. Now the aggregation query is not returning the correct data.

Why $group is only returning 100k records?

Total Documents in the collection: 882496

Documents Count by $count: 882496

Documents Count by $group: 100,000

Connection string: mongodb+srv://name:password@cluster0.ohw5a.mongodb.net/dbname?retryWrites=true&w=majority

答:
The connection string you have mentioned in the answer corresponds to a replica set - which in a sharded environment corresponds to ONE SHARD, which is clustered for HA.

Hence the count is returning the count of documents that exists on that shard itself.

Connect to mongos and then run the query. It should work just fine.


问:
How to Add Horizontal Scrollbar and Vertical Scrollbar to a Paginated Data Table in Flutter for Desktop
```<code>Container(
                    height: MediaQuery.of(context).size.height,
                    width: 2000,
                    // This padding value of 200 is not auto calculated, it is based on where the table ends,
                    // If table becomes much more highted then, this value should be changed manually by the developer.
                    padding: const EdgeInsets.fromLTRB(0, 40, 10, 200),
                    //If there is no cleaner way to add scrollbars to paginated data table then
                    //please suggest a way to get this value automatically.
                    decoration: BoxDecoration(
                      color: Colors.blue.shade200,
                    ),
                    child: AdaptiveScrollbar(
                        controller: verticalScroll,
                        width: width,
                        scrollToClickDelta: 75,
                        scrollToClickFirstDelay: 200,
                        scrollToClickOtherDelay: 50,
                        sliderDecoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(5)),
                        ),
                        sliderActiveDecoration: BoxDecoration(
                          color: Colors.grey.shade300,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(5)),
                        ),
                        underColor: Colors.transparent,
                        child: AdaptiveScrollbar(
                            underSpacing: EdgeInsets.only(bottom: width),
                            controller: horizontalScroll,
                            width: width,
                            position: ScrollbarPosition.bottom,
                            sliderDecoration: BoxDecoration(
                              color: Colors.grey.shade300,
                              borderRadius:
                                  const BorderRadius.all(Radius.circular(5)),
                            ),
                            sliderActiveDecoration: BoxDecoration(
                              color: Colors.grey.shade500,
                              borderRadius:
                                  const BorderRadius.all(Radius.circular(5)),
                            ),
                            underColor: Colors.transparent,
                            child: SingleChildScrollView(
                                controller: horizontalScroll,
                                scrollDirection: Axis.horizontal,
                                child: SingleChildScrollView(
                                    clipBehavior: Clip.none,
                                    controller: verticalScroll,
                                    scrollDirection: Axis.vertical,
                                    child: SizedBox(
                                      width: 1520,
                                      child: PaginatedDataTable(
                                        sortAscending: isAscending,
                                        sortColumnIndex: sortColumnIndex,
                                        arrowHeadColor: Colors.black,
                                        source: ErpInventoryDataSource(
                                            erpInventoryList),
                                        columns: <DataColumn>[
                                          DataColumn(
                                              label:
                                                  const Text('Inventory Id '),
                                              onSort: doColumnSort),
                                          DataColumn(
                                              label:
                                                  const Text('Inv Location '),
                                              onSort: doColumnSort),
                                          DataColumn(
                                              label: const Text('Inv Date '),
                                              onSort: doColumnSort),
                                          DataColumn(
                                              label: const Text('Inv Qty '),
                                              onSort: doColumnSort),
                                          DataColumn(
                                              label: const Text('Inv Min Qty '),
                                              onSort: doColumnSort),
                                          DataColumn(
                                              label: const Text('Inv Cost '),
                                              onSort: doColumnSort),
                                          const DataColumn(
                                            label: Text(
                                              'Edit/Delete',
                                              //style: Theme.of(context).textTheme.headline4,
                                            ),
                                          ),
                                        ],
                                        columnSpacing: 100,
                                        horizontalMargin: 30,
                                        rowsPerPage: 5,
                                        showFirstLastButtons: showFLButtons,
                                        //showCheckboxColumn: false,
                                      ),
                                    )))))),
</code>```

答:
Wrap it in a ScrollBar like so:

```<code>Scrollbar(
 child: Scrollbar(
   scrollbarOrientation: ScrollbarOrientation.bottom,
 ),
 chid: ...
),
</code>```

Body:
Wrap it in a ScrollBar like so:

Scrollbar(
 child: Scrollbar(
   scrollbarOrientation: ScrollbarOrientation.bottom,
 ),
 chid: ...
),


问:
Unconstrained Optimization using Gradient and (sparse) Hessian
I'm looking for a C++ optimization package that can do multivariate unconstrained optimization using gradient and Hessian information.  I'm doing it now in Matlab using fminunc with the 'GradObj', 'Hessian', and 'HessPattern' options.  My Hessian is very sparse so a package that takes that into account would be preferable.

Are there any alternatives to Matlab for this?  Open-source or closed-source are both fine.  C++ is preferable but I'm flexible.

答: As I understand, what you need is an efficient linear algebra library. Consider, for example, uBLAS</p>

OwnerDisplayName: eglaser


问:
How do I hide certain fields from different templates in 2sxc apps using Formulas?
I have an App called "Features"

In Features, I have these fields:

Heading

Text

Image

The app has two separate razor templates. One of the templates displays an image, and the other one does not.

How can I hide the "Image" field from Template B, but still display it in Template A? Is this possible with Formulas? If so, how?

答:
Yes, this can be done with formulas ;)
Best check out the current Content Templates, the basic-content (text/image) templates have exactly this implemented.

If you open it from a template which doesn't show images, the images-field is hidden (but the editor can reactivate it). So this is quite sophisticated, you can also do simpler implementations.

Basically the steps are:

Create an ephemeral field which just serves as a temporary variable to determine if it should be shown by default or not - we usually call it something like VarShowImage - probably default to true (so if it's not set, it's true when the form loads) https://docs.2sxc.org/basics/data/fields/ephemeral.html

In the toolbar where it should be hidden, prefill this like VarShowImage=false

On the field which should be hidden, create a formula to control visible based on this field


问:
Regular expression check for special character or number
I have such regular expression which checked for at least one special character in the string:

```<code>^(.*[^0-9a-zA-Z].*)$
</code>```

But how could i change this one to check for at least one special character or at leas one number in the string?

答: you can use the Expresso, it is a smart tool for generate RegExps Expresso</p>

Body:
I have such regular expression which checked for at least one special character in the string:

^(.*[^0-9a-zA-Z].*)$

But how could i change this one to check for at least one special character or at leas one number in the string?


问:
Deploy with Docker Compose on AWS ECS with GitHub Actions
I recently started experimenting with ECS, Docker Compose, and context and it's really interesting. I have managed to deploy and host a compose-file through my terminal using docker compose up and ecs-context, but I would also like to automate this through something like Github actions.

I'm struggling to see how one would set that up, and I have yet to find a guide for it.

Are there any good resources for researching this further? What would be the alternate or maybe even better way of doing CI/CD on AWS through Github?

答:
I moved away from using Docker Compose and just wrote the CloudFormation templates manually. Docker Compose still has some limitations that require quirky workarounds.

But for anyone wondering how I approached this before moving away from it (including GHA caching):

name: Deploy with Docker Compose

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout source code
        uses: actions/checkout@v2

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_REGION }}

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v1

      - name: Setup Buildx
        id: buildx
        uses: docker/setup-buildx-action@v1

      - name: Build and push <YOUR_IMAGE>
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          cache-from: type=gha,scope=<YOUR_IMAGE>
          cache-to: type=gha,scope=<YOUR_IMAGE>
          tags: |
            ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY }}:<YOUR_IMAGE>-${{ github.sha }}
            ${{ steps.login-ecr.outputs.registry }}/${{ secrets.ECR_REPOSITORY }}:<YOUR_IMAGE>-latest

      - name: Install Docker Compose
        run: curl -L https://raw.githubusercontent.com/docker/compose-cli/main/scripts/install/install_linux.sh | sh

      - name: Docker context
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_ACCOUNT_ID: ${{ secrets.AWS_ACCOUNT_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          AWS_REGION: ${{ secrets.AWS_REGION }}
          ECR_REPOSITORY: ${{ secrets.ECR_REPOSITORY }}
          GITHUB_SHA: ${{ github.sha }}
        run: |
          docker context create ecs ecs-context --from-env
          docker --context ecs-context compose up
```


问:
Where would I put external API call code in my rails project?
I have a rails project that has two models Author and Book. They have a many to many relationship. I am planning to create two controllers Authors and Books.

Now lets say I have an external API making the call ex: '/authors/{#author_id}' I want to return the author along with all book information for that particular author. Where would I place this external API code? In the case of the above example would I just place the code along with the Authors controller that is used by my app or do I place the external API code else where to distinguish between external API code and code used internally by my app?

答: You can create service for that, here is a more info aboiut this pattern: https://blog.appsignal.com/2020/06/17/using-service-objects-in-ruby-on-rails.html and https://www.toptal.com/ruby-on-rails/rails-service-objects-tutorial</p>


问:
How to change between iframes in Selenium and Python
I was trying to understand how to change between iframes in selenium webdriver, but I could not figure it out.
In the image ahead, is the iframe that I want to switch to:

Snapshot:

答:
In order to switch to the iframe you can use code like this:

driver.switch_to.frame(driver.find_element_by_css_selector("//iframe[@title='PowerBi Report Viewer']"))
```
<p>When finished working inside the iframe you will have to switch back to the default content with</p>
<pre class="lang-py prettyprint-override"><code>driver.switch_to.default_content()
</code>```

Body:
In order to switch to the iframe you can use code like this:

driver.switch_to.frame(driver.find_element_by_css_selector("//iframe[@title='PowerBi Report Viewer']"))

When finished working inside the iframe you will have to switch back to the default content with

driver.switch_to.default_content()