text:
Q: Performance penalty for undefined arguments I quite often have optional arguments in functions, but some testing is showing a huge performance hit for them in firefox and safari (70-95%). Strangely, if I pass in the literal value undefined then there is no penalty. What could be happening here? I wouldn't have thought that it was a scope chain issue as they are inherently local to the function. Am I to start passing undefined into every optional argument?
jsPerf: http://jsperf.com/function-undefined-args/2

A: For a function like this:
function threeArgs(x, y, z) {
  return x + y + z;
}

that's called like this:
threeArgs(1, 2, 3);

the optimizer is free to make the choice to generate no code at all.  It's fairly easy for it to determine that there are no side effects, because the function simply references its parameter values and returns the result of a simple expression. Since the return value is ignored, there's no reason for the runtime to do anything at all.
Beyond that, if the code were:
something += threeArgs(1, 2, 3);

the optimizer might decide to generate code roughly equivalent to:
something += 6;

Why? Because the call was made with numeric constants, and it can safely fold those at code generation time. It might be conservative on that, because numbers are weird, but here they're all integers so it could well do this. Even if it didn't, it could safely inline the function:
something += 1 + 2 + 3;

When there's a parameter missing, however, it may be that the optimizers bail out and generate a real function call. For such a simple function, the overhead of the function call could easily account for a large difference in performance.
By using variables instead of constants in a test, and by actually using the return value of the function, you can "confuse" the optimizer and keep it from skipping the call or pre-computing the result, but you can't keep it from inlining.  I still think that your result is interesting for that reason: it exposes the fact that (as of today anyway) those optimizers are sensitive to the way that functions are invoked.

A: I think what could explain the performance difference is the way arguments are passed to a function object: via the arguments object. When not passing any arguments, JS will start by scanning the arguments object for any of the given arguments, when those are undefined, The arguments prototype chain will be scanned, all the way up to Object.prototype. If those all lack the desired property, JS will return undefined. Whereas, passing undefined explicitly, sets it as a property directly on the arguments object:
function foo(arg)
{
    console.log(arguments.hasOwnProperty('0'));
}
foo();//false'
foo('bar');//true
foo(undefined);//true

I gather that's the reason why passing undefined explicitly tends to be faster.


text:
Q: Comma sign in Bibliography I am using
\documentclass[a4paper 12pt]{article}

and
\bibliographystyle{unsrt}

to write a report. The problem i am facing is that latex is not putting comma between the author names in my bibliography. can anyone please help me to sort this problem out?

A: Without a minimal working example your problem is too localized. The following examples shows commas between authors.
\documentclass[a4paper 12pt]{article}

\begin{document}
\cite{whole-collection}

\cite{unpublished-full}
\bibliographystyle{unsrt}
\bibliography{xampl}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: scp /path/to/local/file myusername@server.com creates a new file in local directory? scp was working fine, but now when I do
$ scp /path/to/local/file myusername@servername.com

it doesn't ask for my password, but returns nothing immediately, and a new file named "myusername@servername.com" is created in the directory.
Also, I have not problem ssh to server, it asks for my password and I could log in successfully.
$ ssh myusername@servername.com

I did some configuration to set up VIM as IDE for C++ over the weekend, so I might have messed something? I've also created a new anaconda environment for running Python3, if these information help.

A: You need to tell scp you're copying to a remote, using : and (optionally) a path on the target:
scp /path/to/local/file myusername@servername.com:/path/to/remote

If you just specify : it will use the default path, probably myusername's home directory on servername.com:
scp /path/to/local/file myusername@servername.com:

(Thanks to Stephen Harris for pointing out that the remote path is optional.)

A: By default, scp assumes that you want a local file unless you specify where you want the file on the remote server with :.
For example, scp /path/to/local/file myusername@servername.com:./ will do what you intend: to create a file at the default directory of myusername on servername.com called file with the contents of /path/to/local/file on your computer.

A: Because scp can be used to copy files to a server, or from a server the program uses the presence of the : to determine which way to send.  Without a : there is no hostname and so it assumes both files are local.
So
scp x a@b

will treat both x and a@b as local files.
You don't need to specify a target path, but you do need the :
scp x a@b:

If there's no path specified then it will use the default directory (typically the remote $HOME), same as if you'd specified a@b:.


text:
Q: Controlling Process Name of my Jar I wanted to know is there any way I could control the name the process my jar is starting, i.e,
I created a .jar file in java and whenever I am clicking on it, it is causing a process named javaw.exe and I want to control this name.
I want to do so because when I click on my jar file then if it already running it should stop and a new one should start, i.e., I want to run a new thread  (process) everytime I click on it by stopping the previous one.
If I kill the process named javaw.exe, all processes with name javaw.exe would die (if I am running more than one program) . So, I need to change its name.
Plz help.
Thanks !

A: There's nothing wrong with javaw running.  From the documentation:

The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails for some reason.

Ultimately, javaw runs your program without a console window.  Changing that name could lead to some serious issues later, so you'd want to keep that particular program name.

A: Why reinvent the wheel?  There are already standard ways to prevent two copies of the same program from running.    Typically it involves creating a "flag" file, since filesystems guarantee that directory updates are atomic.  On UNIX-like systems, the file would be /var/run/program-name.pid.  If it already exists, then the second copy will exit with an error.

A: You could setup a controller process, that manages your instances:
First you try to connect to the controller on localhost via tcp/ip at a specific port (your programs "name" from now) and if sucessful, you send a message like 'new instance started' to that controller. If the connection was not sucessful, you start a new controller-thread in the current vm (and send the message again to this thread)
the controller loops, waiting for messages and if one matches 'new instance started', it does what you describe.
such a controller can be built easily using a simple ServerSocket, a small HTTP-server or many other messaging libs.


text:
Q: Definition of differentiability of function of two variables I assume that the reader may be well versed with the various notations of partial derivatives.
My book gives the following definition of differentiability:

If $\Delta f(x,y)$ can be expressed in the form:
$\Delta f(x,y)=f_x(a,b)\ \Delta x + f_y(a,b)\ \Delta y + \varepsilon_1\ \Delta x + \varepsilon_2\ \Delta y$;
where $\varepsilon_1 \rightarrow 0$ and $\varepsilon_2 \rightarrow 0$ as $(\Delta x,\Delta y) \rightarrow (0,0)$;
then $f(x,y)$ is differentiable at $(a,b)$

However my calculation gives:

Provided that $f_x(a,b)$, $f_y(a,b)$ and $f_{xy} (a,b)$ exist,
$\Delta f(x,y)=f_{xy}(a,b)\ \Delta x \Delta y+f_x(a,b)\ \Delta x + f_y(a,b)\ \Delta y + \varepsilon_1\ \Delta x + \varepsilon_2\ \Delta y + \varepsilon_3\ \Delta x \Delta y $
where $\varepsilon_1 \rightarrow 0$, $\varepsilon_2 \rightarrow 0$ and $\varepsilon_3 \rightarrow 0$ as $(\Delta x,\Delta y) \rightarrow (0,0)$

Does this mean if $f_x(x,y)$ is not a function of $y$ , i.e. $f_{xy}(x,y)=0$ i.e. equation $(1)$ is obeyed and therefore $f(x,y)$ is differentiable at $(a,b)$???
In other words, if $f_x(x,y)$ is not a function of $y$, then is $f(x,y)$ is differentiable at $(a,b)$???

The calculation is simple, trivial but a bit lengthy. If the reader feels anything wrong, I can present the calculation

A: As stated in the question, a definition of differentiability is
$$\Delta f(x,y)=f_x(a,b)\ \Delta x + f_y(a,b)\ \Delta y + \varepsilon_1\ \Delta x + \varepsilon_2\ \Delta y \tag{1}\label{eq1}$$
I'm not quite sure how you came up with your calculation of
$$\Delta f(x,y) = f_{xy}(a,b)\ \Delta x \Delta y+f_x(a,b)\ \Delta x + f_y(a,b)\ \Delta y + \varepsilon_1\ \Delta x + \varepsilon_2\ \Delta y + \varepsilon_3\ \Delta x \Delta y \tag{2}\label{eq2}$$
For one thing, why did you choose just $f_{xy}(a,b)$ and not use $f_{y\, x}(a,b)$ as well? Regardless, the $2$ equations are not actually inconsistent in the limiting case as $(\Delta x,\Delta y) \rightarrow (0,0)$. This is because the extra $2$ terms you have are both bounded values multiplied by the second order delta values of $\Delta x \Delta y$ while all of the original values on the right are a multiple of just $\Delta x$ or $\Delta y$.
A related question about this was asked here at First principles derivation of area under a curve giving rise to an unexpected term before taking limits. As the comment there by Andy Walls basically states, when $\Delta x$ and $\Delta y$ become small, then their product becomes extremely small, e.g., $0.0000001 \times 0.0000001 = 0.000000000001$.
To help show why this works, consider that $\Delta x$ and $\Delta y$ are changing proportionally to each other, i.e., that $\frac{\Delta x}{\Delta y} = k$, for some non-zero constant $k$, so $\Delta x = k\varepsilon_4$ and $\Delta y = \varepsilon_4$ for some small real $\varepsilon_4$. Substitute this into the RHS of \eqref{eq2} and divide both sides by $\varepsilon_4$ to get
$$\frac{\Delta f(x,y)}{\varepsilon_4} = f_{xy}(a,b)\ k\varepsilon_4 + f_x(a,b) k + f_y(a,b) + \varepsilon_1\ k + \varepsilon_2\ + \varepsilon_3\ k\varepsilon_4 \tag{3}\label{eq3}$$
Now, taking the limit as the various $\varepsilon_i \to 0$ gives you on the RHS
$$f_x(a,b) k + f_y(a,b) \tag{4}\label{eq4}$$
Note doing the exact same calculations in \eqref{eq1} gives you the same result. As you can see, when you're taking limits going to $0$, only the lowest order terms will survive.
I hope this answers your question well enough. Keep in mind I used just a somewhat restricted case of $\Delta x \to 0$ and $\Delta y \to 0$ because I thought it'd be more straight forward & simpler than showing the general case, but you may wish to try that yourself to confirm your understanding of this issue.


text:
Q: Expanded widget takes full height of the screen irrespective of its children I am using a dynamic bottom sheet with a column as its child. The last child of this column is a grid view. For some small screen devices, the content of this bottom sheet my get overflow so I wrapped the grid view inside an expanded widget. Now its content are scrollable if they are overflowing.
But the problem here is, even if the contents of the grid view are not overflowing (screen size is big enough) it still expands to full screen leaving empty space at the bottom. I am trying to solve this issue for past 3 days but no result. I tried various combinations of parent and child widget but nothing gives the satisfying result.
The result I am expecting is that the grid view should scroll when contents are overflowing and if not then it should take only the required space and not the entire screen.
Here is my entire code, the grid view with the problem is at the end :
showModalBottomSheet<dynamic>(
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (context, setState) {
              return Container(
                color: Colors.white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(color: Color.fromARGB(255, 225, 225, 225)),
                        ),
                        //color: Color.fromARGB(255, 255, 255, 255),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.fromLTRB(15, 15, 10, 15),
                            child: Icon(
                              Icons.save,
                              color: Color.fromARGB(255, 2, 136, 209),
                              size: 28.0,
                            ),
                          ),
                          Expanded(
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                onTap: (){},
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(8.0, 13.0, 10.0, 10.0),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        mainAxisSize: MainAxisSize.min,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            constraints: BoxConstraints(minWidth: 0, maxWidth: MediaQuery.of(context).size.width*(2/3)),
                                            child: Text(
                                              'PDF Name',
                                              overflow: TextOverflow.ellipsis,
                                              maxLines: 2,
                                              softWrap: true,
                                              style: TextStyle(
                                                fontSize: 16.0,
                                                fontWeight: FontWeight.bold,
                                                color: Color.fromARGB(255, 117, 117, 117),
                                              ),
                                            ),
                                          ),
                                          Padding(
                                            padding: EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
                                            child: Icon(
                                              Icons.edit,
                                              color: Color.fromARGB(255, 2, 136, 209),
                                              size: 16.0,
                                            ),
                                          ),
                                        ],
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 0.0),
                                        child: Text(
                                          "PDF Size",
                                          style: TextStyle(
                                            fontSize: 12.0,
                                            color: Color.fromARGB(255, 117, 117, 117),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                        children: <Widget>[
                          Expanded(
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                child: Divider(
                                  color: Color.fromARGB(255, 220, 220, 220),
                                  thickness: 1.1,
                                ),
                              )
                          ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
                            child: Text(
                              "Share/Save File to",
                              style: TextStyle(
                                color: Color.fromARGB(255, 117, 117, 117),
                                fontSize: 15.0,
                              ),
                            ),
                          ),
                          Expanded(
                              child: Padding(
                                padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                child: Divider(
                                  color: Color.fromARGB(255, 220, 220, 220),
                                  thickness: 1.1,
                                ),
                              )
                          ),
                        ]
                    ),
                    Expanded(
                      child: GridView.count(
                        padding: EdgeInsets.fromLTRB(0, 0, 0, 15),
                        crossAxisCount: 3,
                        shrinkWrap: true,
                        childAspectRatio: 1.25,
                        children: <Widget>[
                          FileSaveCard(icon: Icons.phone_android, color: Colors.pink, title: 'Internal Storage', press: (){}),
                          FileSaveCard(icon: Icons.folder, color: Colors.blueAccent, title: 'My Documents', press: (){}),
                          FileSaveCard(icon: Icons.add_to_drive_rounded, color: Color.fromARGB(255, 254, 150, 0), title: 'Google Drive', press: (){}),
                          FileSaveCard(icon: Icons.mail, color: Colors.lightBlue, title: 'Send to Email', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            }
        );
      },
    );

Here is the output image:

It even slides under that phone's status bar at the top. How can I avoid that as well.
This is the result I am expecting:
Case 1: When it is overflowing, this works fine as I have wrapped grid view in an expanded widget, it becomes scrollable -

Case 2: When screen size is sufficient for the children, below image should be the output, but I get empty space at bottom instead-

Okay, I figured it out finally. For the Status Bar overlapping part giving safe area and all was not working and as suggested by Sagar Acharya using FractionallySizedBox did prevented it but it forced the bottom sheet to take up full screen irrespective of its content height leaving empty space after its last item. Instead I used constraints: BoxConstraints(maxHeight: (MediaQuery.of(context).size.height)*0.95) which did not force sheet to take full height and also prevented it from overlapping status bar.
For the other problem I first removed expanded from top of my grid view and wrapped my whole column (containing all items of the bottom sheet) with SingleChildScrollView. Now it keeps the content wrapped until sheet reaches full screen height and when it does it becomes scrollable.
But still there is one thing I want to change, in my output my whole content of the bottom sheet is scrollable but I just want the grid view children to be scrollable, the top most 'PDF Name' and 'Share/Save File to' should not scroll along with it. Any ideas how I can do that. I tried using SingleChildScrollView on grid view instead of Column but it did not work (the element overflowed when the sheet reached full height)
Here is my code:
showModalBottomSheet<dynamic>(
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (context, setState) {
              return Container(
                //height: 900,
                constraints: BoxConstraints(maxHeight: (MediaQuery.of(context).size.height)*0.95),
                color: Colors.white,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(color: Color.fromARGB(255, 225, 225, 225)),
                          ),
                          //color: Color.fromARGB(255, 255, 255, 255),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.fromLTRB(15, 15, 10, 15),
                              child: Icon(
                                Icons.save,
                                color: Color.fromARGB(255, 2, 136, 209),
                                size: 28.0,
                              ),
                            ),
                            Expanded(
                              child: Material(
                                color: Colors.transparent,
                                child: InkWell(
                                  onTap: (){},
                                  child: Padding(
                                    padding: const EdgeInsets.fromLTRB(8.0, 13.0, 10.0, 10.0),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisSize: MainAxisSize.min,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Container(
                                              constraints: BoxConstraints(minWidth: 0, maxWidth: MediaQuery.of(context).size.width*(2/3)),
                                              child: Text(
                                                'PDF Name',
                                                overflow: TextOverflow.ellipsis,
                                                maxLines: 2,
                                                softWrap: true,
                                                style: TextStyle(
                                                  fontSize: 16.0,
                                                  fontWeight: FontWeight.bold,
                                                  color: Color.fromARGB(255, 117, 117, 117),
                                                ),
                                              ),
                                            ),
                                            Padding(
                                              padding: EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
                                              child: Icon(
                                                Icons.edit,
                                                color: Color.fromARGB(255, 2, 136, 209),
                                                size: 16.0,
                                              ),
                                            ),
                                          ],
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 0.0),
                                          child: Text(
                                            "PDF Size",
                                            style: TextStyle(
                                              fontSize: 12.0,
                                              color: Color.fromARGB(255, 117, 117, 117),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Row(
                          children: <Widget>[
                            Expanded(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                  child: Divider(
                                    color: Color.fromARGB(255, 220, 220, 220),
                                    thickness: 1.1,
                                  ),
                                )
                            ),
                            Padding(
                              padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
                              child: Text(
                                "Share/Save File to",
                                style: TextStyle(
                                  color: Color.fromARGB(255, 117, 117, 117),
                                  fontSize: 15.0,
                                ),
                              ),
                            ),
                            Expanded(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                  child: Divider(
                                    color: Color.fromARGB(255, 220, 220, 220),
                                    thickness: 1.1,
                                  ),
                                )
                            ),
                          ]
                      ),
                      GridView.count(
                        padding: EdgeInsets.fromLTRB(0, 0, 0, 15),
                        crossAxisCount: 3,
                        shrinkWrap: true,
                        //physics: NeverScrollableScrollPhysics(),
                        physics: const ScrollPhysics(),
                        childAspectRatio: 1.25,
                        children: <Widget>[
                          FileSaveCard(icon: Icons.phone_android, color: Colors.pink, title: 'Internal Storage', press: (){}),
                          FileSaveCard(icon: Icons.folder, color: Colors.blueAccent, title: 'My Documents', press: (){}),
                          FileSaveCard(icon: Icons.add_to_drive_rounded, color: Color.fromARGB(255, 254, 150, 0), title: 'Google Drive', press: (){}),
                          FileSaveCard(icon: Icons.mail, color: Colors.lightBlue, title: 'Send to Email', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),

                          /*FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                          FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),*/
                        ],
                      ),
                    ],
                  ),
                ),
              );
            }
        );
      },
    );

Any help would me much appreciated.
Thank you.

A: *

*I think this is the answer you wanted

import 'package:flutter/material.dart';
import 'package:test11111/test1.dart';
import 'package:get/get.dart';

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: const Text('showModalBottomSheet'),
        onPressed: () {
          showModalBottomSheet<void>(
            context: context,
            builder: (BuildContext context) {
              return SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: Get.height* 0.4,
                      color: Colors.white,
                      child: Column(
                        children: [
                          Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(color: Color.fromARGB(255, 225, 225, 225)),
                              ),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(15, 15, 10, 15),
                                  child: Icon(
                                    Icons.save,
                                    color: Color.fromARGB(255, 2, 136, 209),
                                    size: 28.0,
                                  ),
                                ),
                                Expanded(
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      onTap: (){},
                                      child: Padding(
                                        padding: const EdgeInsets.fromLTRB(8.0, 13.0, 10.0, 10.0),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisSize: MainAxisSize.min,
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Container(
                                                  constraints: BoxConstraints(minWidth: 0, maxWidth: MediaQuery.of(context).size.width*(2/3)),
                                                  child: Text(
                                                    'PDF Name',
                                                    overflow: TextOverflow.ellipsis,
                                                    maxLines: 2,
                                                    softWrap: true,
                                                    style: TextStyle(
                                                      fontSize: 16.0,
                                                      fontWeight: FontWeight.bold,
                                                      color: Color.fromARGB(255, 117, 117, 117),
                                                    ),
                                                  ),
                                                ),
                                                Padding(
                                                  padding: EdgeInsets.fromLTRB(5.0, 0.0, 0.0, 0.0),
                                                  child: Icon(
                                                    Icons.edit,
                                                    color: Color.fromARGB(255, 2, 136, 209),
                                                    size: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                            Padding(
                                              padding: const EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 0.0),
                                              child: Text(
                                                "PDF Size",
                                                style: TextStyle(
                                                  fontSize: 12.0,
                                                  color: Color.fromARGB(255, 117, 117, 117),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Row(
                              children: <Widget>[
                                Expanded(
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                      child: Divider(
                                        color: Color.fromARGB(255, 220, 220, 220),
                                        thickness: 1.1,
                                      ),
                                    )
                                ),
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
                                  child: Text(
                                    "Share/Save File to",
                                    style: TextStyle(
                                      color: Color.fromARGB(255, 117, 117, 117),
                                      fontSize: 15.0,
                                    ),
                                  ),
                                ),
                                Expanded(
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                                      child: Divider(
                                        color: Color.fromARGB(255, 220, 220, 220),
                                        thickness: 1.1,
                                      ),
                                    )
                                ),
                              ]
                          ),
                          Expanded(
                            child: GridView.count(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 15),
                              crossAxisCount: 3,
                              shrinkWrap: true,
                              childAspectRatio: 1.25,
                              children: <Widget>[
                                FileSaveCard(icon: Icons.phone_android, color: Colors.pink, title: 'Internal Storage', press: (){}),
                                FileSaveCard(icon: Icons.folder, color: Colors.blueAccent, title: 'My Documents', press: (){}),
                                FileSaveCard(icon: Icons.add_to_drive_rounded, color: Color.fromARGB(255, 254, 150, 0), title: 'Google Drive', press: (){}),
                                FileSaveCard(icon: Icons.mail, color: Colors.lightBlue, title: 'Send to Email', press: (){}),
                                FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class FileSaveCard extends StatelessWidget {
  FileSaveCard(
      {Key? key,
      required this.icon,
      required this.color,
      required this.title,
      required this.press})
      : super(key: key);
  IconData icon;
  Color color;
  String title;
  VoidCallback press;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          IconButton(icon: Icon(icon), color: color, onPressed: press),
          Text(title)
        ],
      ),
    );
  }
}

A: Ok So from the code i see you are using things in wrong manner.

*

*If you are using the isScrollControlled =true it will use the complete height of the device as you have used the expanded and the Column widget as a parent for the children inside it.

*Next if you do not want the complete height so instead of column you have to use the Wrap widget and remove the expanded from the gridview it will take the height as per the children.

*If you want the fill modelsheet and the space from top as it overlaps the statusbar you can use the FractionallySizedBox widget
FractionallySizedBox(
   heightFactor: 0.95,// This will take 0.05 percent height from the top and show the status bar
)

Note: It can only be used when the isScrolled is true.
so I have created the example from the code that you have provided, Also i have added my icon set so change it as per your needs.
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

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

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

class _MyAppState extends State<MyApp> {
  final items = <Widget>[
    //1
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),
    //2
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),
    //3
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),
    //4
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),
    //5
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),
    //6
    const Icon(
      Icons.phone_android,
      color: Colors.pink,
      semanticLabel: 'Internal Storage',
    ),

    //Add the same item below this to make it full screen and items below 7 will have the minimum model sheet height.
    //7
    // const Icon(
    //   Icons.phone_android,
    //   color: Colors.pink,
    //   semanticLabel: 'Internal Storage',
    // ),

    //
    // FileSaveCard(icon: Icons.folder, color: Colors.blueAccent, title: 'My Documents', press: (){}),
    // FileSaveCard(icon: Icons.add_to_drive_rounded, color: Color.fromARGB(255, 254, 150, 0), title: 'Google Drive', press: (){}),
    // FileSaveCard(icon: Icons.mail, color: Colors.lightBlue, title: 'Send to Email', press: (){}),
    // FileSaveCard(icon: Icons.share, color: Colors.green, title: 'Share', press: (){}),
  ];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: true,
      child: Scaffold(
        body: ElevatedButton(
          onPressed: () {
            showModalBottomSheet<dynamic>(
              // use only when you want to use the full height of the screen.
              isScrollControlled: items.length > 6 ? true : false,
              context: context,
              builder: (BuildContext context) {
                return StatefulBuilder(builder: (context, setState) {
                  return FractionallySizedBox(
                    heightFactor: items.length > 6
                        ? 0.95
                        : null, // This widget will add padding from top showing the status bar
                    child: Container(
                      color: Colors.white,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                    color: Color.fromARGB(255, 225, 225, 225)),
                              ),
                              //color: Color.fromARGB(255, 255, 255, 255),
                            ),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding:
                                      const EdgeInsets.fromLTRB(15, 15, 10, 15),
                                  child: Icon(
                                    Icons.save,
                                    color: Color.fromARGB(255, 2, 136, 209),
                                    size: 28.0,
                                  ),
                                ),
                                Expanded(
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      onTap: () {},
                                      child: Padding(
                                        padding: const EdgeInsets.fromLTRB(
                                            8.0, 13.0, 10.0, 10.0),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisSize: MainAxisSize.min,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Container(
                                                  constraints: BoxConstraints(
                                                      minWidth: 0,
                                                      maxWidth:
                                                          MediaQuery.of(context)
                                                                  .size
                                                                  .width *
                                                              (2 / 3)),
                                                  child: Text(
                                                    'PDF Name',
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    maxLines: 2,
                                                    softWrap: true,
                                                    style: TextStyle(
                                                      fontSize: 16.0,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      color: Color.fromARGB(
                                                          255, 117, 117, 117),
                                                    ),
                                                  ),
                                                ),
                                                Padding(
                                                  padding: EdgeInsets.fromLTRB(
                                                      5.0, 0.0, 0.0, 0.0),
                                                  child: Icon(
                                                    Icons.edit,
                                                    color: Color.fromARGB(
                                                        255, 2, 136, 209),
                                                    size: 16.0,
                                                  ),
                                                ),
                                              ],
                                            ),
                                            Padding(
                                              padding:
                                                  const EdgeInsets.fromLTRB(
                                                      0.0, 5.0, 0.0, 0.0),
                                              child: Text(
                                                "PDF Size",
                                                style: TextStyle(
                                                  fontSize: 12.0,
                                                  color: Color.fromARGB(
                                                      255, 117, 117, 117),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Row(children: <Widget>[
                            Expanded(
                                child: Padding(
                              padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                              child: Divider(
                                color: Color.fromARGB(255, 220, 220, 220),
                                thickness: 1.1,
                              ),
                            )),
                            Padding(
                              padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
                              child: Text(
                                "Share/Save File to",
                                style: TextStyle(
                                  color: Color.fromARGB(255, 117, 117, 117),
                                  fontSize: 15.0,
                                ),
                              ),
                            ),
                            Expanded(
                                child: Padding(
                              padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
                              child: Divider(
                                color: Color.fromARGB(255, 220, 220, 220),
                                thickness: 1.1,
                              ),
                            )),
                          ]),
                          Expanded(
                            flex: items.length > 6 ? 1 : 0,
                            child: GridView.count(
                                padding: EdgeInsets.fromLTRB(0, 0, 0, 15),
                                crossAxisCount: 3,
                                shrinkWrap: true,
                                childAspectRatio: 1.25,
                                physics: const ScrollPhysics(),
                                children: items),
                          ),
                        ],
                      ),
                    ),
                  );
                });
              },
            );
          },
          child: const Text("Press"),
        ),
      ),
    );
  }
}

Run the application and let me know if that works for you.


text:
Q: PDA (Pushdown Automata) Trace - I don't understand the answer I am learning about PDA, and I get how to trace a set of symbols or an alphabet for a given drawn PDA. However, I don't know how to trace for a given PDA (in written form) see below.
So this is a written PDA:
Q={s0,f}
Σ={a,b,c}
Γ={S,X,a,b,c}
F={f}
δ={((s0,ε,ε),(f,S)),
((f,ε,S)(f,aSc)),
((f,ε,S)(f,X)),
((f,ε,X)(f,bXc)),
((f,ε,X)(f,ε)),
((f,a,a)(f,ε)),
((f,b,b)(f,ε)),
((f,c,c)(f,ε))
}

The question asked:
Trace one possible computational path of your pushdown automaton from with
the input abccc. This string will not be accepted. Explain how you know that your computation has not accepted the input, that is, why the state and stack configuration after the input has been used up is not an accepting one.

The answer was:
State   Stack
s0      ε
f       S
f       aSc
f       Sc
f       Xc
f       bXcc
f       Xcc
f       cc
f       c
f       ε

I don't understand the stack symbols. I thought if there was a ε at the end of the stack that the input was accepted :S?
Would really appreciate it if someone could explain it to me
Thanks


text:
Q: Review queue edit posts mouse doesn't work Basically when reviewing a low quality post, if I choose to edit the item, I cannot move the cursor by clicking in the textarea. The keyboard is working fine, but any mouse interaction appears to be disabled.
The issue only appears if you review one item first, then the next item is loaded in. Editing this item will have disabled mouse input.
I haven't tested other review queues yet but will do so as soon as possible.
This seems to only affect low-quality posts.
Browsers I've tested:
Broken

*

*Chrome 33, Win 7

*Chrome 34, Win 7 | OSX Mavericks

*Chrome 36, Win 7

*Firefox 28, Win 7

*Safari 8, Yosemite

Working

*

*Safari 7 OSX Mavericks (Intermittent)

A: This was a bug with the popup that gives you some pre-made comments to post when deleting or recommending deletion. Since this functionality is only available in the Low Quality Posts queue, the bug only appeared in that queue. It wasn't consistently reproducible because you had to previously have had a review where you recommended deletion for this issue to appear.
That bug was fixed a week ago (it was another symptom of this bug), except for a very small remaining problem where only the very first click after deletion may do nothing, but only in very unlikely circumstances. This remaining bug is also fixed in the next build.


text:
Q: How to dynamically compute value of a variable and use it in a command? Reducing what I'm trying to do to a simple example:
env temp=`pwd` echo "$temp"

I get this message:
temp: Undefined variable.

How do I make it work (in a shell-agnostic way)? I'm expecting the result of pwd to be printed.
My actual requirement uses a complicated expression in place of pwd, a script in place of "echo", and the variable $temp as an argument to that script.
Also, I want to set this variable only for this single command, and not for the whole shell (or any subsequent subshells).

A: How about something like this for sh and bash
(export temp=`pwd`; echo $temp)

And this for csh
csh -c 'setenv temp `pwd`; echo "$temp"'


text:
Q: Dynamic enums in vb6 Is there a way to create an enum at runtime in vb6?
Basically I need to create a enum of Products, but I'll get the data of Products at runtime and this is supposed to vary.

A: No.
The whole point of enums is to provide type safety at compile time. For example, if a function accepts an enum value as a parameter, the range of valid inputs is well-defined based on the members of the enum type. It doesn't have to worry about how to handle invalid input because that will result in a compiler error.
There's no way to achieve this kind of type safety at run time, so dynamically created enums don't make much sense. At any rate, they're not a feature supported by the language or runtime environment.
You'll have to just use a unique identifier (like a string or a numeric value) in place of an enum. If you wanted, you could create an array or another collection class that mapped those IDs to a unique key (e.g., the name of product). You could then add products to the array dynamically at runtime, and retrieve their ID by name.
Note that with this strategy, you will need to validate inputs and handle any errors manually.


text:
Q: How to deploy a war Java web application in Wamp server? I have a web application which I developed in J2EE. I created my war file,deployed it correctly on Apache server and works as expected.
Now I need to make my application run on wamp server. I know that wamp is not for java j2ee application, but Is there a way to deploy my application on wamp? I thought about adding a php software layer : an index.php file executing the j2ee war like this:
<?php
shell_exec("java -war C:\wamp64\www\MyApp\webApp.war ");
?>

But it did not work, I have a white empty page.
What is wrong with my idea? How can I make my j2ee application run on a wamp server without the need of a Tomcat server?
Thank you in advance!


text:
Q: libgtk-x11-2.0.so.0 error opencv I'm trying to install opencv on my server. I ran:
conda install -c https://conda.binstar.org/menpo opencv3

which worked successfully but then when I try to import cv2 I get the following error:
ImportError: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory

I tried apt-get install libgtk-x11-2.0.so.0 but the package doesn't exist.
My guess is that because I'm running a VPS, the gtk libraries are not present. Any ideas on how to deal with this? Thanks!

A: I got the same error and it was resolve by installing libgtk package.
Run this command;
apt-get install libgtk2.0-0


text:
Q: How to sort a list of string dates I need some help with sorting a list of dates. I have a few lines of code and I tried a lot of different solutions I found on the internet but none of them seems to work.
import datetime

class WhiteChocolate:
    def __init__(self, vervaldatum):
        self.vervaldatum = vervaldatum

WhiteChocoStock = []

WhiteChocoStock.append(WhiteChocolate("22/04/2014"))
WhiteChocoStock.append(WhiteChocolate("21/04/2015"))
WhiteChocoStock.append(WhiteChocolate("12/12/2013"))

test = sorted(WhiteChocoStock, key=lambda x: datetime.datetime.strptime(x, '%d/%m/%Y'))

I don't know what I'm doing wrong.

A: You are trying to sort a list of objects, when you need to sort by the vervaldatum property of each of the objects in your list, which contains the date string:
sorted(WhiteChocoStock, key=lambda x: datetime.datetime.strptime(x.vervaldatum, '%d/%m/%Y'))


text:
Q: Why iteration over bs4.element.ResultSet makes no copy of original? I am a bit confused by the behaviour of iteration on Beautifulsoup ResultSets. Generally speaking, in python I would expect iteration to generate a copy of each element. A list cannot be modified by assigning new values to iterated elements.
l1 = [1,2,3]
for elem in l1:
    elem = elem + 10

will not modify original list l1
But if I do:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

for elem in soup('body'):
    elem.unwrap()

Then the original soup element is modified!
This seems inconsistent to me, but it is clear I am missing some basic stuff here
I am using python 3.5 and BS 4.4.1
Thanks in advance

A: Ok, it was a beginner's mistake. When iterating over the soup elements, we are iterating over mutable elements so a modification of a component of a copy is still reflected onto the original variable
l1 = [[1,1],[2,2]]
for elem in l1:
    elem[1] = 5555

would deliver
l1 = [[1,5555],[2,5555]]

Same behaviour for the iteration on bs tags


text:
Q: I cant use the objects attribute in django project I created a Projects model
class Projects(models.Model):
name = models.CharField(max_length=257, unique=True, null=False)
description = models.TextField()
active_issue_count = models.IntegerField(default=0)  # functiona bağlanmalı
solved_issue_count = models.IntegerField(default=0)  # functiona bağlanmalı
is_active = models.BooleanField()
start_date = models.DateTimeField()
deadline = models.DateTimeField()

and I want to use this project model Projects.objects.all() with this code but when I typed in pyCharm shows me this suggestion
but while I try to use this model
class User(AbstractUser, PermissionsMixin):
    objects = UserManager()
    related_group = models.CharField
    current_project = models.ForeignKey(to='core.Project',
    related_name='current_project', on_delete=models.PROTECT, null=True)
    total_worked_project = models.IntegerField(default=0)  # functiona bağla
    active_work_project_count = models.IntegerField(default=0)  # functiona bağla

    REQUIRED_FIELDS = ['email']

`
I can use User.objects.all() without suggestion what should I do anyone can help me ?

A: PyCharm just don't follow some object's relation. Here it has no clue that this Model class has related Manager, that you can call with objects.
You can ignore it in PyCharm so it will not bother you.
More actions... => Ignore (...)


text:
Q: Rails date format in text_field
*

*If i let the user to type the date_format in text_field. is there any format to validate the date_format if the user enters invalid string?

*If i show the date_formats as drop downs, Is there any international date_formats available?
eg: Date-formats (MMM. d, YYYY),(h:mm a)
Any Suggestions.

A: Have you tried Date.parse? Could be used in both of your questions.
http://ruby-doc.org/stdlib-2.0.0/libdoc/date/rdoc/Date.html#method-c-parse


text:
Q: Is returning Double.NaN from method a good practice to indicate invalid double value Currently, I'm implementing a method with the following signature
public static double Newtons_method(double[] payments, double[] days, double guess)
Sometimes, the calculation will fail. There are several ways to indicate failure.

*

*Change returned type to Double, and return as null.

*Throws exception.

*Return Double.NaN and use Double.isNaN(double) to test against it.

However, there are several concern.

*

*I prefer not to return Object, for performance purpose. I need to do a lot of box and unboxing if Double is used.

*I prefer not to throw an exception, for performance purpose. Also, try catch makes code looks messy. Not, in Newtons_method, there are quite a number common cases where such algorithm will fail. So, it might not appropriate to consider them as exception
How about 3rd approach, returning Double.NaN? Is that consider a good practice?
Here's the source code for your reference.
https://github.com/yccheok/xirr/blob/master/src/org/yccheok/quant/XIRR.java#L56
Note that, there isn't any error checking being implemented yet. So, err might never further reduced, and the method might go into infinity loop.

A: In general, the practice of using a special return value for exceptional situations goes against the grain with Java's way of informing the caller about exceptional situations. To that end, strategies #1 and #3 are equivalent, because both of them result in caller code like this:
// This could be double or Double
double res = Newtons_method(pmt, guess);
// This could be res==null check or Double.isNaN(res) call
if (!checkResult(res)) {
    // Do something else
}
// Do regular processing

This is error-prone, because inevitably somebody will forget to do the check, causing errors down the road. This tends to happen more when method calls are nested, as in
double res = doStuff(Newtons_method(pmt1, guess), Newtons_method(pmt2, guess));

An incorrect result makes it into parameters of the next-level function call, forcing either an argument exception (if the coder is very good about his argument checking) or a hard to debug error down the road.
Your strategy #2 is better, because callers cannot simply "forget" to catch the exception: they would have to either catch and process it, or add throws to their own method.

A: Here's a solution that combines the safety-net advantage of exceptions, but doesn't force the caller to use them to check for success or failure. It also doesn't have the cost of throwing an exception each time the result is a failure, if the caller doesn't want this cost:
public Result compute(...) { ... }

public interface Result {
    /**
     * Returns true if the computation was successful
     */
    boolean isSuccessFul();

    /**
     * Returns the computed value if successful.
     * @throws IllegalStateException if the computation failed - you could use another exception here if you prefer
     */
    double getValue();

    /**
     * Gets the reason for the failure, is the computation has failed.
     * @throws IllegalStateException if the computation succeeded
     */
    String getFailureReason();
}

class Success implements Result {
    private final double value;

    public Success(double value) {
        this.value = value;
    }

    @Override
    public boolean isSuccessFul() {
        return true;
    }

    @Override
    public double getValue() {
        return value;
    }

    @Override
    public String getFailureReason() {
        throw new IllegalStateException("The computation was successful");
    }
}

class Failure implements Result {
    private final String reason;

    public Failure(String reason) {
        this.reason = reason;
    }

    @Override
    public boolean isSuccessFul() {
        return false;
    }

    @Override
    public double getValue() {
        throw new IllegalStateException(reason);
    }

    @Override
    public String getFailureReason() {
        return reason;
    }
}

That way, callers assuming that the result is successful will do
double result = compute().getValue();

and will get a meaningful exception if the result was a failure.
And people who test the result will be able to do it without having any performance loss due to exceptions:
Result r = compute();
if (r.isSuccessful()) {
    double value = r.getValue();
    ...
}
else {
    ...
}

This is basically similar as returning null, except the code is much more self-explanatory, the caller has much less chance of forgetting to test the failure case, and gets a meaningful exception in that case.

A: I've seen people use Double.NaN in a similar manner, and I've never heard anyone saying it was bad practice to do that. You might want to put in the methods Javadocs that you use that approach though.


text:
Q: Using @ClusteringColumn and @Index in achilles cassandra on same column I need to use same column as clustering column and secondary index. But achilles compilation fails.
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(table="users")
public class Users{
    @PartitionKey
    @Column
    private String userID;

    @Index(name = "fname")
    @ClusteringColumn
    @Column
    private String fname;
}

But compiler throws error as below:
[ERROR] /D:/Work/Codebase/itam-common/schema/target/generated-sources/annotations/info/archinnov/achilles/generated/dsl/Users_SelectIndex.java:[466,44] method fname() is already defined in class info.archinnov.achilles.generated.dsl.Users_SelectIndex.E

I am using achilles-core: 5.3.1 and cassandra-driver-core:3.3.0

A: Try giving different name for your @Column and @Index annotation:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(table="users")
public class Users{
    ...
    @Index(name = "fname_idx")
    @ClusteringColumn
    @Column(name = "fname")
    private String fname;
    ...
}


text:
Q: Can I place \includegraphics command before \begin{document}? Can I place \includegraphics command before \begin{document}? I see in sharelatex they are doing like that but in texstudio I am writing the same code but I get the error.

A: Display of graphics or Text/tables, showing page numbers/headers etc. i.e. anything which is really connected with text etc. is typesetting.
Typesetting is not possible with LaTeX before \begin{document}.
If text/content is to be stored, either in boxes or a wrapper macro, this can be done of course, see the \blindtext command from blindtext package, which is definitely stored before \begin{document} (since it's in a package), but you can't use \blindtext before \begin{document} directly.
The example videos provided in the link show basically
\title{%
   \includegraphics{foo}
}

The \title{#1} macro is effectively doing this\gdef\@title{#1}, i.e. using another macro to store the content, designed to be used by \maketitle later on.


text:
Q: Electron Application run on apple silicon ARM64 We are able to ran the Electron desktop application by  using electron-builder along with dmg on X64.If we want to run same application on apple silicon(ARM64), We installed following dependancies(X64)
1 Xcode 12 and upgrade Mac to Bix sur.
2 "npm install electron@11.0.0-beta.1"
3 node-gyp(7.1.2)
but, found below errors:
"ERROR TypeError: Cannot read property 'require' of null"
Also while building and packaging the application we want to add extraFiles.
Kindly suggest if any solution.
Also read about electron-packager,but How can we add extra files using the same.

A: I don't know how to resolve your error but I can suggest to you to install the latest electron release and not a beta version. If you think the beta can be the best way to use with an apple silicon (I don't now if the latest beta is compiled for it) you can try it equally, because macOS will compile electron for you... (it can takes about 20 seconds to compile).


text:
Q: using conditions on populate with waterline and sails.js I'm trying to use conditions on populate, but can't solve it.
The following code exists and working great, just add conditions made it crash.
Page.find({ 'id' : id })
.populate('addons', { 'type' : 'seo' })
.then(function(page)) {

});

but when i try to add 'or' condition it crashes.
Page.find({ 'id' : id })
.populate('addons', {
    or: [
        {
            'type' : 'seo'
        },
        {
            'type' : 'general'
        },
        {
            'type' : 'local',
            'zone' : zoneId // zoneId holds the correct information
        }
    ]
})
.then(function(page)) {

});

thanks.


text:
Q: Form to appear in a popup panel I have the following file setup:
In forms.py
class TableCheckInForm(forms.Form):
    guest_count = forms.IntegerField(min_value =0)

In views.py:
def table_checkin_view(request):
    if request.method == 'POST':
        form = TableCheckInForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
    else:
        form = TableCheckInForm()
    return render(request,
                  'table/table_checkin.html', {'form': form})

In the template table_view.html

...
<button class="button checkin_button" onclick="openForm()">Check In</button>
...

In another template table_checkin.html
{% load static %}

Check-In

    <form class="form-container" method="post">
      {{ form.as_p }}
      {% csrf_token %}
      <button type="submit" class="table_checkin" onclick="closeForm()">Check In</button>
    </form>

In static Javascript file table.js
function openForm() {
  document.getElementById("table_checkin_form").style.display = "block";
}

function closeForm() {
  document.getElementById("table_checkin_form").style.display = "none";
}

In urls.py
urlpatterns = [
    ...
    path('', views.table_view, name='table_view'),
    path('1/checkin/', views.table_checkin_view, name='table_checkin_view'),
    ...
]

I am trying to implement a popup panel that contains the form above, similar to this example from W3Schools here.
Suppose I am currently on the template table_view.html. When I click the button checkin_button, I would like to have the form popup in a small panel that renders table_checkin.html. That means, in the background, I would like still see the template table_view.html.
But the form in my case always appear in a completely new page (since it has its own url).
Putting aside the css effect, is it possible to have one view containing a form being rendered as a popup on top of another view?
If you have other suggestions to implement this effect, that would be great. Thanks.

A: You don't need to open a separate URL to render the form.
To create the example you're referencing, the form is included as a div in what would be your table_view.html page. It's hidden by default, then the div is displayed when on clicks the Open Form button.
Sticking the code from the first button in the W3Schools example to the end of the script (before the closing body tag) into table_view.html should make their example run for you. Then replace the form and action info. Add CSS as needed.


text:
Q: How factorize a lot of "little" numbers? Several fast algorithms are available to factorize big numbers, but what is the best algorithm to factorize a lot of "little" numbers? I need to factorize a lot of odd numbers $< \mathbf{2^{56}}$. I want to do that only with 64 bits arithmetic.
I use a combination of that:

*

*A table of all prime $< 2^{16}$.

*A "offset technics" to iterate on possible prime numbers bigger than $2^{16}$.

*The Pollard's rho heuristic to (probably) find a divisor. I implemented the version presented in "Introduction to Algorithms" (Cormen, Leiserson, Rivest and Stein), with added a maximum number of iterations something like $n^{1/2}$ or $n^{1/4}$.

In fact I want to compute the sum of odd divisors $\sigma_{\text{odd}}$ of these numbers. To check that $\forall n \in \mathbb{N}, n > 1, \exists k : \sigma_{\text{odd}}^k(n) < n$.
Maybe there is a better way to do that than use the complete factorization in prime numbers?
And what about all these considerations in a parallel context?
Answer:
Finally I use an unique big table with all prime numbers $<2^{32}$:

*

*prime32.7z (165 MiB):
https://mega.nz/#!jQtWGY5Y!jHj0PXwJ52Rd69cSuFzo_X_3lk-N5GJHC5JiiR0K7wE

*prime32.bin.gz (272 MiB):
https://mega.nz/#!jU9FDRBK!wLfU4YncXYR5fZbUTqRGNZX7eL_j6BlG2j4mSr3YHBM

A: In order to calculate the sum of divisors of definite number you may use the Euler pentagonal number theorem application for divisors sum $\sigma(n)$.
$$\sigma(n)=\sigma(n-1)+\sigma(n-2)-\sigma(n-5)-\sigma(n-7)+...$$
The ${1,2},{5,7},...$ are generalized pentagonal numbers.
$\sigma(n)=0$ if $n<0$
$\sigma(n-n) = 0$ if $n$ is not a generalized pentagonal number and
$\sigma(n-n) = n$ otherwise.
The generalized pentagonal numbers can be found:
https://oeis.org/A001318
There are some other articles:
http://euler.genepeer.com/eulers-pentagonal-number-theorem/
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.538.6485&rep=rep1&type=pdf


text:
Q: What is the best way to do HTML encoding and decoding in Apex? I am programmatically building a HTML string in Apex and then saving it to a rich text field. The problem is that SalesForce is doing some HTML encoding on the string before it gets persisted which is making the string longer and causing a STRING_TOO_LONG error. What is the best way to do HTML encoding and decoding in Apex? See below for my attempt:
public String htmlEncode (String s) {

    Map<String, String> htmlEncodingMap = new Map<String, String>();
    htmlEncodingMap.put('<', '<');
    htmlEncodingMap.put('>', '>');
    htmlEncodingMap.put('"', '&quot;');
    htmlEncodingMap.put('&', '&');

    for (String token : htmlEncodingMap.keySet()) {
        s = s.replace(token, htmlEncodingMap.get(token));
    }

    return s;
}

public String htmlDecode (String s) {

    Map<String, String> htmlDecodingMap = new Map<String, String>();
    htmlDecodingMap.put('<', '<');
    htmlDecodingMap.put('>', '>');
    htmlDecodingMap.put('&quot;', '"');
    htmlDecodingMap.put('&', '&');

    for (String token : htmlDecodingMap.keySet()) {
        s = s.replace(token, htmlDecodingMap.get(token));
    }
    return s;
}

A: The Apex String class has HTML escape and unescape methods on it, escapteHtml4 and unescapeHtml4. Here are some examples from these topics in the documentation...
String s1 =
   '"<Black&White>"';
String s2 =
   s1.escapeHtml4();
System.debug(s2);
// Output:
// "<Black&
// White>"

String s1 =
   '"<Black&White>"';
String s2 =
   s1.unescapeHtml4();
System.assertEquals(
   '"<Black&White>"',
   s2);

2022.11.18: Updated broken links to SF documentation


text:
Q: How to autoexpand neosnippet with deoplete dropdown menu? Iam looking for an configuration (init.vim) to expand an neosnippet when selected with the deoplete plugin drop down menu.
What i've done so far:

*

*Added all to vim-plug
call plug#begin ('~/.local/share/nvim/plugged')
Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
Plug 'Shougo/neosnippet.vim' | Plug 'Shougo/neosnippet-snippets'
call plug#end ()

*configured for autostart
" Use deoplete.
let g:deoplete#enable_at_startup = 1
" Use smartcase.
let g:deoplete#enable_smart_case = 1
" Set minimum syntax keyword length.
let g:deoplete#sources#syntax#min_keyword_length = 2

This leads to this screen:
Now I want to expand this snippet, when hitting <Enter> at the selection. Has anyone suggestion how to achiev that?
Thanks for your time and best regards,
Befedo

A: Neosnippets doesn't expand automatically. You need to configure the key mappings. The project suggest the following to expand them using Ctr+k:
" Plugin key-mappings.
" Note: It must be "imap" and "smap".  It uses <Plug> mappings.
imap <C-k>     <Plug>(neosnippet_expand_or_jump)
smap <C-k>     <Plug>(neosnippet_expand_or_jump)
xmap <C-k>     <Plug>(neosnippet_expand_target)

If you want to expand them when using the popup menu use the following:
inoremap <silent><expr><CR> pumvisible() ? deoplete#mappings#close_popup()."\<Plug>(neosnippet_expand_or_jump)" : "\<CR>"


text:
Q: Classical noise approximation of a system coupled to a quantum environment I have a question based on the principles described in "Quantum simulator of an open quantum system using superconducting qubits: exciton transport in photosynthetic complexes" by Mostame et al. In this paper they are interested in studying the remarkable efficiency of photosynthesis, and more specifically the transport of excitation in photosynthetic complexes such as FMO.
They model the complex as an 'electronic system' consisting of finite-dimensional system of two level systems, coupled to coupled to a bath of 'phonon bath' of harmonic oscillators. The reasoning behind this model is that the sites through which the excitations traverse either contain an excitation or not, making them a form of a two level system. In addition to that in real cells these sites interact with the vibtrational environment of the surrounding molecular structure, hence the phononic bath.
Based on these considerations one can write down a Hamiltonian of the form
\begin{equation}
H_\text{tot} = H_\text{el} + H_\text{ph} + H_\text{I} \tag{1}
\end{equation}
where $H_\text{el}$ describes the two-level systems, $H_\text{ph}$ describes the photons, and $H_\text{I}$ describes their interaction.
The two-level system part has the form
\begin{equation}
H_\text{el} = \sum_{j=1}^N \epsilon_j \vert{j}\rangle\langle{j}\vert + \sum_{i < j}^{N} V_{ij}\left(\vert{j}\rangle\langle{i}\vert + \vert{i}\rangle\langle{j}\vert\right) \, .
\end{equation}
where the basis states $\vert j\rangle$ are defined by the electronic excitation residing on molecule (site) j and all other sites being in their electronic ground state.
The photon part has the form
\begin{equation}
H_\text{ph} = \sum_{j=1}^{N} H_{\text{ph},j} \quad
H_{\text{ph},j} = \sum_l \hbar \omega_l(a^{j\dagger}_l a^j_l + 1/2) \, .
\end{equation}
The interaction has the form
\begin{equation}
H_\text{I} = \sum_{j=1}^N \vert{j}\rangle\langle{j}\vert\left(\sum_l \chi_{jl}(a^{\dagger,j}_l + a_l^j)\right) \, .
\end{equation}
In the paper they conveniently write this in terms of Pauli matrices
\begin{align}
H =  & \frac{1}{2}\sum_{j=1}^N \epsilon_j \sigma_{z}^j + \frac{1}{2} \sum_{i<j}^N V_{ij} \left(\sigma_{x}^j\sigma_{x}^i + \sigma_{y}^j\sigma_{y}^i \right) \\ & + \sum_{j=1}^N\sum_l \hbar \omega_{l,j}(a^{j\dagger}_l a^j_l + 1/2) + \sum_{j=1}^N\sum_l \chi_{jl} \sigma_z^j\left(a^{j\dagger}_l + a^j_l\right) \tag{4}
\end{align}
where we see that the bath and the two level systems can exchange energy.
Note that in the text they write that the effect of this phononic environment on the two level systems is fully contained in the bath power spectral density
\begin{equation}
J_j(\omega) = \sum_l \vert\chi_{jl}\vert^2\delta(\omega-\omega_l)
\end{equation}
This leads to my question, which relates to the section that follows the previous equations called the classical noise approximation. There they describe the so called Haken-Strobl-Reineke model, where one replaces the quantum mechanical bath of harmonic oscillators by a classical noise environment leading to time-dependent fluctuations of the transition energies $\epsilon$. Here one can rewrite the above Hamiltonian as
\begin{equation}
\frac{1}{2}\sum_{j=1}^N \left[\epsilon_j + \delta\epsilon_j(t)\right] \sigma_{z}^j + \frac{1}{2} \sum_{i<j}^N V_{ij} \left(\sigma_{x}^j\sigma_{x}^i + \sigma_{y}^j\sigma_{y}^i \right) \tag{5}
\end{equation}
where one assumes that $\delta \epsilon_j(t)$ is white and Gaussian distributed.
Now my question is, how does one derive or motivate
\begin{equation}\sum_{j=1}^N\sum_l \hbar \omega_{l,j}(a^{j\dagger}_l a^j_l + 1/2) + \sum_{j=1}^N\sum_l \chi_{jl} \sigma_z^j\left(a^{j\dagger}_l + a^j_l\right) \rightarrow \frac{1}{2} \sum_{j=1}^N \delta\epsilon_j(t) \sigma_z^j
\end{equation}
I already know that one has to assume something about the noise having a white power spectral density and it being Gaussian distributed. In addition to this I think one might have to assume the environment to have a high enough number of modes to be considered a continuum. But even with this it is not obvious to me at all. Does one substitute the above $J_j(\omega)$  for a white noise PSD to obtain the result?
I tried looking at the original Haken Strobl paper on this topic, but the derivations did not seem to start from the phononic bath, they just assumed the $\delta \epsilon_j(t)$ term from the start. I therefore understand that an exact derivation might not be there, but I would at least like to motivate the transition, perhaps with some high temperature limit or something of the sort.

A: Looking at Eq. (4), we can see that the coupling is essentially between the $\sigma_z$ of the two level systems, and the position $x$ of the photon modes.
Let's focus on a single site:
$$H_\text{I, one site} = \sum_{\text{mode }l} \chi_l \sigma_z x_l \, .$$
In English: the electron site interacts with a set of modes the photon field, indexed by $l$, with a coupling strength $\chi_l$, and that coupling is of the form $\sigma_z x$.
Let's think classically.
Each photon mode is a harmonic oscillator.
If those oscillators are in a thermal state, then the position $x$ of each oscillator is jiggling around randomly.
Since the position is directly coupled to the $\sigma_z$ of each two level system, then classically we're just straight-up saying that the wiggling bath makes the frequencies of the two-level systems wiggle.
In other words:
$$ \epsilon_j \sigma_z^j \stackrel{\text{classical}}{\longrightarrow} \left( \epsilon_j + \delta\epsilon_j(t)\right) \sigma_z \, .$$
Note that in the original post, the photon bare Hamiltonian is not present in Eq. (5).
My guess is that whatever approximation the authors actually used implicitly uses the interaction picture for the photons, which makes the bare photon Hamiltonian go away at the cost of introducing time dependence into $H_\text{I}$.
Of course now we want to know

*

*What assumptions had to be made for this approximation to work?

*What are the statistics (i.e. spectral density) of $\delta \epsilon_j$?
For the first, I bet one approximation made in the paper is that the photons and site energies are largely detuned.
If this weren't the case, the coupling might have $\sigma_{x,y}$ terms in it to begin with.
Whether or not those terms exist depends on the details of the coupling.
Anyway, that's one possible assumption.
The next assumption is probably something along the lines of the photon bath being "large" or "having short memory".
This assumption directly leads to the white noise spectral density stated in the paper.
To understand why, take a look at any text on the quantum master equation, for example in Exploring the Quantum by Serge Haroche.
In fact, another way to understand this is to realize that we have exactly the same situation as a qubit connected to a readout resonator.
That system is known to experience dephasing from shot noise in the resonator, as described in the very well known 2004 paper by A. Blais.


text:
Q: Embedded Jetty - use WebSocketUpgradeFilter together with AsyncProxyServlet I've got a class that extends AsyncProxyServlet to do proxying with Jetty:
Server httpProxy = new Server();
ServletHolder servletHolder = new ServletHolder(TunnelProxyServlet.class);
HandlerCollection handlers = new HandlerCollection();
httpProxy.setHandler(handlers);

ServletContextHandler contextHandler = new ServletContextHandler(handlers, "/", ServletContextHandler.SESSIONS);

contextHandler.addServlet(servletHolder, "/*");

Now I'd like to add WebSocket support to this.
I tried this:
try {
    WebSocketUpgradeFilter.configure(contextHandler);
    NativeWebSocketServletContainerInitializer.configure(contextHandler, ((context, container) ->
    {
      container.addMapping("/*", (req, resp) -> new WebSocketProxy().getWebSocketConnectionListener());
    }));
   } catch (ServletException ex) {
     Logger.getLogger(HttpProxy.class.getName()).log(Level.SEVERE, ex.getMessage());
   }

But the code never reaches this point.
How can I do proxying with WebSockets?

A: WebSocket Proxy is a very large and complicated topic.
First, let me start by saying that WebSocket proxying is possible starting with Jetty 10.
The basic support for WebSocket proxy was added to Jetty 10 in https://github.com/eclipse/jetty.project/pull/3365
Sadly, Jetty 9 has no support for WebSocket Proxy.
Either built into Jetty itself, or with enough core features within Jetty's WebSocket layer to allow you to implement it yourself.
Next, Jetty's AsyncProxyServlet is not capable of handling upgraded connections (like WebSocket).  That class can only handle HTTP requests (be it HTTP/1.0, HTTP/1.1, or HTTP/2.  With HTTP/3 support in the near future).
Some advice, when you do WebSocket proxying, you'll need to decide how you do it.
Are you going to proxy the frames as-is? (easiest, and most recommended approach).
Are you going to want to read the frame content? (requires complicated extension manipulation, extension preservation, frame preservation, and the ability to read partial messages from the frame level, etc)
Are you going to want to read the whole message (1..n frames) content? (this quadruples your memory requirements for websocket as its : remote websocket client -> websocket proxy server -> your proxy interested in messages -> websocket proxy client -> websocket backend server)


text:
Q: Swipeview - show preview/snippet of next item? I am using Swipeview (http://cubiq.org/swipeview) to create a touch-enabled carousel working on an iPhone and Android. The basics works great.
My problem starts when i try to get it to show 25% of the next slide pr default. The idea is that the user can see 1/4 of the next slide/image, which should then make them slide the image to reveal the next slide/image. The first image then disapears, the second image becomes 100% visible, aligned to the left, and the 3rd image is then visible by 1/4. And so on.
I have tried changing the div.style.cssText (in swipeview.js) to have a width of 75% instead of the default 100%. This works for the initial load, but when i scroll, the part of the 2nd image that was visible on slide 1, is now hidden on slide 2.
I made a fiddle to demonstrate: http://jsfiddle.net/zeqjN/1/ (test it in Chrome and try dragging the image to the left)
Any ideas as to how i can modify swipeview.js to fit my needs?

A: You can achieve this with css only. Just add a scale effect on the items.
.scroller .scroll-item { float: left; -webkit-transform: scale3d(1.1,1.1,1.1) }

Check out:
http://jsfiddle.net/frapporti/Xt9dM/


text:
Q: After HDP cluster kerberized Journal node service having issue while starting Below is the error after cluster kerberized.
Exception in thread "main" java.io.IOException: Login failure for jn/keystone.mwbsys.com@EXAMPLE.COM from keytab /etc/security/keytabs/jn.service.keytab: javax.security.auth.login.LoginException: Unable to obtain password from user

A: added keystone.mwbsys.com in /etc/hosts file
and then restarted the journal nodes its fixed the issue. I know this is not the permenent solution but it worked.


text:
Q: How to add link without ruining transition CSS/HTML how would i go about so that when a user clicks on an image it takes them to another page although without ruining the transition as everything ive tried works but removes the transition or makes the one of the images dissapear
html

css
.box1 {
  width:430px;
  height:450px;
}

#imagetrans {
  position:relative;
  margin:0 auto;
}

#imagetrans img.top:hover,
#container > div img.top:hover {
  opacity:0;
  margin:0 auto;
}

#imagetrans img,
#container > div img {
  position:absolute;
  -webkit-transition: opacity 0.3s ease-in-out;
  -moz-transition: opacity 0.3s ease-in-out;
  -o-transition: opacity 0.3s ease-in-out;
  transition: opacity 0.3s ease-in-out;
}

Any ideas?

A: have you tried adding "a" to the CSS
#imagetrans img,
#container > div img a {
    position:absolute;
    -webkit-transition: opacity 0.3s ease-in-out;
    -moz-transition: opacity 0.3s ease-in-out;
    -o-transition: opacity 0.3s ease-in-out;
    transition: opacity 0.3s ease-in-out;
}


text:
Q: Partial derivative notation confusion Consider the two-dimensional fluid flow represented by the Lagrangian transformation
\begin{equation}
    \vec{u} = \vec{X}(\vec{a}, \tau) = (a+\Gamma b \tau , b)
\end{equation}
where $\vec{x} = (x,y), \vec{a} = (a,b) , \Gamma = constant$
Compute the Lagrangian velocity field:
\begin{equation}
    \vec{v}(\vec{a}, \tau) = \frac{\partial \vec{X}(a, \tau)}{\partial \tau}
\end{equation}
This professor I have uses different mathematical notation that I am used to and for some reason this question is tripping me up when I feel like it is really easy


text:
Q: Dispatch on union types in Haskell I'm trying to write a function that is polymorphic on a String or Num argument in Haskell.
I've written some pseudocode that doesn't compile:
numDigits strOrNum =
  if isString strOrNum then length strOrNum
  else isNum strOrNum then length (show strOrNum)

numDigits 1000   -- Should return 4
numDigits "1000" -- Should return 4

Note isString and isNum are not real Haskell functions, they're just for demonstration.
Coming from Lisp, strOrNum is a union type, and this code would run.
I know typeclasses are needed for ad-hoc polymorphism in Haskell, but I'm not sure how to piece it together.

A: Whether it's better to model something as a sum-type or a type-class is I think an  intuition that you simply build over time (sum-types are more often the better option).
But since you mention

I know typeclasses are needed for ad-hoc polymorphism in Haskell, but I'm not sure how to piece it together.

here's a hopefully intuitive explanation.
Basic idea
Basically you're saying that there is a whole selection of types that your code can work with. You should try to formulate what those types have in common - i.e. why do you accept those types but reject others. You then define a type-class that captures this and implement most of your code in terms of this type-class.
Your example
To illustrate it on your example.
You're accepting numbers and strings (that represent numbers) because you say that both can be represented as sequences of digits and you want to define a function that counts those digits. It probably then makes sense to define a type-class that captures the ability to be written as a sequence of digits.
class IsBase10Positional t where
  digits :: t -> [Int]

you'd then define the instances for your types:
instance IsBase10Positional Int where
    digits n = D.digits 10 n

instance IsBase10Positional String where
    digits chars = digitToInt <$> chars

D.digits comes from http://hackage.haskell.org/package/digits-0.3.1/docs/Data-Digits.html#v:digits
digitToInt from https://hackage.haskell.org/package/base-4.15.0.0/docs/Data-Char.html#v:digitToInt
your numDigits function is then defined on all types that are part of this type-class:
numDigits :: IsBase10Positional a => a -> Int
numDigits x = length (digits x)

Conclusion
It is often pretty hard to formulate what is the common behavior that the type-class is supposed to capture. If you start adding a lot of functions into the type-class itself then you probably failed to capture the right essence of what the types have in common (in your application's domain).

A: You can this kind-of working with this:
data MyNum
  = IntNum Int
  | StrNum String

numDigits :: MyNum -> Int
numDigits (IntNum n) = length $ show n
numDigits (StrNum s) = length s

instance Num MyNum where
  fromInteger = IntNum . fromInteger
  -- note: skipped the rest (won't work really well sorry)

instance IsString MyNum where
  fromString = StrNum

here is an example in GHCi:
> :set -XOverloadedStrings
> numDigits "1000"
4
> numDigits 1000
4

This is working as 1000 as a literal is considered a type of any Num - fromInteger will be used to convert this into the target-type.
Same for "1000" when you enable the OverloadedStrings extension in GHC this will be treated as an IsString instance using fromString
I'd consider this just a nice trick for this question though - the Num instance is obviously incomplete.
I'd have to give this some thought, but I think this cannot be turned into a lawful Num instance because of the StrNum part (allowing for StrNum "bad" for example)
My hunch is that you get into trouble because you'd have to use StrNum ... values a both 0 and 1 and if those both are equal the resulting ring can only really be {0} (if you even allow for it)
Note: this is no proof and I can (and probably am) wrong ...

A: Maybe this is what you want?
{-# LANGUAGE FlexibleInstances #-}
class HasNumDigits a where
  numDigits :: a -> Int

instance HasNumDigits Int where
  numDigits n = length (show n)

instance HasNumDigits String where
  numDigits s = length s

-- >>> numDigits (1000 :: Int)
-- 4

-- >>> numDigits "1000"
-- 4

Alternatively, a sum type is often a better alternative than a union type:

data StrOrNum = Num Int | Str String

numDigits strOrNum = case strOrNum of
  Str str -> length strOrNum
  Num num -> length (show strOrNum)

-- >>> numDigits (Num 1000)
-- 4

-- >>> numDigits (Str "1000")
-- 4


text:
Q: RabbitMQ Request-Response pattern - consumer stops listening to queue after processing first message I'm trying to implement RabbitMQ Request-Response pattern.
My goal is that there would be always one consumer that listens to a queue and replies to messages.
So I've set the server up by:
var consumer = new EventingBasicConsumer(channel);

channel.BasicConsume(queue: 'listensToThisQueue',
   noAck: true,
   consumer: consumer);

consumer.Received += (model, ea) =>
{
   // Replying to client
   channel.BasicPublish(exchange: '',
            routingKey: routingKey,
            basicProperties: props,
            body: message);
   // Basic ack
   channel.BasicAck(deliveryTag: incomingDeliveryTag,
            multiple: false);
}

Everything actually works fine:

*

*Client sends first message

*Server receive and reply

*Client gets the message

The only problem is that after finshing Received method (After executing BasicAck) - Consumer stops listening to listenToQueue (I actually see 0 consumers on this queue in the UI management).
Why is that ?

A: This is happening because you are subscribing to the queue with noAck set to True. In this case, the consumer crashed after the first message was delivered (which is why you see 0 consumers). So you have to subscribe to the queue with noAck set to False.


text:
Q: Continuous concave functions Let $f:(0,+\infty)\to\mathbb{R}$ be a concave and continuous function. I know that $f$ satisfies the following inequalities (for all $x,y\in(0,\infty)$):

(1) $f(\lambda x+(1-\lambda) y)\geq\lambda f(x)+(1-\lambda)f(y)\;\;;0<\lambda<1$
(2) $f(x+h)+f(x-h)-2f(x)\leq0 \;\;; h>0$

(3) $\frac{f(x+h_2)-f(x)}{{h_2}}-\frac{f(x)-f(x-h_1)}{{h_1}}\leq0\;\;; h_1,h_2>0$

(4) $\frac{f(x_4)-f(x_3)}{{x_4}-x_3}\leq\frac{f(x_2)-f(x_1)}{{x_2}-x_1}\;\;; x_4>x_3>x_2>x_1$

(5) $\frac{1}{2}(f(x_2)+f(x_1))\leq\frac{1}{x_2-x_1}\int_{x_1}^{x_2}f(u)du\leq f(\frac{x_2+x_1}{2})$

In addition, I know that (1) and (4) are equivalent moreover (2) implies  (3) also (3) implies  (4) after that (4) implies (5). Now my question is :

How can I prove that (2) implies (3) and how about (4) implies (5)? thanks a lot.


text:
Q: How Can I Store My Images On The Server How do I store a photo on the server.
I store them in a directory - "D:\zjm_code\basic_project\pinax\media\default\pinax\images\upload" but this now a lot of images.
Is there another simple way?
Thanks

A: There are two common options.
1) Store them on the file system on the server, preferably not all in one directory - but split logically.
2) Store the images in a database, if you are using MySql you would do this using the "blob" type.

A: When you store all the images in one directory it could quickly become unmanaged due to huge number of files. You can put your images in subdirectories based on md5 or sha1 hash function. Usually 2 levels of subdirs is enough.
In this case your directory images/upload will contain subdirs with the names 00, 01, 02 .. FF (256 names total) and each of these 256 directories in turn will contain directories with names 00 through FF giving you in total 256*256 directories on level 2.
For each uploaded file you calculate hash function (not necessary based on it's content, but on some unique data) and take [0:2] as a name of first directory and [2:4] as a name of second level directory.
This would be helpful in creating directories: mkdir -p functionality in Python