Flutter NoSuchMethodError: The method 'toDate' was called on null

Question: An exception was thrown: NoSuchMethodError: The method 'toDate' was called on null.
Exception:
══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
The following assertion was thrown while dispatching notifications for TextEditingController:
setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in
the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error
can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose()
callback. Another solution is to check the "mounted" property of this object before calling
setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is
retaining a reference to this State object after it has been removed from the tree. To avoid memory
leaks, consider breaking the reference to this object during dispose().

When the exception was thrown, this was the stack:
#0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1137:9)
#1      State.setState (package:flutter/src/widgets/framework.dart:1172:6)
#2      _CommentsState.initState.<anonymous closure> (package:anime_space_app/widgets/comments.dart:33:41)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:308:24)
#4      ValueNotifier.value= (package:flutter/src/foundation/change_notifier.dart:412:5)
#5      TextEditingController.value= (package:flutter/src/widgets/editable_text.dart:154:11)
#6      EditableTextState._value= (package:flutter/src/widgets/editable_text.dart:2161:23)
#7      EditableTextState._formatAndSetValue (package:flutter/src/widgets/editable_text.dart:2540:5)
#8      EditableTextState.userUpdateTextEditingValue (package:flutter/src/widgets/editable_text.dart:2769:5)
#9      RenderEditable._setTextEditingValue (package:flutter/src/rendering/editable.dart:735:27)
#10     RenderEditable._setSelection (package:flutter/src/rendering/editable.dart:755:5)
#11     RenderEditable.selectPositionAt (package:flutter/src/rendering/editable.dart:1974:5)
#12     RenderEditable.selectPosition (package:flutter/src/rendering/editable.dart:1950:5)
#13     TextSelectionGestureDetectorBuilder.onSingleTapUp (package:flutter/src/widgets/text_selection.dart:1158:26)
#14     _TextFieldSelectionGestureDetectorBuilder.onSingleTapUp (package:flutter/src/material/text_field.dart:89:11)
#15     _TextSelectionGestureDetectorState._handleTapUp (package:flutter/src/widgets/text_selection.dart:1511:29)
#16     TapGestureRecognizer.handleTapUp.<anonymous closure> (package:flutter/src/gestures/tap.dart:611:57)
#17     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#18     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:611:11)
#19     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:298:5)
#20     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:269:7)
#21     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
#22     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:443:20)
#23     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#24     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#25     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#26     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#27     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#28     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#32     _invoke1 (dart:ui/hooks.dart:170:10)
#33     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#34     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)

The TextEditingController sending notification was:
  TextEditingController#722ea(TextEditingValue(text: ┤├, selection: TextSelection.collapsed(offset:
  0, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end:
  -1)))
════════════════════════════════════════════════════════════════════════════════════════════════════
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
V/InputMethodManager(21258): Starting input: tba=site.animslash.app ic=io.flutter.plugin.editing.InputConnectionAdaptor@6a46c51 mNaviBarColor -15130582 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager(21258): startInputInner - Id : 0
I/InputMethodManager(21258): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(21258): Input channel constructed: fd=159
D/InputTransport(21258): Input channel destroyed: fd=187
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
D/ViewRootImpl@d406a90[MainActivity](21258): MSG_RESIZED: frame=Rect(0, 0 - 1440, 2960) ci=Rect(0, 84 - 0, 1032) vi=Rect(0, 84 - 0, 1032) or=١
D/ViewRootImpl@d406a90[MainActivity](21258): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x1
surface={valid=true 497100464128} changed=false
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not
mounted)

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not
mounted)
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not
mounted)
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not
mounted)
D/ViewRootImpl@d406a90[MainActivity](21258): ViewPostIme pointer 0
D/ViewRootImpl@d406a90[MainActivity](21258): ViewPostIme pointer 1

Another exception was thrown: NoSuchMethodError: The method 'toDate' was called on null.

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not
mounted)
I/TextInputPlugin(21258): Composing region changed by the framework. Restarting the input method.
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
V/InputMethodManager(21258): Starting input: tba=site.animslash.app ic=io.flutter.plugin.editing.InputConnectionAdaptor@67a2caf mNaviBarColor -15130582 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager(21258): startInputInner - Id : 0
I/InputMethodManager(21258): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(21258): Input channel constructed: fd=160
D/InputTransport(21258): Input channel destroyed: fd=159
W/IInputConnectionWrapper(21258): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(21258): getTextBeforeCursor on inactive InputConnection
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
I/chatty  (21258): uid=10334(site.animslash.app) identical 2 lines
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

Another exception was thrown: NoSuchMethodError: The method 'toDate' was called on null.

Source Code:
class Comments extends StatefulWidget {   Comments({this.title});   final String? title;   @override   State<Comments> createState() =>
_CommentsState(); }

class _CommentsState extends State<Comments> {   @override   void initState() {
    getcurrentuser();
    CommentController.addListener(() => setState(() {}));

    super.initState();   }

  void getcurrentuser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        signinUser = user;
        print(signinUser.email);
      }
    } catch (e) {
      print(e);
    }   }

  @override   Widget build(BuildContext context) {
    final CmID = FirebaseFirestore.instance
        .collection('Comments')
        .doc('${widget.title}')
        .collection('Comments')
        .doc()
        .id;
    return Scaffold(
      backgroundColor: kPrimaryColor,
      body: SafeArea(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              decoration: BoxDecoration(
                color: kBackgroundColor,
                border: Border(
                  top: BorderSide(
                    color: kBackgroundColor,
                    width: 2,
                  ),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: CommentController,
                        validator: (val) {
                          if (val!.isEmpty || val.length <= 2) {
                            return "الرجاء ادخال تعليق صحيح";
                          } else {
                            return null;
                          }
                        },
                        style: TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.comment, color: Colors.white),
                          labelText: 'ادخل تعليقك',
                          labelStyle: TextStyle(color: Colors.white),
                          prefixStyle: TextStyle(color: Colors.white),
                          iconColor: Colors.blue,
                          contentPadding: EdgeInsets.symmetric(
                            vertical: 10,
                            horizontal: 20,
                          ),
                          prefixIconColor: Colors.blue,
                          suffixIcon: CommentController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  splashRadius: 22,
                                  onPressed: () => CommentController.clear(),
                                  icon: Icon(Icons.close),
                                ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                          ),
                          focusColor: Colors.blue,
                          hoverColor: Colors.blue,
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                    TextButton(
                      style: ButtonStyle(),
                      onPressed: () async {
                        if (CommentController.text.isEmpty ||
                            CommentController.text.length < 3) {
                          Fluttertoast.showToast(
                            msg: 'يجب على تعليقك ان يكون حرفين او اكثر',
                            backgroundColor: kBackgroundColor,
                          );
                        } else {
                          final commentid = FirebaseFirestore.instance
                              .collection('Comments')
                              .doc(widget.title)
                              .collection('Comments')
                              .doc();

                          final json = {
                            'id': commentid.id,
                            'sender': signinUser.displayName,
                            'img': signinUser.photoURL,
                            'time': FieldValue.serverTimestamp(),
                            'text': CommentController.text,
                          };

                          await commentid.set(json);

                          CommentController.clear();
                        }
                      },
                      child: Text(
                        'ارسال',
                        style: TextStyle(
                          color: Colors.blue,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          CommentsStreamBuilder(
            title: '${widget.title}',
          ),
        ],
      )),
    );   } }

class CommentsLine extends StatelessWidget {
  CommentsLine(
      {required this.time,
      this.title,
      this.img,
      this.text,
      this.sender,
      required this.isMe});
  final String? title;
  final Timestamp time;
  final String? sender;
  final String? text;
  final bool isMe;

  final String? img;

  @override
  Widget build(BuildContext context) {
    DateTime minAgo = DateTime.now().subtract(const Duration(minutes: 1));
    DateTime secAgo = DateTime.now().subtract(const Duration(seconds: 1));
    DateTime dayAgo = DateTime.now().subtract(const Duration(days: 1));
    DateTime monAgo = DateTime.now().subtract(const Duration(days: 30));
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8), color: kBackgroundColor),
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      '$sender',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      timeago.format(time.toDate(), locale: 'ar'),
                      style: TextStyle(color: Colors.white70, fontSize: 12),
                    )
                  ],
                ),
                SizedBox(
                  width: 10,
                ),
                CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage('$img'),
                ),
              ],
            ),
            SizedBox(
              height: 8,
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '$text',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CommentsStreamBuilder extends StatelessWidget {
  CommentsStreamBuilder({this.title});
  final String? title;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore
          .collection('Comments')
          .doc('$title')
          .collection('Comments')
          .orderBy('time')
          .snapshots(),
      builder: (context, snapshot) {
        List<CommentsLine> commentsWidget = [];

        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: kBackgroundColor,
            ),
          );
        }
        if (snapshot.data?.docs.isEmpty != false) {
          return Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/cry.gif',
                  height: 110,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  "لاتوجد تعليقات",
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          );
        }
        final messages = snapshot.data!.docs.reversed;
        for (var message in messages) {
          final messagetext = message.get('text');
          final messgaesender = message.get('sender');
          final messgaeimg = message.get('img');
          final datatime = message.get('time');
          final currentUser = signinUser.displayName;

          final commentWidget = CommentsLine(
            sender: messgaesender,
            time: datatime,
            img: messgaeimg,
            text: messagetext,
            isMe: currentUser == messgaesender,
            title: title,
          );
          commentsWidget.add(commentWidget);
        }

        return Expanded(
          child: ListView(
            reverse: false,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
            children: commentsWidget,
          ),
        );
      },
    );
  }
}

Comment: Could you add the code of the file where the error occurred - `_CommentsState`?
Comment: Where do I get it?
Comment: You Mean This?

  void initState() {
    getcurrentuser();
    CommentController.addListener(() => setState(() {}));

    super.initState();
  }
Comment: I added it """"
Answer: You need to check if time is null or not. check the code below.
class Comments extends StatefulWidget {   Comments({this.title});   final String? title;   @override   State<Comments> createState() =>
_CommentsState(); }

class _CommentsState extends State<Comments> {   @override   void initState() {
    getcurrentuser();
    CommentController.addListener(() => setState(() {}));

    super.initState();   }

  void getcurrentuser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        signinUser = user;
        print(signinUser.email);
      }
    } catch (e) {
      print(e);
    }   }

  @override   Widget build(BuildContext context) {
    final CmID = FirebaseFirestore.instance
        .collection('Comments')
        .doc('${widget.title}')
        .collection('Comments')
        .doc()
        .id;
    return Scaffold(
      backgroundColor: kPrimaryColor,
      body: SafeArea(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              decoration: BoxDecoration(
                color: kBackgroundColor,
                border: Border(
                  top: BorderSide(
                    color: kBackgroundColor,
                    width: 2,
                  ),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: CommentController,
                        validator: (val) {
                          if (val!.isEmpty || val.length <= 2) {
                            return "الرجاء ادخال تعليق صحيح";
                          } else {
                            return null;
                          }
                        },
                        style: TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.comment, color: Colors.white),
                          labelText: 'ادخل تعليقك',
                          labelStyle: TextStyle(color: Colors.white),
                          prefixStyle: TextStyle(color: Colors.white),
                          iconColor: Colors.blue,
                          contentPadding: EdgeInsets.symmetric(
                            vertical: 10,
                            horizontal: 20,
                          ),
                          prefixIconColor: Colors.blue,
                          suffixIcon: CommentController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  splashRadius: 22,
                                  onPressed: () => CommentController.clear(),
                                  icon: Icon(Icons.close),
                                ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                          ),
                          focusColor: Colors.blue,
                          hoverColor: Colors.blue,
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                    TextButton(
                      style: ButtonStyle(),
                      onPressed: () async {
                        if (CommentController.text.isEmpty ||
                            CommentController.text.length < 3) {
                          Fluttertoast.showToast(
                            msg: 'يجب على تعليقك ان يكون حرفين او اكثر',
                            backgroundColor: kBackgroundColor,
                          );
                        } else {
                          final commentid = FirebaseFirestore.instance
                              .collection('Comments')
                              .doc(widget.title)
                              .collection('Comments')
                              .doc();

                          final json = {
                            'id': commentid.id,
                            'sender': signinUser.displayName,
                            'img': signinUser.photoURL,
                            'time': FieldValue.serverTimestamp(),
                            'text': CommentController.text,
                          };

                          await commentid.set(json);

                          CommentController.clear();
                        }
                      },
                      child: Text(
                        'ارسال',
                        style: TextStyle(
                          color: Colors.blue,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          CommentsStreamBuilder(
            title: '${widget.title}',
          ),
        ],
      )),
    );   } }

class CommentsLine extends StatelessWidget {
  CommentsLine(
      {required this.time,
      this.title,
      this.img,
      this.text,
      this.sender,
      required this.isMe});
  final String? title;
  final Timestamp time;
  final String? sender;
  final String? text;
  final bool isMe;

  final String? img;

  @override
  Widget build(BuildContext context) {
    DateTime minAgo = DateTime.now().subtract(const Duration(minutes: 1));
    DateTime secAgo = DateTime.now().subtract(const Duration(seconds: 1));
    DateTime dayAgo = DateTime.now().subtract(const Duration(days: 1));
    DateTime monAgo = DateTime.now().subtract(const Duration(days: 30));
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8), color: kBackgroundColor),
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      '$sender',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                     time != null ?  timeago.format(time.toDate(), locale: 'ar': ""), // here check if time is null or not
                      style: TextStyle(color: Colors.white70, fontSize: 12),
                    )
                  ],
                ),
                SizedBox(
                  width: 10,
                ),
                CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage('$img'),
                ),
              ],
            ),
            SizedBox(
              height: 8,
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '$text',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CommentsStreamBuilder extends StatelessWidget {
  CommentsStreamBuilder({this.title});
  final String? title;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore
          .collection('Comments')
          .doc('$title')
          .collection('Comments')
          .orderBy('time')
          .snapshots(),
      builder: (context, snapshot) {
        List<CommentsLine> commentsWidget = [];

        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: kBackgroundColor,
            ),
          );
        }
        if (snapshot.data?.docs.isEmpty != false) {
          return Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/cry.gif',
                  height: 110,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  "لاتوجد تعليقات",
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          );
        }
        final messages = snapshot.data!.docs.reversed;
        for (var message in messages) {
          final messagetext = message.get('text');
          final messgaesender = message.get('sender');
          final messgaeimg = message.get('img');
          final datatime = message.get('time');
          final currentUser = signinUser.displayName;

          final commentWidget = CommentsLine(
            sender: messgaesender,
            time: datatime,
            img: messgaeimg,
            text: messagetext,
            isMe: currentUser == messgaesender,
            title: title,
          );
          commentsWidget.add(commentWidget);
        }

        return Expanded(
          child: ListView(
            reverse: false,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
            children: commentsWidget,
          ),
        );
      },
    );
  }
}

Answer: So the problem could be you do not clear your resources right. Inside the initState method, you have something like this:
@override
void initState() {
  getcurrentuser();

  CommentController.addListener(() => setState(() {})); // This causes the issue

  super.initState();
}

The problem is that the addListener callback is executed even after the _CommentsState is unmounted. Meaning, when you add the listener, you should remove it later as well.
You can do it this way:
class _CommentsState extends State<Comments> {
  @override
  void initState() {
    super.initState(); // Notice I moved this up as well

    getcurrentuser();

    CommentController.addListener(_updateState); // Add listener on init
  }

  @override
  void dispose() {
    CommentController.removeListener(_updateState); // Remove listener on dispose

    super.dispose();
  }

  void _updateState() => setState(() {});

  @override
  Widget build(BuildContext context) {
    ...
  }
}


Authenticating against LDAP with ApacheDS and PHP

Question: I'm wondering how to authenticate against ApacheDS in PHP. I keep getting a "Invalid Credentials" when I try to log on as a user in a group. I can log in as "uid=admin,ou=system" just fine, but if I try "uid=,ou=consumers,ou=system", it returns "Invalid Credentials".
It is important to note that this is not the full DN of the entry. It's more like "uid=...+gn=...+...,ou=consumers,ou=system". I can search and find this value just fine when bound to the administrator and the API account.
How do I bind to a user just to authenticate and retrieve information on them (like the rest of their attributes and the children of their entry? Here's what I'm doing and failing.
<code>$dn = ldap_connect($serveraddress,10389);
$bn = ldap_bind("uid=".$user.",ou=consumers,ou=system");
var_dump($bn);
var_dump(ldap_error($dn);
</code>
Thank you for any help you can provide.
Edit: So I've gotten farther. Why is this a protocol error?
<code>$ds=ldap_connect("192.168.1.126",10389);  // must be a valid LDAP server!
if ($ds) ldap_bind($ds,"uid=apiaccess,ou=system",...);
else die("!Can't connect to server");

$userid = md5($user);
$results = ldap_get_entries($ds,ldap_search($ds,"ou=consumers,ou=system","(uid=".$userid.")"));
$result = $results[0]["dn"];
echo $result;
if ($ds) ldap_bind($ds,$result,$pass);
else die("!Can't connect to server");
var_dump(ldap_error($ds));
</code>
Answer: You need to tell PHP to use LDAPv3.
Before you call ldap_bind, add the following call:
<code>ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
</code>
Comment: Now I'm getting an "invalid credentials" on the first bind and a successful second bind. It's locating the dn just fine, apparently, as an anonymous user. Why is this happening? How do I authenticate `apiaccess` so that I can modify the data later?
Comment: I'm getting similar protocol errors. Mind sharing what you did if you remember any of this?


Porque está dando erro ao tentar compilar o programa com essa biblioteca (IUP)?

Question: Ao incluir uma biblioteca C está dando esse erro ao tentar compilar

<code>||=== Build: Release in iup (compiler: GNU GCC Compiler) ===|
obj\Release\main.o:main.cpp|| multiple definition of `WindowProcedure(HWND__*, unsigned int, unsigned int, long)@16'|
obj\Release\main.o:main.cpp|| first defined here|
obj\Release\main.o:main.cpp|| multiple definition of `WinMain@16'|
obj\Release\main.o:main.cpp|| first defined here|
ld.exe||cannot find -lbgi|
ld.exe||cannot find -liup|
ld.exe||cannot find -liupcontrols|
ld.exe||cannot find -lcd|
ld.exe||cannot find -liupcd|
||=== Build failed: 9 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
</code>

Não é a primeira vez que tenho esse tipo de problema ao tentar usar bibliotecas nos meus programas. Configurei as pastas no linker/compilador, mas não está dando certo. Estou usando o Code Blocks, mas já tentei no Dev-C++ e Netbeans e também tive problemas.
A biblioteca que estou usando é essa e o programa que tentei compilar e esse:
<code>#include <stdlib.h>
#include <iup.h>

int main(int argc, char **argv)
{
  IupOpen(&argc, &argv);

  IupMessage("Hello World 1", "Hello world from IUP.");

  IupClose();
  return EXIT_SUCCESS;
}
</code>
Atualização:
Estou utilizando o Windows 10 x64 com o compilador MingW.
Eu segui o passo-a-passo, coloquei a biblioteca na pasta do compilador e incluí o arquivo de cabeçalho tanto na hierarquia do projeto quanto na configuração do compilador. Apesar disso esta dando esse erro:

<code>"/C/msys/1.0/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/Users/Carlos/Documents/NetBeansProjects/IUP'
"/C/msys/1.0/bin/make.exe"  -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/iup.exe
make.exe[2]: Entering directory `/c/Users/Carlos/Documents/NetBeansProjects/IUP'
mkdir -p dist/Debug/MinGW-Windows
gcc     -o dist/Debug/MinGW-Windows/iup build/Debug/MinGW-Windows/main.o -L/C/MinGW/lib -liup -liupcontrols -lcd -liupcd -lcomctl32 -lole32 -g -I/C/MinGW/include -include /C/MinGW/include/iup.h
build/Debug/MinGW-Windows/main.o: In function `main':
C:\Users\Carlos\Documents\NetBeansProjects\IUP/main.c:6: undefined reference to `IupOpen'
C:\Users\Carlos\Documents\NetBeansProjects\IUP/main.c:8: undefined reference to `IupMessage'
C:\Users\Carlos\Documents\NetBeansProjects\IUP/main.c:10: undefined reference to `IupClose'
collect2.exe: error: ld returned 1 exit status
make.exe[2]: *** [dist/Debug/MinGW-Windows/iup.exe] Error 1
make.exe[2]: Leaving directory `/c/Users/Carlos/Documents/NetBeansProjects/IUP'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/Users/Carlos/Documents/NetBeansProjects/IUP'
make.exe": *** [.build-impl] Error 2
</code>
Comment: Tente dar um título mais descritivo para sua pergunta, pode ser a diferença entre atrair a atenção de quem sabe a resposta, ou não...
Comment: Poste mais detalhes de como você está compilando o código. Este código é o exemplo da documentação do projeto IUP, então deveria funcionar. Observe que você precisa de várias libs, instaladas e com acesso para poder compilar, caso seja compilação em linux.
Comment: Utilizei todas as respostas, mas ainda não consegui resolver. Mas vou continuar tentando. Obrigado a todos pela ajuda.
Answer: Mesmo após feitas alterações no processo de compilação, é possível que o erro persista, pois compiladores são otimizados para alterar os arquivos compilados o mínimo possível. Portanto, arquivos-objeto e linkados (.o, .obj) podem ainda conter erros que já foram corrigidos!
Experimente, após cada mudança, deletar tais arquivos e recompilar do zero, para evitar erros persistentes. Ao superar esse erro, termine a prática.
Answer: Para essa biblioteca funcionar você deve colocar a biblioteca na pasta do compilador e adicionar as configurações que indica no Linker/Compilador...
Olha ai esse passo a passo:
http://webserver2.tecgraf.puc-rio.br/~mgattass/cg/trbDicas/iup/PassoAPassoIUP.html


Number of $2\times2$ invertible matrices

Question: How many $2\times2$ matrices are there that are invertible over $Z_n$?
Hint: You can use Chinese remainder theorem and this formula for $Z_p$ when $p$ is a prime number.
The number of $2\times2$ matrices on $Z_p : (p^2 - 1)(p^2 - p)$
I think that for example for $n = 26$ we have this answer by factorisation $26$ to $2\times13$
$(2^2-1)(2^2-2)(13^2-1)(13^2-13)$
But I can't prove it .
Comment: Chinese remainder theorem?
Comment: @AnginaSeng No force to use it. Any how
Answer: Hints.
Write $n=p_1^{m_1}\cdots p_r^{m_r}$.
1) Convince yourself that the various ring morphisms $\mathbb{Z}/n\mathbb{Z}\to \mathbb{Z}/p_i\mathbb{Z}$ induces a ring morphism
$f:M_2(\mathbb{Z}/n\mathbb{Z})\to \prod_{i=1}^r M_2(\mathbb{Z}/p_i\mathbb{Z})$
2) Using Chinese remainder Theorem, show that $f$ is surjective.
3) Looking at the determinants, justify that if $M_i\in GL_2(\mathbb{Z}/p_i\mathbb{Z})$ for all $i$, then any matrix $M\in M_2(\mathbb{Z}/n\mathbb{Z})$ satisfying $f(M)=(M_1,\ldots,M_r)$ lies in fact in $GL_2(\mathbb{Z}/n\mathbb{Z})$ (use CRT again).
Conclude that $f$ induces a surjective group morphism
$g:GL_2(\mathbb{Z}/n\mathbb{Z})\to \prod_{i=1}^r GL_2(\mathbb{Z}/p_i\mathbb{Z})$
4) Show that $\ker(g)=I_2+M_2 ((p_1\cdots p_r\mathbb{Z})/n\mathbb{Z})$.
5) Deduce the value $\vert \ker(g)\vert$ and $\vert im(g) \vert,$ and deduce the number you are looking for.


How to expand NodeForm so new argument can passed to it

Question: I have a content type called service request, which have some conditional fields that each might appear or disappear based on an other field value called service type.
I have used conditional field and they work just right but for better user experience I want node form to be called using one of the service types.
so I tried to follow this instructions provided by Jaypan to extend NodeForm, but when overriding form function of NodeForm, it leads to Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId()
this is how I used to create $form:
class ServiceBuilderForm extends NodeForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state, $serviceType = NULL) {
    // Added as a fallback in case a developer uses this form without passing
    // $someId:
    if (is_null($serviceType)) {
      $form = [
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => $this->t('Form is missing Service Type which is required'),
      ];
    }
    else {
      $form = parent::form($form, $form_state);
      // Do something with $form and $some_id
    }

    return $form;
  }
}

and in my Controller I have get my form using:
$form = \Drupal::formBuilder()->getForm('\Drupal\{my_module}\Form\ServiceFormBuilder', $serviceType);

Comment: You need a form mode https://drupal.stackexchange.com/questions/230527/how-do-i-load-a-form-with-a-specific-form-display-form-mode and you don't necessarily need a controller https://drupal.stackexchange.com/questions/244898/how-to-utilize-custom-form-modes-to-edit-a-user-entity
Comment: In `\Drupal::formBuilder()->getForm('\Drupal\{my_module}\Form\ServiceFormBuilder', $serviceType);` the class name is not the same used when defining the form class, which is `ServiceBuilderForm`.
Answer: After you have integrated the form class in the entity type as form mode
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('service', 'Drupal\mymodule\Form\ServiceBuilderForm');
}

and invoked the node form in a controller
$form = $this->entityFormBuilder()->getForm($node, 'service');

or without controller directly in a route:
_entity_form: 'node.service'

the entity including the field data is passed to your form
class ServiceBuilderForm extends NodeForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $node = $this->entity;
    if ($node->getType() == 'service_request') {
      $field_value = $node->field_service_type->value;

and you avoid the error from your question that the entity is null.
Comment: thanks for your wonderful answer
Answer: While 4k4 provided a great answer on how to extend an Entity Form and how to instantiate that , for any one who just needs to extend NodeForm class to send new argument to that, they can use a simple code like below :
$node = $this->entityService
  ->getStorage('node')
  ->create(['type' => 'service']);

$form = $this->entityService
  ->getFormObject('node', 'default')
  ->setEntity($node);

$form = $this->myFormBuilder->getForm($form, $questions);//arguments will be passed in form and can be accessed in form using `$form_state->getBuildInfo()['args'][0]`

$form['field_service_type']['widget']['#default_value'] = $rbid;
$form['field_service_type']['widget']['#value'] = $rbid;
$form['#validate'][] = 'my_form_validate';

return [
  'form' => $form,
];

in the code above $this->entityService is an EntityTypeManager object injected to my controller, when I got the usual form object I have set service type field (not recommended cause it is related to widget type).

as mentioned in code as comment arguments passed can be accessed in
form using $form_state->getBuildInfo()['args']

So just in mind that if you need to pass arguments to an EntityForm and you are looking for a simple solution, then this code might help.
Comment: BTW [EntityFormBuilderInterface::getForm()](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityFormBuilderInterface.php/function/EntityFormBuilderInterface%3A%3AgetForm/9.1.x) also accepts arguments as third parameter $form_state_additions. See https://drupal.stackexchange.com/questions/219431/entity-form-additional-arguments


Understanding the radius of convergence under function composition

Question: I am currently working myself into polynomial approximation of functions where you get very useful bounds by viewing them as functions over complex arguments. While doing this I noticed something peculiar I have not been able to wrap my mind around:
Consider the function $$f(z) =\log\exp(z).$$ From my naive point of view, this is equal to $z$ and hence holomorphic on the whole complex plane. But if I look at the function composition I would get that the radius of convergence of the Taylor expansion is only $\pi$ as $z=\pm i\pi$ gives $\log -1$, the argument lies on the negative real axis where we get problems with the logarithm.
How can I resolve this apparent contradiction?
Answer: There is no contradiction. $\log$ is a multivalued function.  $z$ is one of the branches of $\log \exp(z)$ and is holomorphic on the whole complex plane, but it is not the only possibility.  If you use the principal branch of $\log$, which has a branch cut on the negative real axis, then you get a branch of $\log \exp(z)$ that has branch cuts wherever $\exp(z)$ is on the negative real axis ($\text{Im}(z) = i n \pi$ for odd integers $n$).
Comment: I get this point, but I do not see how we get to the branch $z$ from the function composition -- don't I always have to select one of the branches of $\log$ to make the function composition work? Or can I choose a branch of $\log$ depending on $z$?
Comment: Yes, the branch of $\log$ must depend on $z$.  You certainly can't just select a particular branch of $\log$, because $\exp$ is not a one-to-one function.  For example, $\exp(0) = \exp(2\pi i) = 1$, so you need to use $\log(1) = 0$ when the $1$ comes from $\exp(0)$, but $\log(1) = 2 \pi i$ when the $1$ comes from $\exp(2\pi i)$.
Comment: Excellent, I did not know this was "allowed", but then it makes a lot of sense. Thanks!


Does the subspace topology of rationals have the cofinite topology?

Question: Just to be clear, we are talking about the subspace topology of all rational numbers as a subset of $\bf{R}$. The answer is clearly no right? Because every open set in Q is the intersection of open intervals in $\bf{R}$ with Q and their complement are the the remaining rationals which are infinite.
Comment: [Welcome to Math.SE!](//math.meta.stackexchange.com/a/11168/290189) [Please use MathJax.](//math.meta.stackexchange.com/a/4928/290189)  For some basic information about writing math at this site, see [MathJax tutorial and quick reference](//math.meta.stackexchange.com/q/5020/290189) and [equation editing how-to](//math.meta.stackexchange.com/q/1773/290189). Please read [this post](//math.meta.stackexchange.com/a/9960/290189) for writing a good question.
Answer: Yes. With the usual (standard) topology on $\Bbb R,$ the interval $(0,1)$ is open in $\Bbb R.$ So $\Bbb Q\cap (0,1)$ is not empty and is not co-finite in $\Bbb Q$ but it is open in $\Bbb Q.$
Comment: I know what your "yes" means ("The answer is clearly no right?") -  but the answer to the question in the title is "no" ;-)
Comment: I mean yes you are right
Answer: The cofinite topology on any infinite set is not Hausdorff (all non-empty open subsets intersect). A metric space like $\Bbb Q$ in the subspace topology is always Hausdorff. So no. Alternatively, the cofinite topology on an infinite set would also be connected and compact and $\Bbb Q$ is neither.


Erro de sintaxe em chave final

Question: No meu código estão aparecendo os seguintes erros:

Error  1   } expected**
Error  2   Type or namespace definition, or end-of-file expected**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TesteVO;
using System.Data;
using TesteBancoDeDados;
using System.Reflection;

namespace TesteNegocio
{
public class NgcCliente
{
    public NgcCliente()
    {

    }

    public List <VoCliente> ConsutaCliente()
    {
        DataTable tabela = BDOracleCliente.ConsultaCliente();

        /*
        List<VoCliente> teste = tabela.AsEnumerable().Select(m => new VoCliente()
        {
            Codigo = m.Field<string>("Codigo"),
            Nome = m.Field<string>("Nome"),
            Endereco = m.Field<string>("Endereco"),
            Cidade = m.Field<string>("Cidade"),
            RG = m.Field<string>("RG"),
            CPF = m.Field<string>("CPF"),
            DataDeContrato = m.Field<DateTime>("DataDeContrato"),
            ValorMensalidade = m.Field<decimal>("ValorMensalidade"),
            Cancelado = m.Field<bool>("Cancelado")
        }).ToList();
        */

        public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new()
        {
            var dataList = new List<TSource>();

            const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
            var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
                                    select new { Name = aProp.Name,
                                    Type = Nullable.GetUnderlyingType(aProp.PropertyType) ??
                            aProp.PropertyType }).ToList();
            var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
                                        select new { Name = aHeader.ColumnName,
                        Type = aHeader.DataType }).ToList();
            var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList();

            foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
            {
                var aTSource = new TSource();
                foreach (var aField in commonFields)
                {
                    PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
                    var value = (dataRow[aField.Name] == DBNull.Value) ?
                    null : dataRow[aField.Name]; //if database field is nullable
                    propertyInfos.SetValue(aTSource, value, null);
                }
                dataList.Add(aTSource);
            }
            return dataList;
        }

        List<VoCliente> teste = tabela.ToList<VoCliente>();

        //return teste;
    }
}
}

Answer: Este método está dentro de outro método, se tirar ele de dentro e deixar no nível da classe deve resolver:
public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new()

Coloquei no GitHub para referência futura.
É para tirar o corpo todo.
Um método não pode estar dentro de outro, ainda mais público. Em C# 7 é possível ter uma função local dentro de um método, mas ela é privada ao método.
Pelo estilo do código é provável que tenha outros problemas, até de digitação.

Erro de sintaxe em chave final


Logging similarities between vectors with R

Question: I'm trying to write a program that automatically groups similarities between vectors. The vectors are comprised of point coordinates.
For example (assuming X, Y, and Z are numbers):
Data Set 1: [1, 8, X1, X2, 6, X3, X4, 8, 5, 4, 9, 4, Y1, Y2, Y3, Y4, Y5, 1, 5, 7]
Data Set 2: [X1, X2, X3, X4, 6, 3, 5, 4, 3, 6, Y1, Y2, Y3, 7, Y4, Y5, 7, 3, 5, 7]
Data Set 3: [X3, 5, 6, 4, 3, 6, X1, Y3, 3, 5, 6, X4, 2, 6, 7, X2, Y2, 5, 6, X4, Y4]
X1, X2, X3, and X4, and Y1, Y2, Y3, Y4, and Y5 don't match perfectly with each other between Data Set 1 and 2, but they're within very close proximity, and in the same order, unlike the example in Data Set 3.
Is there an algorithm that can do this kind of grouping?
Comment: The question is indeed vague, because you do not define what "similar" means, and that is a very important point. For example are [0.99,1.99] and [1,2] "similar"? Are [1,2,3,4,0] and [1,2,3,4,100000] "similar"? Are non-integer points even possible?
Comment: The match has to be mostly exact. 1 needs to match with another 1, 2 with another 2, and so on, and only allow variation in maybe 1 of the 6 points.
Answer: Have a look at the field of subspace clustering. Also known as Biclustering.
In your example, the two points could be part of a subspace cluster in Dimensions 1,2,3+5, while dimension 4 would be considered irrelevant or "noise" for the cluster.
Subspace clusterings can live with clusters having different relevant dimensions. The main challenge is how to deal computationally with large numbers of attributes. If you have $d$ dimensions, you'd potentially have to check $O(2^d)$ subspaces for clusters. So you can't check all of them, but need clever methods of searching for interesting subspaces.
https://en.wikipedia.org/wiki/Clustering_high-dimensional_data#Subspace_Clustering
You might also want to look into the Curse of dimensionality (e.g. on Wikipedia)
https://en.wikipedia.org/wiki/Curse_of_dimensionality
Comment: Looks very promising. I'll look it up now. Thank you for your reply.
Comment: I've been doing a lot of research into clustering algorithms, and I finally know enough now to fully appreciate this reply. Thank you again, Anony-Mousse.
Answer: @Subtle Array, you're right that the question is vague, but I think it's legitimate to look for a starting point and refine your question through exploration. @Erik's question is one that you will definitely have to address along the way.
R is very good at handling both simultaneous and iterative operations across data sets. You could, for example, calculate the Mahalanobis distance for each of your 5-dimensional points, then calculate the differences between a pair of points, and tell you they are "matched" if the difference is below your threshold.
Or, you could have R do an element-wise difference between two points. This is, anyway, the default behaviour. Once you have a 5-dimensional array of differences, you could tell R to check if the median difference is below your threshold, or if most of the elements are below your threshold.
Reading back over it, my answer sounds vague too. In short, this is certainly a problem that R can solve in lots of ways. If this is the sort of problem you work with regularly, you will be well-rewarded for learning R now.
EDIT:
Given the updates to your question, I think two approaches might be viable. Mahalanobis distance, as I mentioned above, is implemented in the R function "mahalanobis()," which I believe is part of the "stats" library. The function takes a matrix and the corresponding covariance matrix to calculate a set of Mahalanobis scores. For your vector set, each vector will get a single number corresponding to its multidimensional dispersion.
But you could also try the following:
<code>x1=1:10
x2=1:10; x2[c(3,5)]=c(43,3)
x3=1:10; x3[c(5,7)]=c(24,14)

this.list = list(x1,x2,x3)
lapply(this.list, function(x){
sum.differences = unlist((lapply(this.list, function(y){
    sum(abs(x-y))
})))
which.min(sum.differences[sum.differences != 0])
})
</code>
This toy code will find the minimum total distance between any two of your vectors. It's a quick-and-dirty approach, and I'm sure lots of people on this forum could write something much more clever, but I hope it might at least get you going.
Comment: Thank you for your reply. I have text files full of points, whole numbers without decimals. Example: [1, 90, 23, 42, 11, 20, 4, 40, ...], [8, 20, 70, 90, 54, 50, 5, ...] I would like to cluster the patterns between these datasets where there is only minor variation. Example: The program would acknowledge [1, 2, 3, 4, 5, 6] in the first set, and [1, 2, 3, 4, 0, 6] in the second as a pattern, and log both sets of numbers into a text file. I think if I just knew the name(s) of this type of clustering, I'd be able to look it up and research it, and learn how to apply it.
Comment: Are you looking for clustering, in which many points will aggregate together, or simply pairing, in which a point is testing against a single other point? I read your original question as a search for pairs, but perhaps what you're looking for is called "cluster analysis," or as @Anony-Mousse writes, "subspace clustering."
Comment: Mahalanobis distance (gauging similarity of an unknown sample set to a known one) sounds close to what I'm looking for. Biclustering also sounds promising, but I'm still trying to make sense of the definition. I probably need to learn more linear algebra. In short: I'm looking for the name of the algorithm or technique used to automatically group similar patterns, where only 1 or maybe 2 of the elements are different, between 2 data sets. Element order is also a factor. [1, 2, 3, 4, 0, 6] and [1, 2, 3, 4, 5, 6] would be considered a match, but [3, 6, 5, 2, 1, 4] wouldn't.
Comment: I did some research, and updated and simplified my post so that it would be more clear.
Comment: Ash, you've been a great help. Thank you very much!


Bot Framework LUIS ignore specific words

Question: I'm using Bot Framework Composer v2.1.2 and I created an intent "Cancel" with following trigger phrases:

cancel
quit
abort
exit
never mind
forget about it
back

However during conversations when user is answering multiple choice questions (yes/no) LUIS also treats these answers as Cancel intents.
Is there a way to tell LUIS to ignore specific phrases?
I am aware that I could block interruptions for those multiple choice questions but that would impact user experience.
Answer: Have you tried increasing the confidence score like below?

You could also create a 'None' Intent Recognized Trigger try routing the words you want to ignore to it.
Comment: Thanks for answer. For 'Yes' and 'No' LUIS is 91% (0.91) sure it should be 'cancel' so I would have to set the threshold pretty high. If I created a 'None' intent that would kick-in after selecting an answer wouldn't that just make the bot repeat the question and therefore loop? It wouldn't assign the answer to a variable.
Comment: I just tried this on the Core Assistant with Language bot and it was giving me a score of 0.48 for 'No' and so it was ignored. I guess you need to train LUIS properly. You could try the portal.
Comment: I would love to use the portal but according to official bot composer github LUIS used in Composer can't be trained in portal. It crashes. Been there, done that. I will try to operate with trigger words for now. A bit of a pain tbh.


Show that $f(x, y) : = x^y$ is continuous.

Question: Let $f : (0, +\infty) \times \mathbb{R} \to \mathbb{R}$ be the exponential function $f(x, y) : = x^y$ . Show that $f$ is continuous. (Hint: The easiest way to proceed is to write $f(x,y) = \exp(y\ln(x))$ and use the continuity $\exp()$ and $\ln()$.)
I know that $f\oplus g : X \to \mathbb{R}^2$ defined by $f\oplus g(x) = (f(x), g(x))$ is continuous if $f$ and $g$ are continuous, and I also know that the composition of two continuous functions is continuous, and that the product of two continuous functions is continuous.
I was trying to prove the question using these results, but I couldn't manage to do it. I appreciate if you give some hint.
Edit: Suppose that there exists a continuous function $h:(0, \infty) \to \mathbb{R}$ such that $h(x): = y$. Then, $\exp(y\ln(x)) = \exp \circ (h\cdot\ln)(x)$. This allows me to use the properties above, and it shows that  $f(x,y)$ is jointly continuous. But, I am not sure if I can simply argue that there exists a continuous function $h$. If I am not allowed to proceed in this way, how can I use properties to finish the proof?
Comment: With the hint in hand, this amounts to writing $\exp (y \ln x)$ using only direct sums, compositions, and products of continuous functions.
Answer: Now $ g(x)=ln(x),h(y)=y$ both are continuous over specified domains, hence $l(x)=yln(x)$ and $exp(x)$ are also continuous. Applying composition after this gives you the answer.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Sorry it should be $\mathbb{R}^2$.
Answer: Let $\pi_1(x,y) = x$ and $\pi_2(x,y) = y$. These maps are continuous (it's a very simple direct $\epsilon$-$\delta$ argument). Now, $f(x,y) = x^y = \exp(y\ln(x))$ can be expressed using only elementary oprations of product and composition as follows:
\begin{align}
f &= \exp \circ [\pi_2 \cdot (\ln \circ \pi_1)]
\end{align}
(of course on the RHS, we restrict the domain of $\pi_1,\pi_2$ to $(0,\infty)\times \Bbb{R}$). Here,  $\pi_2$ and $\ln\circ\pi_1$ are continuous so their product is also continuous. Hence finally the composition with $\exp$ is also continuous (actually the same argument shows $f$ is $C^{\infty}$; just replace every instance of "continuous" with $C^{\infty}$)


A regression specification problem: what if one control variable is a function of another—does this cause any issues?

Question: Suppose you run a regression:

$y_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \epsilon_i$

but you believe that:

$x_{i1} = f(x_{i2})$

will this cause any issues for your estimation and interpretation of the regression coefficients?
The following source (http://www.swlearning.com/pdfs/chapter/0324289782_3.PDF) on p. 84 states that in a simple regression setting your estimated beta coefficient "measures the sample relationship between $y$ and $x_1$ after $x_2$ has been partialled out" (removed).  My concern, more generally, is that if you have two controls that pick up much of the same variation of $y$—and you choose to include both—then the general effect that they both try to identify upon $y$ may show up as insignificant (since it is—crudely put—split across the two), this while only including one of the two controls could have resulted in a significant identification of the general effect.
Am I wrong in thinking along these lines?  I recognise that omitting a variable that is correlated with both $y$ and a control $x$ results in an omitted variable problem/bias.  I am, however, not sure if the omitted variable problem is still a "bias inducing problem" when we believe that  e.g. $x_{i1} = f(x_{i2})$ holds.
Any thoughts/comments would be much appreciated.
PS: I note that there are several questions on regression specification and general insignificance, but I have not found one that directly addressed my concerns.
Comment: Sounds more like a two-stages least squares or structural equation model problem.
Comment: I think you are talking about polynomial regression, look at the wikipedia page and many many posts here about `polynomial` and `quadratic` for a special common case.
Comment: Reading some more it appears that this is a classic problem of multicollinearity (see: http://en.wikipedia.org/wiki/Multicollinearity).
Answer: If $X_1$ is an exact affine function of $X_2$, $X_1 = \alpha_0+\alpha_1X_2$, then the "problem" is that your regressor matrix will be singular and non-invertible, and so OLS estimation will break down.  But there is a way out, since in reality in such a case you have
$$y= \beta_0 + \beta_1(\alpha_0+\alpha_1x_2) + \beta_2x_2 + u$$
$$\Rightarrow y = \gamma_0 + \gamma_1x_2 + u,\;\; \gamma_0 = \beta_0+\beta_1\alpha_0,\;\; \gamma_1=\beta_1\alpha_1+\beta_2$$
In other words, in such a case you can run a simple regression with only $X_2$ present as regressor, and you will obtain estimates for the $\gamma$ coefficients.
If $f(X_2)$ is not a linear function, in general, no problem arises. In fact very often one sees $f(X_2) = X_2^2$, i.e a regression of the form
$$y= \beta_0 + \beta_1x_2^2 + \beta_2x_2 + u$$
Remember, whether the regression is "linear or not" has to do with whether it is linear in the unknown coefficients, not in the regressors.
Comment: When you say "this is not the case in my application", do you mean "in my case, the $f()$ function is not linear" or "$f()$ is linear, but the software does not give any warning"? And if you mean the second, then how exactly does your software react?
Comment: Thanks Alecos. That is a nice intuitive explanation. As I mentioned in a comment above this seems to be the standard issue of multicollinearity (when f(.) is taken to be linear). However, programs like Stata (to my knowledge) would often give a warning (and drop the variable causing issues) when this happens--I assume due to the invertability issue you mentioned. However, this is not the case in my application. With that said, what is the practical solution here? Do I drop one of the $x's$ from the regression in your example?
Comment: Sorry for not being clear. I mean that f() is not linear since that would have been picked up by the software. I read some more about it and it seems like the problem is a bit like double edged sword in that there is a tradeoff--if I remove a variable then I increase the risk of biased coefficient estimates, while if I keep it in my coefficient estimates will be precise but the standard errors will be large (possibly yielding statistical insignificance where it would otherwise yield significance).I guess my question is: what do people do in practice to resolve this issue?


Response code: 404 while running simple Jmeter Load test

Question: I am new to Jmeter , my manager asked me explore on this tool. Was starting with simple example to put load on website http://184.108.40.206:7001/OESWeb/Login/loginPage.jsp . I have done all necessary setup like proxy etc. While running the same i am getting Response code: 404 error
Below is http request and its results:
Answer: Try recording your test scenario using JMeter's HTTP(S) Test Script Recorder, building a JMeter Test Plan manually is a huge overhead in terms of required time.
The fastest and the easiest way to prepare JMeter for recording is using JMeter Templates feature,

Choose File -> Templates -> Recording from JMeter's main menu and click "Create" button.
Then expand WorkBench -> HTTP(S) Test Script Recorder and click "Start"
Configure your browser to use JMeter as a proxy (given JMeter and browser are running on the same machine use localhost as proxy host and 8888 as proxy port)
Start executing your test scenario in browser - JMeter will capture the requests and convert them into HTTP Request samplers
Comment: I have chosen BadBoy tool for recording purpose as i am facing issues with jmeter's http test script recorder. But the error is same response code 404 at the same page which i mentioned before.


Why does $D \det(I)B=\frac{d}{d t}\det(I+t B)|_{t=0}$ hold?

Question: The following problem is from Taylor's PDE I. I do not get why $D \det(I)B=\frac{d}{d t}\det(I+t B)|_{t=0}$ hold. Since $\det(I)=1$ and $D$ is $n\times n$ matrix, the left side seems to be a matrix, while the right side is clearly a scalar. Could anyone tell me how I should correctly interpret $\det(I)$ in this case?
Comment: The notation is strange.  I assume it means that the directional derivative of $\text{det}$, evaluated at $I$, in the direction of $B$, is equal to ${\text{Tr}} \;B$.
Comment: That makes sense! Thanks for your answer.
Answer: Hoping I'm not completely off-base here!  I think that mjqxxx had it right in his comment, i.e. that $D \det(I)$ refers to the linear map from $M_n(\Bbb C) \to \Bbb C$ which is the derivative of $\det: M_n(\Bbb C) \to \Bbb C$ at the point $I \in M_n(\Bbb C)$; then $D\det(I) B$ makes sense as the directional derivative of $\det$ in the $B$ direction at the point $I$, so that
$D\det(I)B = \dfrac{d}{dt}(\det(I + tB) \mid_{t = 0} \tag{0}$
is in fact a legitimate notation.
Having said these things,  and clearly understanding the symbolism, I must say that I became quite intrigued by the "other question" presented in the body of this post, so I went ahead and answered it as well.
Soooooooo, in case that anyone is interested:
Let $\lambda_i \in \Bbb C$, $1 \le i \le n$, be the $n$ eigenvalues of $B$; note if need be we allow multiple occurances of the same complex number in the list $\lambda_1$, $\lambda_2$, $\ldots$, $\lambda_n$ to accommodate repeated eigenvalues of $B$.  Bearing this convention in mind, we recall that the determinant of a complex matrix is the product of its eigenvalues; we have
$\det(B) = \prod_1^n \lambda_i.  \tag{1}$
We next observe that, for any complex square matrix $C$ and any eigenvalue $\mu$ of $C$, with eigenvector $v \ne 0$,
$Cv = \mu v, \tag{2}$
for any complex numbers $a, b \in \Bbb C$ we have
$(aC + bI)v = aCv + bIv = a\mu v + bv = (a\mu + b)v; \tag{3}$
that is,  the eigenvalues of $C$ themselves are transformed in accord with the linear mapping $C \mapsto aC + bI$,
whilst the eigenvectors are unaffected; furthermore, if $v$ is a generalized eigenvector, that is
$Cv - \mu v = w, \tag{4}$
where $w \ne 0$ is also a generalized eigenvector, then
$(aC + bI)v - (a\mu + b)v = aCv + bv - a\mu v - bv$
$= aCv - a\mu v  = a(Cv - \mu v) = aw; \tag{5}$
for $a \ne 0$, (5) indicates that $v$ is a generalized eigenvector corresponding to eigenvalue $a\mu + b$ of $aC + bI$; these considerations lead to the conclusion that the entire invariant subspace structure of $C$ is preserved under $C \mapsto aC + bI$, provided that $a \ne 0$; thus the multiplicities of the transformed eigenvalues $a\mu + b$ are the same as those of the original $\mu$.
We apply the above remarks to the matrix $B$; it follows that the eigenvalues of $I + tB$ are precisely the numbers $1 + t\lambda_i$; thus
$\det(I + tB) = \prod_1^n (1 + t\lambda_i). \tag{6}$
The product on the right-hand side of this equation may be expanded in terms of the elementary symmetic polynomials $\sigma_k(t\lambda_1, t\lambda_2, \ldots, t\lambda_n)$ in the $n$ quantities $t\lambda_i$, yielding
$\det(I + tB) = \prod_1^n (I + t\lambda_i) = \sum_0^n \sigma_k(t\lambda_1, t\lambda_2, \ldots, t\lambda_n); \tag{7}$
a detailed proof of (7) may be found in my answer to this question.  Each $\sigma_k(t\lambda_1, t\lambda_2, \ldots, t\lambda_n)$ is in fact a homogeneous polynomial of degree $k$ in the $\lambda_i$; thus (7) becomes
$\det(I + tB) = \prod_1^n (I + t\lambda_i) = \sum_0^n t^k \sigma_k(\lambda_1, \lambda_2, \ldots, \lambda_n)$
$= 1 + t\sigma_1(\lambda_1, \lambda_2, \ldots, \lambda_n) + t^2\sigma_2(\lambda_1, \lambda_2, \ldots, \lambda_n) + \ldots + t^n\sigma_n(\lambda_1, \lambda_2, \ldots, \lambda_n); \tag{8}$
it follows immediately from (8) that
$\dfrac{d}{dt}(\det(I + tB) \mid_{t = 0} = \sigma_1(\lambda_1, \lambda_2, \ldots, \lambda_n); \tag{9}$
since
$\sigma_1(\lambda_1, \lambda_2, \ldots, \lambda_n) = \sum_1^n \lambda_i = \text{Tr}(B), \tag{10}$
we may combine (9) and (10) to arrive at
$\dfrac{d}{dt}(\det(I + tB) \mid_{t = 0} = \text{Tr}(B), \tag{101}$
the result desired (by Yours Truly in any event).  QED!
Note:  One reason I find this problem so engaging is that I think it the may very well lead to nice proofs of things like Liouville's formula and so forth; I have always found the usual demonstrations (see the wikipedia page I just linked) rather cumbersome. End of Note.
Comment: Eq. (7) looks so interesting! I enjoyed reading your argument in another post where you answered to that question.
Comment: @Aran Komatsuzaki:  I know; it's one of my current obsessions!  It has ***lots*** of applications!   By the way, to what other post do you refer?  The one I linked here?  Anyway, thanks for the "acceptance", and Cheers!
Comment: Yes. The one you linked here :-)
Answer: suppose the eigenvalues of $B$ are $\lambda_1, \lambda_2, \cdots, \lambda_n.$  then  the eigenvalues of $I + tB$ are $1 + t\lambda_1, 1 + t\lambda_2, \cdots, 1 + t\lambda_n.$  we will use the fact that the determinant of a matrix is the product of its eigenvalues.
now we have $$det(I + tB) = (1 + t\lambda_1) (1 + t\lambda_2) \cdots (1 + t\lambda_n) = det(I)+ t(\lambda_1 + \lambda_2 \cdots +\lambda_n) + \cdots  $$
therefore $$\frac{d}{dt}det(I + tB)\big|_{t = 0}  = trace(B).$$
Comment: Thanks for your concise answer!


Custom text/html in custom form module

Question: I am following this tutorial and I've already created my custom form as Drupal 8 module.
I wonder, how to add custom text/html in form? I mean when somebody goes to the path pointed in *.routing.yml, I would like to display not only form fields, but also some intro html/text.
I know the form building is here:
public function buildForm(array $form, FormStateInterface $form_state) {

$form['name_surname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name and surname:'),
  '#required' => TRUE,
);
...
}

But I don't know what kind of entry (or #type) should I insert to get just an custom html/text block between fields or above them all?
Answer:
What kind of entry (or #type) should I insert to get just an custom
  html/text block between fields or above them all?

Item element type provides a display-only form element with an optional title and description.
$form['help'] = [
  '#type' => 'item',
  '#title' => t('Block title'),
  '#markup' => t('Block content'),
];

You may also add arbitrary content to render arrays using the #markup render array key as follows.
$form['text']['#markup'] = t('Some text.');

Comment: This is handy, but beware: it won't work for unrecognized tags. Ex: ``. I haven't figured out a way to do this yet.
Answer: #field_prefix #field_suffix and #description should do the trick. Here's more info about FormElement. I believe you can also set an element to type markup and then use #markup to create an element that's just HTML (see ya.teck's answer).
Comment: #type markup has been removed https://www.drupal.org/node/2036237
Comment: To clarify to those who might not click ya.tect's link, `'#markup' => 'foo'` still exists, you just dont need to specify, '`#type' => 'markup'` anymore.
Answer: With Using markup you can add Html markups into your form.for an instance :
$form['help'] = [
    '#type' => 'markup',
    '#markup' => 'Find out more',
    '#weight' => '3',

];

Comment: https://www.drupal.org/node/2036237 - Not sure if you saw the comment earlier. Although the code will work as type markup will not have any effect.
Comment: Drupal just strips any HTML out of the '#markup' key, anyone know if there's a fix for this?

Custom text/html in custom form module


Client side thumb creation OR Server side?

Question: Hy,
I have two options to choose from:
Client side(with FLASH or Javascript):
 pro: image manipulations occurs on the client side, so no load on the server
 cons: more uploaded data
Server side(Ruby on rails):
 pro: less uploaded data
 cons: image manipulations occurs on the server side, so there are some load and will be queried...
For example, when you upload an image, you will get 4 images: a large image, medium, thumb1, thumb2, so in the case of the client side will be needed to upload the 4 optimized images. For the server side, will be only uploaded 1 optimized image and then manipulated.
What is better and less consuming way?
EDIT:
On server side: I really do not know these details but will be used ruby on rails.
The only thing I wanted to know if is more consuming:
1) load an image with FLASH, optimize it, upload on server, then on server side make 4 thumbs and then save.
OR
2) load an image in FLASH, make 4 thumbs and upload them on server.
The thumb resolutions are still variable, so I cant say the sizes.
Answer: I don't see how you expect to manipulate it client side in a webbrowser unless its some application, anyways image manipulation usually takes place server side. Create a que so everything is organized and works in an organized manner.
Comment: Hy,
On client side with FLASH or (if possible) with just javascript.
Answer: it sounds like you are asking everyone to make your decision for you.  That means you don't have enough information to make a decision yet.  Once you understand the problem, you'll know the right solution.  With the information you provided, any "authoritative" answer would be a guess.
For a client implementation:  How much data must be sent to the client to do the image manipulation (i.e. how big is the application)?  What minimum resources would be required of the client machine?  About how long would developing a proof of concept take?  How large of an image would client upload?  What software would the client have to have already installed?  What operating systems will you support?
In a server implementation: what's the max size image the server would accept for manipulation?  How many images is the server expected to handle?  What kind of load is anticipated?  What are similar applications from which load can be inferred?  How long would it take to create a proof of concept?  What amount of server resources would be necessary to perform the work?How will you prevent one user (or a small group of users) from monopolizing the server's resources, but still fulfill their requests in a reasonable time?
Once the POC is created for one, how long would it take to create a POC for the other? What are the testing costs?  If you have to purchase software, what are those costs?  If you are going to use OSS software, are the licenses acceptable?  Will you be creating a derivative work (and does it matter, given the license)?  Same for closed source software - those have licenses, too.
Comment: Well, for the client side FLASH is kind of universal and it runs on almost every machine.

On server side: I really do not know these details but will be used ruby on rails.

The only thing I wanted to know if is more consuming:
1) load an image with FLASH, optimize it, upload on server, then on server side make 4 thumbs and then save.

OR

2) load an image in FLASH, make 4 thumbs and upload them on server.

The thumb resolutions are still variable, so I cant say the sizes.
Comment: You still have to download your flash app to the browser.  How big will this app be?  Which is more important, given your deployment scenario - server resources or client response time?  Will client uploads be fast enough to prevent the clients from browsing away?

More succinctly: why aren't you creating some basic proof of concept code and testing for yourself?  Especially since you don't seem to know the details of your deployment...


Can you deduce an statement from the two statements "No B is an A" and "Some C are B"

Question: In my textbook it says that there is no statement you could deduce from the above two statements in the title. However in my opinion it would be possible to deduce "Some C are no A" from it.
$$
(\forall B \rightarrow \neg A) \wedge (\exists C \rightarrow B) \Vdash (\exists C \rightarrow \neg A)
$$
Intuitively this would make sense for me and I also did a quick proof with tableau calculus. Now I am not sure if there is an error in my textbook or if I'm missing something. Either I wrongly converted the statements into boolean logic or the entailment is in fact not true.
Comment: "Some C are B" is $\exists x (Cx \land Bx)$
Comment: Having said that, your intuition is correct: we can conclude that $\exists x (Cx \land \lnot Ax)$ (that is: "Some C is not A".
Comment: It's amazing that you can claim to have done a proof using the tableaux calculus when you do not even have syntactically valid premise and conclusion! Learn the basics properly. Since your textbook is so lousy, read "Language, Proof and Logic" instead.
Comment: The textbook's claim is horribly wrong. You can deduce any one of those two statements from those two statements. You can deduce the conjunction of those two statements. You can deduce the disjunction of any one of those two statements with any other statement. You can deduce any tautology from those two statements. There are infinitely many things you can deduce from those two statements. Including the one you indicate.
Answer:
In my textbook it says that there is no statement you could deduce from the above two statements in the title. However in my opinion it would be possible to deduce "Some C are no A" from it.
$$
(\forall B \rightarrow \neg A) \wedge (\exists C \rightarrow B) \Vdash (\exists C \rightarrow \neg A)
$$

"No B is an A" ought to be translated as $$¬∃x \;(Ax\land Bx)\tag1$$ or, equivalently, $$∀x \;(Bx\to¬Ax).$$
"Some C is B" ought to be translated as $$∃x \;(Bx\land Cx)\tag2.$$
"Some C is not A" ought to be translated as $$∃x \;(¬Ax\land Cx)\tag3.$$
Indeed, $(1)$ and $(2)$ together logically entails $(3).$
Answer: "In my textbook it says that there is no statement you could deduce from the above two statements in the title." Really? For a start you can deduce "No A is B" and "Some B are C". Then as @ryang notes, you are right that you can deduce "Some C are not A" [though NB his corrections of your badly misused quantifier symbolism]. You can also deduce "Some C are not both C and A', and "Some C are not both B and A", etc. etc.
So I wonder: does your textbook really make that silly claim you report?


dificuldade para trabalhar com CSS em responsividade

Question: observem minha pagina;
CSS;
@CHARSET "UTF-8";

body {
    margin: 0;
    padding: 0;
}

#topo {
    width: 100%;
    height: 500px;
    background-color: #000000;
    margin: 0 auto;
}

#logo{
    position:relative;
    top:0px;
    border: 2px solid #fff;
    width:400px;
    height:12px;

}
#menu{
    position:relative;
    top:0px;
    border: 2px solid #fff;
    width:400px;
    height:200px;

}

Como faço para deixar um do lado do outro?
Comment: já pensou em utilizar o bootstrap?
Comment: você pode utilizar o sistema de colunas do bootstrap
Comment: Coloca o código HTML também, mas terá que usar `float` ou `display:inline-block`.
Comment: se eu usar float ele não vai ficar responsivo.
Comment: concordo com o uso do bootstrap, até mesmo para você entender melhor o comportamento responsivo... depois você pode criar seu próprio grid system
Comment: esse projeto está configurado para bootstrap, como faço para ficar responsivo?
Comment: Use o grid do bootstrap, é mais fácil e te evita problema na quebra do layout em determinados tipos de telas. Basta só ir adaptando para tuas necessidades.
http://getbootstrap.com/css/
Answer: Como falado pelos comentários, acho está a melhor opção para responsividade:
o Bootstrap funciona com um sistema de grids (grades) para posicionar os elementos na página.
Esse mecanismo funciona como uma espécie de tabela abstrata, e é responsivo (responsive), orientado a dispositivos móveis (mobile first) e se ajusta de acordo com a tela (fluid), quando ela muda de tamanho ou de orientação.

As columns (colunas), no Bootstrap, definem as divisões verticais das
  rows (linhas) do seu layout.
Columns devem estar sempre dentro das rows, e elas definem espaços na
  row para que você coloque os itens visuais ou conteúdos que foram
  projetados.
Então, no Bootstrap, você tem linhas (rows) e colunas (columns) para
  definir um layout. É, exatamente, como uma grade ou matriz (ou
  tabela), porém, utilizando div's com classes.
Para criar uma column você pode criar uma div com os prefixos
  pré-definidos pelo Bootstrap, como no exemplo:

Neste exemplo, temos uma linha (.row) com duas colunas (.col-md-6).
O número seis, no final de cada classe de coluna, define o espaço que
  ela ocupa na linha. Assim, neste exemplo, teríamos a linha (row)
  dividida exatamente no meio por duas colunas, já que usamos o número
  seis.
Os prefixos de colunas servem para indicar em quais tipos de tela a
  coluna vai se manter posicionada como no design principal. Os prefixos
  têm o seguinte padrão:

Sugiro os links: Como usar o grid, Documentação Bootstrap


How to shift a power series to be centered at a?

Question: Let's say that I want to approximate $\sin{(4)}$ Using a the first three non-zero terms of a power series. If I'm centered at $x=0$, I get a bad approximation, as you can see in the image.

How do I get a better approximation, not by adding more terms to the power series, but by finding a different power series centered at $x=4$? If I just use the Taylor Series, the first term would be $\sin{(4)}$, but that defeats the purpose - I can't use $\sin{(4)}$ if I'm trying to approximate $\sin{(4)}$. Thank you!
Comment: Well, you probably don't mean "centered at $x=4$"...you want it to be centered at a value near $4$, a value for which you can compute the power series.  $x=\pi$ isn't a bad start.  Or $x=\frac {5\pi}4$.
Comment: The first term of the Taylor series for $f(x)$ centered at $x=a$ is $f(a)$. In deriving the standard Taylor series for $\sin x$, we use that $\sin 0 = 0$ and that $\cos 0 = 1$. The Taylor series is good for approximating a function in the vicinity of the center, In addition to needing to know the value, it also won't look very nice (or be easy to calculate) if centered at $x=4$. Looking at your graph to see how good 5 terms (two are zero so they are normally left out) approximate $\sin$, I would suggest going for a series centered at $x=\pi$.
Comment: You can shift the sine function by using $\sin(a+h) = \sin(a)\cos(h)+\cos(a)\sin(h)$
Comment: So it's not possible to center it exactly at $x=4$ unless I already know the value of $\sin{(4)}$? So I pick a value close to $4$ that is a know sin value?
Comment: @Gribouillis How does that help? Where would I go from there?
Comment: @user3925803 you can write $\sin(4) = -\sin(4 - \pi)$, which gives you small value of argument (assuming $\pi$ is known). This will the same result as expanding $\sin$ at $x = \pi$. Of course, in both cases it's assumed that $\pi$ is known with good precision - if not, you need either more terms or different approach.
Comment: Closely related and possibly useful: [What does expanding $e^{2x}$ in powers of $\left(x-1\right)$ means?](https://math.stackexchange.com/q/3689743/25554)
Comment: @Gribouillis formula is not wrong, but perhaps a bit to general. I think you can derive all the shifts you need from (multiple applications of) the simpler $\sin(-x)=-\sin(x)=\sin(x+\pi)$.
Answer: Per the suggestions in the comments, I have expanded the series around $\pi$. Including terms up through $x^3$ seems to approximate $\sin 4$ pretty well already.
The even-numbered terms are multiples of $\sin \pi = 0$, so I have omitted them from this display.

Interactive hilarity


Why did I get the birthdate in Oracle with an extra zero? How to change my sql?

Question: I wrote the select sql statement in DB SOLO and I can get the result like 2015-09-09 10:48:35, but when I use the java jdbc to get the result, it always returns 2015-09-09 10:48:35.0. And when I try to parse it into date format, I get an error:
java.text.ParseException: Unparseable date: "2015-09-09 10:48:35.0"

How to change my sql? In mysql, I can format it like this:
select date_format(birthday,'%Y-%m-%d %H:%i:%s') birthday from student

Comment: `date_format()` is not a function supported by Oracle.  Are you sure you are not using MySQL?
Comment: @PeterM. `to_date()` does **not** "format" a date. It converts a character value _into_ a date. To _format_ a date you need [`to_char()`](https://docs.oracle.com/database/121/SQLRF/functions216.htm#SQLRF06129)
Comment: Oracle's string formatting of dates is something like:
select to_date(birthday, 'YYYY-MM-DD HH24:MI:SS') birthday from student

---- http://www.techonthenet.com/oracle/functions/to_date.php
Comment: In oracle its to_char and the extra zero are the milliseconds, i presume
Comment: How are you getting the date value from the `SELECT` into the variable that you are trying to parse?  It looks like you are selecting the date as a string and then telling Java to convert it back to a date.  But you shouldn't need to do that (and you shouldn't do it).  You should be getting the date value from the database right into a Java `Date` object.    Date format shouldn't enter into it.
Answer: Use TO_CHAR
SELECT TO_CHAR(birthday, 'YYYY-MON-DD HH24:MI:SS') FROM DUAL


Why am I getting org.json.JSONException: Not a primitive array?

Question: I have this function:
fun getFeed(token: String): Result<Array<Post?>, Exception> {
        if (token != "") {
            val (request, response, result) = "https://alles.cx/api/feed"
                .httpGet()
                .header("Authorization", token.toString())
                .response()

            when (result) {
                is Result.Success -> {
                    println("Result success")
                    try {
                        val responseJSON = JSONObject(String(response.data))
                        if (!responseJSON.has("err")) {
                            println("Has no error")
                            var feedArray = arrayOfNulls<Post>(0)
                            println("HERE?")
                            var feed = JSONArray(responseJSON["feed"])   // <-----ERROR HERE
                            println("not here")
                            println("Made to the for")
                            for (i in 0 until feed.length()) {
                                println("For $i")
                                val jsonObject = feed.getJSONObject(i)

                                var imageURL: URL? = null
                                if (jsonObject.has("image")) {
                                    imageURL = URL(jsonObject["image"].toString())
                                }
                                feedArray[i] = Post(
                                    jsonObject.getString("id"),
                                    User(jsonObject.getJSONObject("author").getString("id"), jsonObject.getJSONObject("author").getString("username"), jsonObject.getJSONObject("author").getString("name")),
                                    jsonObject.getString("createdAt"),
                                    jsonObject.getInt("replyCount"),
                                    jsonObject.getInt("score"),
                                    jsonObject.getString("content"),
                                    null,
                                    imageURL,
                                    jsonObject.getInt("vote")

                                )
                                println("Added post $i")
                            }
                            println(feedArray)
                            return Result.Success(feedArray)
                        }
                        else {
                            println("yes error")
                            return Result.Failure(Exception(responseJSON["err"].toString()))
                        }
                    }
                    catch(e: Exception) {
                        return Result.Failure(e)
                    }
                }
                is Result.Failure -> {
                    return Result.Failure(Exception(result.component2()?.localizedMessage))
                }
            }
        }
        else {
            return Result.Failure(Exception("badAuth"))
        }
    }

An error is occurring on this line. I know this because of the print statements that are in the code:
var feed = JSONArray(responseJSON["feed"])   // <-----ERROR HERE

This is what the error that is occurring is.
[Failure: org.json.JSONException: Not a primitive array: class org.json.JSONArray]

This is what the feed object from the get request will look like, just so you have an idea of what it is:
{
    "feed": [
        {
            "type": "post",
            "slug": "equ2ZfaX2UThtkS8DzkXdc",
            "author": {
                "id": "00000000-0000-0000-0000-000000000000",
                "name": "Archie",
                "username": "archie",
                "plus": true
            },
            "content": "I know it's quite inactive here atm. But I'm doing tons of stuff behind the scenes - basically rewriting the entire platform from scratch. Micro will be done by the end of the summer.",
            "image": null,
            "createdAt": "2020-07-30T20:39:23.000Z",
            "score": 5,
            "vote": 0,
            "replyCount": 0,
            "hasParent": false
        }
    ]
}

What could possibly be going wrong here. I am using Fuel for the request, but I don't think that is the problem
Answer: Pretty sure the correct way to get the array would be to do var feed = responseJSON.getJSONArray("feed").  You're implementation calls the JSONArray(Object o) constructor which is meant to be called only for primitive arrays (int[], double[], etc.) as they cannot be effectively typed using generics). Thus the constructor complains as you pass in an object which is not a primitive array.


Project on Simple Groups

Question: I have to give a 15-20 minute presentation on a topic or result dealing with Simple Groups.
Any ideas on what I can look into?
Comment: classification of finite simple groups, Jordan-Hölder thm, examples of simple groups, ... etc
Answer: Title: "Why do we care about simple groups?"
Your goal for this talk would be to convince the audience that understanding simple groups is equivalent to to understanding all finite groups. Why?
First, talk about Jordan-Holder. Note that all groups have a unique set of composition factors up to isomorphism, and that these factors are simple groups.
Second, talk about the Classification. Don't dwell too much on details. Say that there are 4 kinds of simple groups, the first two are easy and familiar: cyclic groups of prime order, alternating groups. Then mention that there are a bunch of families of groups lumped under the name "groups of Lie type," but don't elaborate. Finish with sporadic groups, emphasizing that classifying these took forever and were the difficult part of the Classification theorem, and we that only finished relatively recently.
The third part is the extension problem. Now that we know what the simple groups are, we know all the possible sets of composition factors a group can have.  If we knew how to determine a group up to isomorphism given its set of composition factors, we'd be done with finite group theory. Problem is, composition factors aren't unique- two groups can have the same set (take $\mathbb{Z}_2\times\mathbb{Z}_2$ and $\mathbb{Z}_4$, for example). So where do we go from here? The group extension problem is to answer, given groups $N$ and $M$, what all groups $G$ can occur with $M\unlhd G$ and $G/M\cong N$. If we understood these, then by induction and Jordan-Holder, we'd understand all finite groups.
So, that's why people like 'em.
Comment: Yup, exactly. We'd have a "classification of finite groups."
Answer: Here are a couple of ideas, which could be discussed in tandem.
Composition Series and Extensions - Every finite group has a composition series.  The composition factors are simple and are independent of the chosen series.  This is the Jordan-Holder theorem.  Then, every group can be reconstructed by a series of extensions using its composition factors.  This allows us to view the finite simple groups as the basic building blocks of finite groups, just like prime numbers are the building blocks of the natural numbers.  The one main difference to highlight in this comparison is that "uniqueness of factorization" doesn't hold with finite groups.  For example, the composition factors of the two groups of order $4$ are identical.
Classification of Finite Simple Groups - Perhaps the crown jewel in the theory of finite groups.  The list of finite simple groups is straightforward to write down, but it is fairly surprising that the list is complete (why exactly 26 sporadic groups?).  The proofs of some deep theorems about finite groups are reduced to simple groups (using extensions and composition series), and then the classification allows one to check the result for all of the simple groups.  It would be appropriate to mention Burnside's Theorem and the Feit-Thompson Theorem here, as they are used heavily in the classification.
Answer: Besides the purely group theoretical backing as pointed out by Jared and Alexander Gruber, I would certainly mention Monstrous Moonshine, still a field of active research, where different fields (finite simple groups, modular forms, string theory) come together.

Project on Simple Groups


Is there a regular pentagon with integer area?

Question: Searching for an answer with a regular pentagon to the post   I have unexpectedly the pertinent following question:
is there a regular pentagon with integer sides and integer area?
According to some references in the Web the answer could be affirmative (see this, that, and other where there are "examples" of (side, area)$=(16,440),(24,991),(6,60)$ respectively).
However effective calculation gives, for example with side $24$, the area $990.9949….$ which is obviously not equal to $991$.
I think the precedent examples are approximations and there is not a regular pentagon with integer area but I can not  prove it so far.
Some help or a  counterexample?
Comment: If you start with any regular pentagon $P$, and let $A$ be its area, then for any scalar multiple $rP$ the area is $r^2 A$. So just take $r=\sqrt{A}$ and you get area $1$.
Comment: @fleablood, ...if $a$ is an integer. Why should it be?
Comment: Don't ####ing require people to follow links to understand your question!!!!  If the question is important enough to post than it's important enough to include on the details **in one place**.  Asking me to navigate to another post when I'm trying to help is both rude and lazy.  DONT DO IT!  Now edit this post and state the conditions!!!!
Comment: Integer/rational side as well I assume.
Comment: Presumably, you left out some condition (integer side length, integer vertices, integer something)
Comment: The area of a Pentago is $\frac 1 4 \sqrt{5(5+ 2\sqrt{5})}a^2$.  If $ \sqrt{5(5+ 2\sqrt{5})}$ is irrational $\frac 1 4 \sqrt{5(5+ 2\sqrt{5})}a^2$ will never be an integer for integer a.
Comment: I'm assuming $a$ must be restricted to an integer otherwise the question is trivial.
Comment: @fleablood, no, it is not trivial. For example, the restricttion can be that the verices have integre coordinates.
Comment: You edited the question but did not clarify what conditions you are imposing on the penagon, Piquito.
Comment: @fleablood: your second comment is the reason for which I feel the given "examples" are just approximations and not integers indeed.The constant of degree four, even could be a negation for Lee Mosher's comment. Anyway, if I am wrong I would like a counterexample.
Comment: Well, it depends on conditions.  *Some* conditions must exist otherwise it is trivial. The OP gave examples of (side, area) integer pairs so I presume s/he assumed integer sides.
Comment: Lee's comment anwers the question as you wrote it, Piquito; unless you impose some condition, the question is entirely trivial.
Comment: @MarianoSuárez-Alvarez: the conditions are in the post (hyperlink) from which this question comes: side and area integers
Comment: One of the examples made an assumption that the radius = 5.  I have no friggin' idea why they came up with that.
Comment: First link (this): "So now if we were told the length of the other side,
  we would be in business!
  Say we are told it is about 4 (it's actually more like 4.1291)."  So we can toss that page as utterly useless.  We need to figure out the side and we need to know it *precisely*.  This is is .... garbage.  Next link....
Comment: Second link (that).  Not in english so... but it assumes the side is 6 and the radius is 5.  How it came up with radius 5 ... I have no idea.  By trig we can calculate the radius will be $3/\cos 54 = 5.103...$. Not 5.  So let's toss that.
Comment: This aren't even *close* approximations!
Comment: @fleablood: see gran_chat's answer and be happy. (I have edited for you).
Answer: If we require the pentagon to have integer side length, then the answer is no. The area of a regular pentagon with side length $a$ is
$$5\cdot\left(\frac12a h\right)=\frac54a^2\tan(54^\circ)$$
But $\tan(54^\circ)$ is irrational, because the only rational values of $\tan k\pi/n$ are $0$ and $\pm1$.
Comment: @gran_chat: So, definitely NOT is the answer; I was looking for a maybe  "convenient" irrational radius giving a rational side (there are many examples). Consequently the "examples" in the web deserve well put its quotation marks. Thank you very much.


Preencher os inputs de um iframe

Question: Boa tarde.
Gostaria de saber se é possível preencher os inputs de iframe através de JavaScript.

Sei que name do input do iframe e pensei nisso:

Preencher os inputs de um iframe