Random math questions (modular arithmetic & notation)

Question: I found this amazing wall clock picture on the internet but I really don't know a few things. I don't know what's $B'_L$, 3, why $2^{-1}\equiv 4[7]$ and the one with the black and white circles.
For $B'_L$, I thought first that it could be Bernoulli numbers but figured it out that it was something completely different. For $2^{-1}\equiv 4[7]$, I've been thought modular arithmetic but never with fractions or inverses, so it doesn't make much sense to me. For the last one, I thought it was braille but found out that numbers was completely different.
So can anyone explain me what are these?
Comment: Here ... http://math.stackexchange.com/questions/57458/what-is-b-l-and-why-is-it-equal-to-1
Comment: `3` is the HTML entity with code point `0x33 = 51`, which is the digit '3'. $2^{-1} \pmod{7}$ is the modular inverse of $2$ modulo $7$, which is $4$. `0x0B` is hexadecimal $11$. "the one with the black and white circles" is a binary notation $1\cdot 2^3 + 0\cdot 2^2 + 0\cdot 2^1 + 0\cdot 2^0 = 8$.
Comment: In binary, 8 is 1000. Since $2*4 = 8 = 1$ modulo 7, we can write $4 = 2^{-1}$ mod 7.
Answer: I actually own this physical clock.  It came with a small slip of paper explaining each number as follows (hyperlinks added):

Geek Clock Cheat Sheet
1) Legendre's constant is a mathematical constant occurring in a formula conjectured by Adrien-Marie Legendre to capture the asymptotic behavior of the prime-counting function.  Its value is now known to be exactly 1.
2) A joke in the math world: An infinite number of mathematicians walk into a bar.  The first one orders a beer.  The second orders half a beer.  The third, a quarter of a beer.  The bartender says, "I get it" and pours two beers.
3) A unicode [sic] character XML "numeric character reference."
4) Modular arithmetic, also known as clock arithmetic, is a system of arithmetic for integers, where numbers "wrap around" after they reach a certain value.  The modular multiplicative inverse of 2 (mod 7) is the integer /a/ such that 2*/a/ is congruent to 1 modulo 7
5) The Golden Mean ... reworked a little.
6) Three factorial 3*2*1
7) A repeating decimal that is proven to be exactly equal to 7 with Cauchy's Convergence Test.
8) A graphical representation of a binary, or base-2 number
9) An example of a base-4 number, which uses the digits 0, 1, 2 and 3 to represent any real number.
10)A binomial coefficient, also known as the choose function.  5 choose 2 is equal to 5! divided by (2!*(5-2)!)
11) A hexadecimal, or base-16, number
12) A radical
Design by eagleapex.com
Answer: I don't know about the first two. But for the last two...
Actually, it is $2^{-1} \equiv 4 \pmod 7$. For $x \in \mathbb{R}\setminus\{0\}$, $x^{-1}$ is the unique real number such that $xx^{-1} = x^{-1}x = 1$. So $2^{-1}$ modulo $7$ is the unique number (modulo $7$) such that $2\times2^{-1} = 2^{-1}\times 2 \equiv 1 \pmod 7$. As $2\times 4 = 4\times 2 \equiv 1 \pmod 7$, $2^{-1} \equiv 4 \pmod 7$.
As for the dots, think about binary where a black dot is a one and a white dot is a zero.


Assessing deviation from the mean without Chebyshev's inequality

Question: I have a set of experimental data which comprises distances between successive points:

And a simulation which attempts to recapture the experimental data by choosing points at random and calculating the distances between them. This is repeated many times as to create a population of simulations. The red line below shows the simulated population average:

<code>x-axis = No. of Distances (plotted in increasing size)
y-axis (logarithmic) = Distance size
</code>
Neither the experimental data nor the simulated data fits a normal distribution (as assessed by the one-sample Kolmogorov–Smirnov test). Given the nature of the data i.e. distances between successive points and visual inspection of the data, a gamma-distribution appears to best fit the data.
I need to be able to calculate by how much any given simulation can deviate from the mean such that I can place two lines either side of the population average and show whether or not the experimental data (blue line) falls within this range. This is largely because the experimental data is NOT population based and represents a single sample.
As the 68–95–99.7 rule does not apply here - is there any more precise method than using Chebyshev's inequality and -/+ 2-3SD? This produces a rather wide band that makes it difficult to assess changes in the simulation parameters.
EDIT:
Answer: If you are able to assume a distribution for your population, than you can invert the KS test in order to build a confidence band around the cumulative function of the population which will contain your estimation with a given confidence level.
Starting with formula for the statistic used in KS test
$$ D_n = \sup_x | F_n(x) - F(x) | $$
and knowing that the goodness of fit is built using critical values of Kolmogorov distribution you have
$$ \sqrt{n}D_n > K_\alpha$$
Now by choosing your alpha you are able to determine $K_\alpha$ such that
$$ P(K<K_\alpha) = 1-\alpha$$
So you can determine some quantity $D_\alpha$ such that $P(D_n>D_\alpha)=\alpha$ and use that as a width around the graph of $F(x)$.
See more details on KS test wiki page, section named "Setting confidence limits for the shape of a distribution function".
Comment: Great. I've calculated values of f(x) and then adjusted (x) +/- d calculated as 1.36/SQRT(n) for 95% confidence. This produces a surprisingly wide band (see OP edit). Is this due to a low sample level (n=83) or have I done this incorrectly? I've done all calculations on the population average.
Comment: Obviously the numbers depends on the sample size. Basically, the KS tests statistic works when n goes to infinity, so as larger you have n, the smaller the band you will get
Comment: I am unsure as to what to apply the KS test to. I generate 1000 sets of simulated data and subsequently decimate these into a population average  such that they can be overlaid with the experimental data (which is a single sample). I calculated d(0.05,n) using n=88, however in reality the population average is reflective of 1000 x 88 datapoints. How do I correctly go about this?


Are there any applicable options to Angular ui-select2 directive?

Question: Given the following Angular selec2 controller:
                <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject">
                    @*ng-options="project.WebsiteName for project in projectList"*@
                    <option value=''></option>
                    <option ng-repeat="project in projectList" ng-value="'{{ project.WebsiteGUID }}'">{{project.WebsiteName}}</option>
                </select>

Model data is retrieved as follows from the controller:
    $scope.projectList = dataFactory.getList("")   // no parameters
                            .success(function (result) {
                                $scope.projectList = result.value;
                                $("#projectListSelection").select2({ width: '240' });
                            })
                            .error(function (error) {
                                customUIFunctions.showError("Data Error - Unable to Load Project List"); // use default error message
                                console.log("data error");
                            });

Here's the issue:

When the control first appears on the screen, it looks like a plain old select drop-down control
For a fraction of a second, then its width goes to 0
The control's UI is updated again to look like the select2 control, however its width is only as small as the placeholder
After the control is loaded with data, it then resizes to 240px

When I try setting the width before the data is retrieved (before $scope.projectList = ...) I get the following errors:

query function not defined for Select2 s2id_projectListSelection ...
  angular.js:9402 RangeError: Maximum call stack size exceeded ...

Which makes sense as the DOM isn't fully loaded. So...
     $(document).ready(function () {
        $("#projectListSelection").select2({ width: '240' });
    });

However I still see the same issue, where the width conforms first to the placeholder, then to the wider setting once data is loaded.
I managed to get around this doing:
<select ui-select2 id="projectListSelection" style="width:240px;" . . .

However, that's kind of ugly.
The questions:

Is there a width option that will hold true whether or not data is loaded?
Is there a placeholder option that will allow me to display a message such as "Loading Data..." then display a different message ie. "Select a project ..." once the data is loaded?
Answer:
Your best option here is probably custom CSS that overrides the default.
Create a variable in your controller scope called placeholder with the initial value of "Loading data..." then watch for your data to load and change scope.placholder to "Select a Project...". Then on your element use placeholder="{{ placeholder }}"


How I solve file not found problem in python script?

Question: I had made a program where I require files from that directory where the python file is located. The files are located in the same folder where the python file located.
I can't write the full path of the file in the python script
I used the ./ method in the script but it gives error
Please help me to solve the problem
here is my code
'''
#code
root=Tk()
root.title("SOHAM YOUTUBE VIDEO DOWNLOADER")
root["bg"]='#1F1F1F'
root.iconbitmap("./img/youtube_(1).ico")
root.geometry("900x680")

file =PhotoImage(file="./img/youtube-icon.png")
headingIcon=Label(root, image=file)
headingIcon.pack(side=TOP, pady=3)

'''
My folder location

Here img is my required folder in YOUTUBE_VIDEO_DOWNLOADER.py which is my python file
My script error is given below
y"python "e:/python projects/YOUTUBE VIDEO DOWNLOADER/YOUTUBE_VIDEO_DOWNLOADER.py
Traceback (most recent call last):*emphasized text*
  File "e:\python projects\YOUTUBE VIDEO DOWNLOADER\YOUTUBE_VIDEO_DOWNLOADER.py", line 215, in <module>
    root.iconbitmap("./img/youtube_(1).ico")
  File "C:\Users\soham\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2073, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "./img/youtube_(1).ico" not defined

Comment: Please don't use images to describe anything. In this case use text to describe your folder hierarchy.
Comment: The error means that the ico file cannot be found.
Comment: I had use .ico file
Answer: One trick I use to account for this problem, is to use the __file__ variable (which holds the path of the scripts file) as my reference path and then write the path to the file I want.
If your directory looks like this:
my_dir
|> my_script.py
|> img/
   |> my_img.png

Then __file__ will be equal to C:\\...\my_dir\my_script.py.
And your image will be os.path.join(os.path.dirname(__file__), 'img', 'my_img.png')
Comment: I think you can print the full path you made and the path that uses `__file__`. Compare them and adjust the code accordingly.
Comment: Sir I had tried it but it not working
icopath = os.path.join(os.path.dirname(__file__), 'img', 'youtube_(1)')
root.iconbitmap(icopath)
Comment: Error
$ python "e:/python projects/YOUTUBE VIDEO DOWNLOADER/YOUTUBE_VIDEO_DOWNLOADER.py"
Traceback (most recent call last):
  File "e:\python projects\YOUTUBE VIDEO DOWNLOADER\YOUTUBE_VIDEO_DOWNLOADER.py", line 221, in
    root.iconbitmap(icopath)
  File "C:\Users\soham\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2073, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "e:\python projects\YOUTUBE VIDEO DOWNLOADER\img\youtube_(1)" not defined
Comment: I think you forgot the `.ico` in the image name
Comment: no sir I had wrote .ico file
and it start working when I gave the full path of the file
but I require to give it a short path like "./img/youtube_(1).ico"
Comment: when I print the path it gives "e:\python projects\YOUTUBE VIDEO DOWNLOADER\YOUTUBE_VIDEO_DOWNLOADER.py"
Comment: Sir I have to replace "YOUTUBE_VIDEO_DOWNLOADER.py" to "img\youtube_(1)"
Comment: Sir I had tried  a code "root.iconbitmap(__file__+"/../img/youtube_(1).ico")"
 and it worked
Comment: Thank you Sir, for help me and spend your precious time


Belt (singing) exercises and techniques?

Question: So, I have worked hard to develop a middle voice and head voice but it doesn't have the really powerful tone of a belt voice. Can anyone give me audio exercises or refer some source for belting techniques and exercises?
Is there any Estill Teacher who can write down some theory and offer exercises in response to this question?
I was refered Singing and the Actor and Belt Voice training but currently I do not have funds to buy these. If anyone has mp3s from these programs, please upload.
Thanks.
Answer: I posted this as answer, but it's not designed as one. I did it to have more room. :)
Belting technique should really only be attempted after a thorough understanding of the mechanics and technique of singing, and at least a baseline amount of classical technique. It takes most singers years to get to a point where they can develop their belting voice naturally and safely. Vocal health is a HUGE issue here; I can't emphasize that enough. Many pop stars have suffered from poor technique, most recently Adele, but victims abound.
http://voicecouncil.com/has-adele-been-a-bad-girl/
I cannot tell for sure from your question, but I get the feeling (correct me if I'm wrong) that you've not taken in-person lessons before. That's fine, and you can accomplish some basic technique, including breath support, pitch control, etc. on your own. However I have to say that belting is not something you should try without a teachers assistance, in person. There's really no substitute for it. Even some teachers, teaching in person lessons have trouble explaining what must be done in a mutually understood way. When you're referring to hidden body muscles that are required to do incredibly complex things, everyone's going to describe things a different way.
If you're at all serious about learning to sing, concentrate on healthy, classical technique for awhile. (Note classical doesn't necessarily refer to classical music.) Try as hard as you can to find a good teacher you can connect with. They may be expensive, but it's cheaper than vocal surgery, and much better than ruining your voice for life. Too many people try to push their voice too hard, too early, and with too little technique. They pay a steep price for it.
Answer: Taking the previous comment in light, it is also important to develop a good practice routine.
You should treat your voice like you would any other muscle; warm-up than exercise.  Humming and Vocal Fry is awesome for a warm up routine, and for developing strength and smoothness, Lip trills are indispensable.


Pulling in YouTube Videos from Specific Channel

Question: I'm trying to pull all videos from a specific youtube channel.
I'm getting this error:
Fatal error: Call to undefined function getYTid() in C:\inetpub\wwwroot\ped.php on line 71

Any suggestions?
class ChannelFeed {

    function __construct($username){
        $this->username=$username;
        echo $this->username;
        $this->feedUrl=$url='http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?orderby=updated';
        $this->feed=simplexml_load_file($url);
    }

    public function getYTid() {

        $ytURL = $this->feed->entry->link['href'];

        $ytvIDlen = 11; // This is the length of YouTube's video IDs

        // The ID string starts after "v=", which is usually right after
        // "youtube.com/watch?" in the URL
        $idStarts = strpos($ytURL, "?v=");

        // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my
        // bases covered), it will be after an "&":
        if($idStarts === FALSE)
        $idStarts = strpos($ytURL, "&v=");
        // If still FALSE, URL doesn't have a vid ID
        if($idStarts === FALSE)
        die("YouTube video ID not found. Please double-check your URL.");

        // Offset the start location to match the beginning of the ID string
        $idStarts +=3;

        // Get the ID string and return it
        $ytvID = substr($ytURL, $idStarts, $ytvIDlen);
        return $ytvID;
    }

public function showFullFeed(){
$vidarray = array();
    foreach($this->feed->entry as $video){
        $vidarray[] = $video->link['href'];
    }
    return $vidarray ;
}

 };
$youtube = new ChannelFeed('channel_name');
$vids = $youtube->showFullFeed();
$vidIDs = array_map(getYTid(),$vids);

Comment: I doubt you meant `$this->feedUrl=$url='http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?orderby=updated'`, which implies you have copy/pasted code from somewhere without understanding what it does.
Answer: I revised this to work correctly.....
    class ChannelFeed {
    function __construct($username){
        $this->username=$username;
        //$this->feedUrl=$url='http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?orderby=published';
        $this->feedUrl=$url='http://gdata.youtube.com/feeds/api/videos?author=' . $username;
        $this->feed=simplexml_load_file($url);
    }

    public function getYTid($links) {
        $IDs = array();
        foreach ($links as $href) {
            $ytURL = $href;
        //$ytURL = $this->feed->entry->link['href'];

            $ytvIDlen = 11; // This is the length of YouTube's video IDs

            // The ID string starts after "v=", which is usually right after
            // "youtube.com/watch?" in the URL
            $idStarts = strpos($ytURL, "?v=");

            // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my
            // bases covered), it will be after an "&":
            if($idStarts === FALSE)
            $idStarts = strpos($ytURL, "&v=");
            // If still FALSE, URL doesn't have a vid ID
            if($idStarts === FALSE)
            die("YouTube video ID not found. Please double-check your URL.");

            // Offset the start location to match the beginning of the ID string
            $idStarts +=3;

            // Get the ID string and return it
            $ytvID = substr($ytURL, $idStarts, $ytvIDlen);
            $IDs[] = $ytvID;
        }
        return $IDs;
    }

    public function showFullFeed(){
    $vidarray = array();
        foreach($this->feed->entry as $video){
            $vidarray[] = $video->link['href'];
        }
        return $vidarray;
    }
};

$youtube = new ChannelFeed('channel_name');
$vids = $youtube->showFullFeed();
$vidIDs = $youtube->getYTid($vids);

Answer: Without checking out the rest of your code, your array_map is using a method of your class, ChannelFeed. Per the documentation, you must use an array to tell it where the function you're wanting to apply as a callback is located.
Change the last line of your code to this:
$vidIDs = array_map(array($youtube, 'getYTid'), $vids);

Comment: thanks, with your code and a bit of tinkering i got it to work
Answer: $vidIDs = array_map(getYTid(),$vids);

Not only are you passing the result of calling getYTid() to array_map rather than a reference to the function, but you're not passing any object context... and getYTid is a member function.
Read again the documentation for array_map, then try:
$vidIDs = array_map(array($youtube, "getYTid"), $vids);

Prior to PHP 5.3, in which object passing became by-reference by default, you'll need:
$vidIDs = array_map(array(&$youtube, "getYTid"), $vids);


Add "Add new content" custom block to a specific page

Question: I would like to add a block which contain a button for when the user click would redirect to the Add new content page with a specific content type.
I'm building some sort of a book store a would like to let users (Anonymous, Logged-in users) to be able to upload content of a specific type to be featured in that page (once approved of course).
For now, I can only list contents added by admin or anyone with the permission but using the default Add new content menu.
How can I achieve this?
Answer: If you have already given anonymous and authenticated users permission to create new content of the content type, you can simply add the link in the block.
If you're creating a custom block through the admin interface, you can make the link as you normally would.
For example, if you want to add a link to the page content type,
Add a page
For node content types, the link pattern is /node/add/CONTENT_TYPE_ID.
For taxonomy, it's /admin/structure/taxonomy/manage/TAXONOMY_VOCAB_ID/add.
The easy way to find these links is to navigate to the add content page and then copy the link.
Comment: Thanks. Trying your suggestions


How to calculate surface integrals of vector fields?

Question: I have a question about surface integrals of vector fields.
The formula I was given is the following when the surface is a rectangle of sides $a$ and $b$ in the $xy$ plane and $\vec{u}(r)$ the vector field :
$$\iint_S \vec{u}.d\vec{S}=\int_0^b \int_0^a(\vec{u}\cdot\vec{e_z})dxdy=\int_0^b \int_0^au_zdxdy$$
Now I tried to use with a cube of sides $a$ like this one
The formula seems to work with the field $\vec{u}(r)=(1,0,0)$ with $$\iint_S \vec{u}.d\vec{S}= \iint_{S_{x,1}} -u_x.dydz + \iint_{S_{x,2}} u_x.dydz = -\int_0^a \int_0^adydz+\int_0^a \int_0^adydz=0$$
But the same reasoning does not work for $\vec{u}(r)=(x,0,0)$ where I write
$$\iint_S \vec{u}.d\vec{S}= \iint_{S_{x,1}} -u_x.dydz + \iint_{S_{x,2}} u_x.dydz = -\int_0^a \int_0^axdydz+\int_0^a \int_0^axdydz=0$$
But this is false because the correct value is $a^3$. Should I evaluate $\vec{u}$ on each surface before integrating ? That would give $$\int_0^a \int_0^a0dydz+\int_0^a \int_0^aadydz=a^3$$ What if the value is not the same for a face ? What if the field was $\vec{u}(r)=(x+y,0,0)$ ?
Answer: Please note that,
$S_{x,1}$ is in plane $x = 0$ so for the first integral $u_x = x = 0$
$S_{x,2}$ is in plane $x = a$ so for the second integral $u_x = x = a$
$\displaystyle \iint_S \vec{u}.d\vec{S}= \iint_{S_{x,1}} -u_x \ dy \ dz + \iint_{S_{x,2}} u_x \ dy \ dz$
$ \displaystyle  = 0 + \int_0^a \int_0^a a \ dy \ dz = a^3$
If the vector field is $\vec{u} =(x+y,0,0)$
Then for the first integral, it is $(y, 0, 0)$ and for the second integral, it is $(a + y, 0, 0)$.
Can you see why the net flux through both surfaces will still be $a^3$?
Comment: Yes I got it thanks


Can't upload war file through tomcat manager dashboard with VPN

Question: I have configured server and deployed war file earlier. All of those I did in Digital Ocean's CentOS server. Now I need to configure  CentOS server In Local Data Center. I have configured Tomcat as usual way. Tomcat is running. I can access tomcat manager dashboard. Problem is when I am trying to deploy war file I am getting error. This is the dashboard of tomcat manager.

But when I hit deploy I am getting connection error.

Note that, I had to access provided IP address with VPN. Because it
  was a requirement to access this IP with VPN.

As I am getting error in 80 port I changed tomcat port to 8080.
Then I traced server and Get this error
java.net.BindException: Address already in use (Bind failed)
       at java.net.PlainSocketImpl.socketBind(Native Method)
       at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
       at java.net.ServerSocket.bind(ServerSocket.java:375)
       at java.net.ServerSocket.<init>(ServerSocket.java:237)
       at org.apache.catalina.core.StandardServer.await(StandardServer.java:440)
       at org.apache.catalina.startup.Catalina.await(Catalina.java:775)
       at org.apache.catalina.startup.Catalina.start(Catalina.java:721)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
       at java.lang.reflect.Method.invoke(Method.java:498)
       at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
       at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)

Also getting this error
17-Feb-2019 17:18:59.396 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
17-Feb-2019 17:18:59.396 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
17-Feb-2019 17:18:59.396 INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
17-Feb-2019 17:18:59.426 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
17-Feb-2019 17:18:59.426 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["http-nio-8080"]
17-Feb-2019 17:18:59.426 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["ajp-nio-8009"]
17-Feb-2019 17:18:59.427 INFO [main] org.apache.coyote.AbstractProtocol.destroy Destroying ProtocolHandler ["ajp-nio-8009"]

Any help will be appreciated!!
Comment: This is your first deployment in the new data center? Your HTTP connector is running on port 80 and Tomcat was started as root? Nothing else is running on this port (e.g. Apache)?
Comment: @Freddy ,   Yes this is first time in this data center. Yes tomcat is started as root. But I don't know how to check Other programs are running on port 80. Can you please help me ?
Comment: Run `netstat -tlpn | grep ':80'` as root. The output shows the running PID and program if there is something running.
Comment: @Freddy I have changed port to 8080. When I use `netstat -tlpn | grep ':8080' ` I am getting this `tcp6       0      0 :::8080                 :::*                    LISTEN      106872/java`
Comment: @Freddy Now I am getting error `java.net.BindException: Address already in use (Bind failed)` . What an I do now :( ?
Comment: I have changed tomcat port 80 to 8080 then started tomcat again. After all of this I am getting `java.net.BindException: Address already in use (Bind failed)` What should I do now ?
Comment: After changing port to 8080.
Comment: Start over. Stop tomcat (if running). Make sure there are no java processes running (`ps aux|grep java`). Kill running java processes (`kill -9 PID`). Run netstat and make sure nothing is listening on the port. Open second terminal and run `tail -f` on your catalina.*log. Delete your webapp inside the "webapps" folder. _Then_ start tomcat. Check again with netstat and watch the output of your logfile. _Then_ deploy your webapp (still watching the logfile).
Comment: @Freddy I have no `webapp` folder inside `webapps` folder. And can you please write command step by step ?
Comment: I have no `webapp` folder inside `webapps`
Comment: @Freddy I updated my question. Can you help me ?
Answer: I was deploying someother .war file in tomcat 8.
To successfully deploy change the max upload and max request.
Open tomcat installation directory then edit  Tomcat 8.0/webapps/manager/WEB-INF/web.xml in a text editor
and find the lines with the text: <max-file-size> and <max-request-size>.
Increase its value.
Ex:
<max-file-size>100428800</max-file-size>
<max-request-size>100428800</max-request-size>

This worked for me.
Comment: great ! you saved my day :)


Chi square test when sample sizes are different?

Question: I have two samples from two different language corpora: Sample one contains 82 verbs, sample 2 contains 89 verbs. I want to compare the frequencies of a particular verb type, let's call them oral verbs, across both samples and see if they differ significantly from each other (I would have used another verb type in which I don't expect differences as a comparison group for a 4-cell chi square test). Originally, I wanted to do a chi square test but then realized that wouldn't be possible given the different sample sizes. Which test might I be able to apply?
 Thank you!
Answer: You can use a chi-squared test in your example with different sample sizes. Your "another verb type" would be verbs that are not oral verbs, i.e. all the other verbs
Suppose in your example, $10$ of the $82$ verbs in sample one were oral verbs and $72$ were not, while $20$ of the $89$ verbs in sample two were oral verbs and $69$ were not. Then the table for your four cell chi-squared test could look like
10  72  |  82
20  69  |  89
__ ___    ___
        |
30 141  | 171

and in R you might get
chisq.test(rbind(c(10, 72), c(20, 69)))

#     Pearson's Chi-squared test with Yates' continuity correction
#
# data:  rbind(c(10, 72), c(20, 69))
# X-squared = 2.4459, df = 1, p-value = 0.1178

so this example would not be statistically significant
Comment: Thanks Henry, that was quick and super useful!
Comment: @BjörnB - if a continuity correction is sensible for small samples then it is also sensible for large samples; it will then only make a small difference and so used to be ignored for hand calculations, but that is not a good reason now we use computers
Comment: Thank you for this good answer. I am wondering why the Yates Continuity Correction is applied (I checked the docs and figured that in the 2x2 case it is the default? [docs](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/chisq.test) ). However I dont really understand why, I thought Yates Correction is necessary for a total N that is smaller than 40?
Answer: Just in case anyone is looking for the Python version of this, you can use scipy ch2_contingency: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html
Using the same example as @Henry
import numpy as np
from scipy.stats import chi2_contingency

obs = np.array([[10, 72], [20, 69]])
chi2, p, dof, ex = chi2_contingency(obs)
print(chi2, dof, p)
> 2.44591778277931 1 0.11783094937852609

Which is the same result as R chisq.test


add captch to registration modal box

Question: I have a modal box for login and registration for my site.
example.com
I want to add the captcha with the registration process.I added the captcha module in my site. But the captcha only work with the drupal's default registration page but not work with the modal box's registration.
How can I add the captcha with the modal box.
Answer: Try something like the following:
<code>$form['my_captcha_element'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);
</code>
More info here :https://www.drupal.org/node/743056

add captch to registration modal box


Can I have a multivalued attributes in IotAgent-UL an OrionCB?

Question: My situation is as follows:
I have a device with multiple attributes. One of those attributes is called DTC (diagnostic trouble codes) that is intended to store a different quantity of error codes each time a meassure is sent. I mean, at a certain moment the device could send 0, 1 or more error codes.
What must I do in order to make DTC attribute something like a list?
I need to do that in IoTAgentUL and Orion CB.
Answer: In Orion you can use arrays to store multivalued attributes
example:
{
   "myAttr": {
     "type": "List",
     "value": ["a", "b", "c"]
   }
}

I don't know whether the UL protocol supports multivalued attributes.
Answer: After researching a while I figured it out.
In IoTAUL is not possible.
In IoTAJson yes it's possible. The way to reach that is doing the following:
The request's body has to be as follows:
{
    "myAttr": ["a", "b", "c"]
}


I need a way to retrieve and log the IMEI, Serial, ICCID, and MEID of an iPhone device connected via usb

Question: As it says in the title I'm after a way to retrieve and log the IMEI, Serial, ICCID, and MEID of an iPhone device connected via usb.
Ideally this method would work with multiple devices plugged in at once and export the information to a spreadsheet with the information separated by column.
Trying to develop a better inventory system for my company's iPhone fleet.
I've been struggling with this for a while now to no avail.
Thanks for looking!
Answer: You can use the command system_profiler SPUSBDataType from a shell to list the USB information, including the serial number of an attached iPhone - you could parse this.

USB Hi-Speed Bus:

  Host Controller Location: Built-in USB
  Host Controller Driver: AppleUSBEHCI
  PCI Device ID: 0x0aa6
  PCI Revision ID: 0x00b1
  PCI Vendor ID: 0x10de
  Bus Number: 0x24

    iPhone:

      Product ID: 0x12a8
      Vendor ID: 0x05ac  (Apple Inc.)
      Version:  6.02
      Serial Number: 797296a8472XXXXXXXXXf5806511452228ac9
      Speed: Up to 480 Mb/sec
      Manufacturer: Apple Inc.
      Location ID: 0x24300000 / 3
      Current Available (mA): 500
      Current Required (mA): 500
      Extra Operating Current (mA): 500

To get things like the IMEI you will need to communicate with the actual phone, probably using IOUSBLib and you will need to do a lot of research on the USB primitives supported by the iPhone as I don't know how well documented they are.
It is probably easier to use a commercial Mobile Device Management (MDM) platform.


Show that if p is an odd prime, then $2(p-3)! ≡ -1 $(mod p)

Question: problem: Show that if p is an odd prime, then :

$$2(p-3)! ≡ -1  \pmod p $$

I know that I have to use Wilson's theorem to solve this question but that's all I know..
Comment: https://artofproblemsolving.com/wiki/index.php/Wilson's_Theorem
Answer: Another way of stating Wilson's Theorem is
$$ (p-2)! \equiv 1 \pmod p $$
Considered $\pmod p,$ how would you describe the relationship of $(p-2)!$ and $2(p-3)! \; \; \; \; \; \; \; \; ?$
Answer: Starting with Wilson's theorem ( p is odd prime):
\begin{align}(p−1)!≡−1 \text{  ( mod p )}\\
(p−3)!(p-2)(p-1)≡−1\\
(p−3)!(p^2-3p+2)≡−1
\end{align}
Since $p^2-3p+2\equiv 2$ (mod p )
$$2(p−3)!≡−1$$


Custom views sort handler without table

Question: I am trying to expose data fetched from remote API and stored to $user object. I have accomplished that with a custom views handler suggested in this post Custom views handler without table.
However, I need to add sorting and filtering, so any help will be great.
This is the custom views field handler code.
<code>/**
 * A handler to provide a field that shows the license type.
 *
 * @ingroup views_field_handlers
 */
class views_handler_apms_license extends views_handler_field {

  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    // Remove the checkbox
    unset($form['alter']['alter_text']);
    unset($form['alter']['text']['#dependency']);
    unset($form['alter']['text']['#process']);
  }

  function render($values) {
    $user = user_load($values->uid);
    if (isset($user->apms['userLicense'])) {
      return $user->apms['userLicense'] ? t('BASIC') : t('FREE');
    }
    else {
      return NULL;
    }
  }
}
</code>
Comment: I'm sure I've seen it asked already, 2 or 3 times. But I can't recall to see this answered :( Also, *"I have accomplished that* - can you show / tell us how? maybe it will gove us some idea about answer.
Comment: Thank you for the question @Mołot,
I use a custom field handler with the following code http://pastebin.com/WwEMsQ6A.
Comment: Great question. I'm struggling with the same thing
Comment: Can you not create a custom filter handler to filter as your require?
Comment: It has never been solved! Maybe some of us can solve it for the community!
Answer: You can use the post_execute() method on your handler to remove entries from the list of all results. This is certainly a bit tricky but it works.
Comment: This is not the right way of doing it. Consider pagination/lots of records. post_execute/pre_render will act current result set only not on all the available records.
Comment: wouldn't   pre_render also work? if so, is post execute a better place to handle sorting?
Comment: I would argue that everything the execution result should be done in post_execute, if you change stuff related with rendering do it in pre_render.
Comment: Well, if you really need to support those cases you need to store values in the databsae ... there is simply no way around that.
Comment: Yeah, I was afraid that it wouldn't be possible. I tested post_execute as well and noticed it was limited because it contains the result of the query (which inckudes pagination). So it's not the answer I'd hoped for, but awarding bounty nonetheless.
Answer: Ok, just to put another idea out there...
If your data set is not too big then output all the unfiltered unsorted data to an html table, and then use a jQuery plugin to do all your sorting and filtering client side. Something like this would be suitable.
Comment: This is what the problem I was facing. The data set was huge and processing it on the server side was very expensive. The solution was to render all on one page and then use the jQuery plugin mentioned above for sorting, filtering and paging.

Custom views sort handler without table


Is my understanding of Null Hypothesis concept correct in this case?

Question: I am a beginner trying to learn statistics. I have a questions related to randomising simulations to accept or reject null hypotheses.
A random experiment was conducted with 48 bank managers to determine if there is a gender discrimination at the work place.
There were 48 IDENTICAL RESUMES, 24 of them belonged to male applicants, 24 belonged to female applicants.
24 managers received 24 RESUMES belonging to MALES, the distribution of the resumes to the managers was assigned at RANDOM.
similarly
24 managers received 24 RESUMES belonging to FEMALES, the distribution of the resumes to the managers was assigned at RANDOM.
Out of 24 males, 21 were promoted.
Out of 24 females, only 15 were promoted.
Meaning that the difference between the male promotion rate and female promotion rate was roughly 29%
NULL HYPOTHESIS: There was no discrimination. In other words, the 29% was due to chance.
ALTERNATIVE HYPOTHESIS: There was discrimination.
The same experiment was simulated 100 times and a dot plot was drawn.
X AXIS - Promotion percentage difference between male and female observed from -100% to +100%. Centre being 0%, left extreme being -100% and right extreme being 100%.
Y AXIS - DOT COUNT from each simulation.
I hope you can visualise it.
The video explained that, since from the 100 randomised simulations, since there were approximately only 2 or 3 data (represented by the DOTS) that had the difference of 29% just like the data we observed and LOTS of data (represented by the DOTS) which had -3% to 3% (negative 3% meaning, that females were favoured) we can reject the null hypothesis.
My questions is, if in these 100 randomised simulations, the dot plot showed that there were in fact MAJORITY (largest no. of DOTS) at the 29% mark, then we must ACCEPT the null hypotheses? That the discrimination occurred due the chance since even after randomising (making it appear the everything is due to chance) we still obtained the same data that the FIRST record of 29% difference showed?
Comment: Welcome to CV. Since you're new here, you may want to take our [tour], which has information for new users. "The video explained that", which video are you referring to? Also, please edit the question to fix the formatting. As a side note, it might be better to use "failure to reject the null hypothesis", instead of saying "accepting the null hypothesis." To get a better idea about the interpretation of the null hypothesis check [here](https://stats.stackexchange.com/questions/85903/why-do-statisticians-say-a-non-significant-result-means-you-cant-reject-the-nu).
Answer: The image is not being shown [1], but I'll try to answer based on what you wrote:
Your reasoning is correct. Roughly speaking, hypothesis tests are built upon a process that is fed using a sample of the data. In the most common form the result of this process is called a 'test statistic', which you compare to 'critical values' to decide whether or not to reject the null hypothesis.
In your example the statistics produced is the number of dots surrounding the 29% mark. Usually the troublesome part is coming up with critical values, which is often done through simulations.
The author in this case suggests that observing 2 or 3 dots leads to not rejecting the null hypothesis, so it makes sense to believe that a higher amount [2] would yield evidence for rejecting it. We could consider, as an example, that the critical value here is the number 10, so anything below it would lead to rejection of the null hypothesis.
[1] - new members can't post images, you have to upload them and then a link is embedded in your post. Try checking what went wrong in this process.
[2] - by higher we mean an amount  obtained through a rigorous method that associates such a number (or an interval) with the event described by the null hypothesis.
p.s.: as suggested in the comment in your question, try referencing any relevant third-party material you mention and fixing spelling and format issues in your question - it helps people help you better.


Possible to use get_absolute_url in {% url %} tags without the model object?

Question: I have a navbar where user can log in and after logging in, the user will have a dropdown menu with a link to his/her profile. Here are my codes:
navbar.html:
{% url 'students:student_profile_view' as student_profile_url %}

{% if request.user.is_authenticated %}

                         {{request.user.first_name}}

                            Profile

                            Logout

students/urls.py:
path('profile/<slug:slug>/', views.student_profile_view, name='student_profile_view'),

students/model.py:
from django.contrib.auth.models import User
from django.utils.text import slugify

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    slug = models.SlugField(blank=True, unique=True)
    avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)
    description = models.CharField(max_length=120, null=True, blank=True)

    objects = models.Manager()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(StudentProfile, self).save(*args, **kwargs)

    def __str__(self):
        return self.user.username

    def get_absolute_url(self):
        # return 'students:student_profile_view', (), {'slug': self.slug}
        return reverse("students:student_profile_view", kwargs={"slug": self.slug})

Navbar.html is a base template, it's not being rendered through a view where I could've passed an object and then called object.get_absolute_url Right now the profile button in my navbar dropdown menu is not working as it's not finding a reverse match for the user.
Also, after logging in I tried entering the link to profile manually in my browser like this: http://127.0.0.1:8000/students/profile/jimhalpert/
I get an error saying Reverse for 'student_profile_view' with no arguments not found. 1 pattern(s) tried: ['students/profile/(?P[-a-zA-Z0-9_]+)/$'] I assure you, the slug is correct.
Is there any way I can use get_absolute_url in navbar.html? why is hard coding the link in the browser not working? Please help.
Answer: This is all a bit confused.
The error presumably comes from the first line of that template, where you are attempting to reverse the students:student_profile_view URL without a slug. Clearly, that URL requires a slug, so you need to pass one when you reverse it. (I don't understand why you say that the slug is correct; you're not passing one at all.)
You appear to want to link to the profile of the current user; so you do have an object, namely request.user.studentprofile. So I don't understand why you don't just use that in the first place:
Profile

or, since you have defined a get_absolute_url method that you're not using, you could use that:
Profile

Either way, you should remove that first line that is causing the problem.
Comment: I'm sorry I should've been more clear. I recently added a slug and an absolute url to my student profile. Before that the regular student profile url (without the slug) was working fine. I think your second solution will work. Thanks for the explanation.


How to create a view of existing blocks?

Question: My aim is to make a Views grid of existing blocks in Drupal 7 (Might be possible without any additional code\module in Drupal 8).
I've tried to make a Content based View and filter it via Block ID's, but when I came to filter this View, I found no such option.
I've tried to check the "Relationships" option to see if I can add a relationship to Blocks but no such option was available there either.
Therefore, I wonder if a View of existing block is even an option naturally.
Comment: Blocks are not entities in Drupal so they are not supported by Views. I'm sorry to say your only option here is going to be custom code or using the excellent http://drupal.org/project/panels module which can get you most of the way there - though bear in mind it won't be automatic. i.e. You'll need to add the blocks yourself.
Comment: I did say Panels in my comment, no? :)
Comment: I might have missed it because of the color + too fast reading of the moment. Anyways, I'm sure I've seen a way to add the block themselves (after they have already been created). Indeed, Panels seems to be the best solution.
Answer: This question seems like a perfect illustration of why you'd use the Bean module (to actually create such view as in this question). Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
In this specific case, after you enabled the BEAN module, you should be able to create a view of blocks. As an illustration, have a look at this (basic) view (in Views export format):
<code>$view = new view();
$view->name = 'blocks_created_with_bean';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'bean';
$view->human_name = 'View of blocks created via the BEAN module';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'View of blocks created via the BEAN module';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'bid' => 'bid',
  'label' => 'label',
  'title' => 'title',
  'type' => 'type',
  'uid' => 'uid',
  'url' => 'url',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'bid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'label' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'uid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'url' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Block: Internal, numeric block ID */
$handler->display->display_options['fields']['bid']['id'] = 'bid';
$handler->display->display_options['fields']['bid']['table'] = 'bean';
$handler->display->display_options['fields']['bid']['field'] = 'bid';
/* Field: Block: Label */
$handler->display->display_options['fields']['label']['id'] = 'label';
$handler->display->display_options['fields']['label']['table'] = 'bean';
$handler->display->display_options['fields']['label']['field'] = 'label';
/* Field: Block: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'bean';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: Block: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'bean';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Block: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'bean';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Block: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_bean';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'view-of-blocks-created-via-the-bean-module';
</code>


How can I "shadow" the filesystem on Linux?

Question: On a Linux environment sometimes I need to run a script as root which will add/modify serveral files on my fs.
Basically I'd like to know exactly which files are modified and how WITHOUT opening the script and trying to guess the code.
I was thinking about using something like unionfs: the main fs would be accessible in readonly mode and all changes are written on a file used as a partition and "mounted" in write mode.
Are there other ways to achieve the same goal (i.e. other than unionfs)?
Answer: You can create a LVM snapshot, then mount the snapshot, run the script, then do a diff between the snapshot and the original.
Comment: how can I create a LVM snapshot? Can you provide a link?
Comment: A google search for "lvm snapshot" would get you there, but here you go: http://tldp.org/HOWTO/LVM-HOWTO/
Answer: Before today's fancy snapshotting and tracing technologies, people solved this problem through clever use of the LD_PRELOAD environment variable, which lets you override C library functions with your own replacements (called function interposition).  In this situation, you would wrap the open() system call, and when files are opened for writing you could:

Preserve the original (e.g., with a .bak extension or something)
Allow the installer to replace it
Produce a diff of the original vs. the modified version.

The installwatch program is one example of this sort of thing.  There are many other examples of this sort of solution, and there are also lots of other ways of using LD_PRELOAD to modify the behavior of binary programs.
Answer: This sounds like something that systemtap may be good at. Here's a blog post where someone wrote a systemtap script which will print out every file a user opens. One thing to keep in mind is that it's not specific to a process, so if you're running the script as a user who is doing a lot of other things, this may be pretty noisy; some modifications may be required. Though, it's a start.
Comment: Looking through the code, it may be pretty easy to modify it to lock onto a given pid instead of a uid.
Answer: An example for the LVM solution mentioned before.
Caveat: The filesystem you want to diff has to be on a lvm logical volume!
(And you have to have some free space on disk.)

# lvcreate --size 2G --name your-fs-snapshot --snapshot /dev/vg0/your-fs
  Logical volume "your-fs-snapshot" created

This takes a snapshot of /dev/vg0/your-fs at that moment. Then, do the changes you want to have recorded.
You can mount your snapshot as a copy of your-fs in the original state and diff with the tool of your choice, e.g. diff.

# mount /dev/vg0/your-fs-snapshot /mnt
# diff -q /original/volume/subdir /mnt/subdir

Do not forget to unmount and remove your snapshot, since while doing this, changes to the original volume are recorded as reverse diffs to the snapshot - until that fills up.

# umount /mnt
# lvremove /dev/vg0/your-fs-snapshot
Do you really want to remove active logical volume your-fs-snapshot? [y/n]: y
  Logical volume "your-fs-snapshot" successfully removed

Hint: If your logical volume contains a partition-table, you can add device entries via:

# kpartx -av /dev/vg0/your-disk-snapshot
Answer: You might also want to look into inotify, which will allow you to monitor filesystem events as they occur. It's similar to OS X's fsevent framework. Most distros will have an inotify-tools package.


How to maximize the infinity norm over a convex region?

Question: Consider the following optimization model
$$\begin{array}{ll} \text{maximize} & \displaystyle\max_{i \in S} |x_{i}|\\ \text{subject to} & Q(x)+ \displaystyle\sum_{i \in S}|x_{i}| \leq m\end{array}$$
where $x_{i} \in \mathbb R$, $Q(x)$ denotes a quadratic function of $x$, and $m$ is a known number.
Can we write this model as a quadratic and convex optimization model, which can be solved by optimization solvers such as Gurobi or CPLEX? In particular, how should we deal with a $\max \max$ type optimization problem?
Comment: Okay. You're _maximizing_ a convex function, so this is going to require the introduction of binary/integer variables
Comment: Yes. it is. Added to my question.
Answer: Your problem can be equivalently stated as
\begin{equation}
\begin{array}{rl}
\max_{x\in\mathbb{R}^n}\ &\|x\|_\infty\\
\text{s.t.}\ & x^{T}Ax+b^{T}x+\|x\|_1\leqslant{c}
\end{array}
\end{equation}
for some symmetric positive-definite matrix $A$. The constraint is convex, but since you are maximizing a convex function, this is a hard problem (NP hard, I believe). Consequently, to solve it, we will have to introduce some binary/integer variables.
Essentially, there are two things you need to be able to do:

Model the absolute values--i.e. introduce variables $y_i\geqslant0$ such that $y_i=|x_i|$ for all $i=1,\dots,n$. This is equivalent to enforcing that \begin{equation}
|x_i|\leqslant{y_i}\Leftrightarrow -y_i\leqslant x_i\leqslant y_i\ \text{ for all }i=1,\dots,n,
\end{equation}
which is easy, and that $y_i\leqslant|x_i|$ for all $i=1,\dots,n$. This will require two things: (1) a value $u_i>0$ such that $|x_i|\leqslant u_i$ holds for all $x$ in which we are interested, and (2) introducing a binary variable $z_i\in\{0,1\}$ for each $i=1,\dots,n$ such that $z_i=1$ iff $x_i\geqslant0$. Using (1) and (2), we have that
\begin{equation}
y_i\leqslant |x_i| \Leftrightarrow y_i\leqslant x_i+2u_i(1-z_i)\text{ and }y_i\leqslant -x_i+2u_iz_i.
\end{equation}
In your case, assumption (1) is basically equivalent to having an upper bound on the optimal objective value. In principle, you could just "pick a huge number", but this is inadvisable--the larger the values $u_i$ are chosen, the weaker the continuous relaxation of this problem becomes, the harder it becomes to solve. Try to pick smart values of $u_i$.
Model the maximum. This is outlined in the Gurobi documentation, for example. From the link:

For example, the MAX constraint $r = \max\{x_1,\ldots,x_k,c\}$ can be modeled as follows:
  \begin{equation}
\begin{array}{rcll}
r &=& x_i+s_j &\text{ for all }j=1,\dots,k\\
r &=& c+s_{k+1} & \\
z_1+\dots+z_{k+1} &=& 1 & \\
SOS1(s_j,z_j) && & \text{ for all }j=1,\dots,k+1\\
s_j &\geqslant& 0 & \text{ for all }j=1,\dots,k+1\\
z_j &\in& \{0,1\} & \text{ for all }j=1,\dots,k+1
\end{array}
\end{equation}
  The first two constraints state that $r \geq \max\{x_1,\ldots,x_k,c\}$, i.e., that the resultant variable $r$ has to be at least as large as each of the operand variables $x_j$ and the constant $c$. This can be modeled using inequalities, but we turned them into equations by introducing explicit continuous slack variables $s_j \geq 0$, which we will reuse below.
Those slack variables and the remaining constraints model $r \leq \max\{x_1,\ldots,x_k,c\}$, which is more complicated. In addition to the explicit slacks, this requires the introduction of binary auxiliary variables $z_j \in \{0,1\}$. The SOS1 constraints state that at most one of the two variables $s_j$ and $z_j$ can be non-zero, which models the implication $z_j = 1 \rightarrow s_j = 0$. Due to the third constraint, one $z_j$ will be equal to $1$ and thus at least one $s_j$ will be zero. Hence, $r = x_j$ for at least one $j$ due to the first constraint, or $r = c$ due to the second constraint.

This should be sufficient detail to figure this out for yourself.
Note on Gurobi
If you want to solve this with Gurobi, as you stated, then you should take advantage of Gurobi's general constraints. General constraints automatically handle both of the reformulations above, and hide all the messy details from you. In combination with their support for quadratic constraints, you should be well on your way to solving.
Comment: Thank you for your detailed answer. I accept it as a correct one.


Count music in beats, bars or seconds?

Question: I'm just wondering if when creating a song what's the correct way to time things. For example, I say the "chorus lasts 30 seconds" or the "chorus lasts 8 bars". Would I say this beat that I made a loop on "4 bars" or a loop of "16 beats".
I'm just wondering what's the convention.
Answer:
I'm just wondering if when creating a song what's the correct way to time things. For example, I say the "chorus lasts 30 seconds" or the "chorus lasts 8 bars"

Either could be correct - or more helpful - in different situations.
If you are mixing down an existing recording and programming in some mix automation, it may be more helpful to think in terms of seconds.
If you are giving some musicians instructions before a performance of a conventional piece with a traditional time signature, it's highly likely that thinking in terms of bars will be more helpful both because it's easier for the performers to count, and also because the duration in seconds may not be known at that point.
If you have composed an avant-garde ambient piece with no obvious beat and no conductor or other band-member providing a count of bars, it might be reasonable to make each performer watch a stopwatch and work in seconds - it would be unusual, of course.

Would I say this beat that I made a loop on "4 bars" or a loop of "16 beats".

Again, it totally depends. If you are working with reference to a machine or a piece of software that only counts beats, 'beats' might be better. If it counts both, 'bars' might be fine. If you are lining the beat up with an existing piece that's notated in bars and beats, 'bars' might be slightly better as it gives a sense of lining your beat up with the bar boundaries.

I'm just wondering what's the convention

None of the terms you've mentioned are unconventional, but each of them is more helpful and relevant in certain contexts.
As it happens, in the musical activity I'm doing at the moment, it makes sense most of the time to think in terms of sample numbers @a sampling rate of 44100Hz. That would be crazy for most purposes, but it's the right thing for this particular context.
Answer: How often do you think you might use a stopwatch? That's a ridiculous way to approach it. It will depend crucially on how fast the piece is.
Bars or measures are the the usual units used in music, and if you want to be precise, you use bpm to measure the tempo, which would produce the speed of what was hoping to be played.
Comment: This is not a ridiculous approach: where music is not a live performance, but part of an ad, a video, a game, etc the duration in seconds is a lot more important than the internal structure. No advertiser will tell you they need x bars of music for their product for example; they'll tell you they need x seconds with some event at this specific time, etc..
Comment: @Thomas - OP asked about 'a song', had what you say been mentioned, it certainly would put a different complexion on it. He didn't. That apart, tracks have been speeded up/slowed down for decades, and nowadays it's easier than ever, so that issue doesn't have to be a problem.
Answer: The term "Beats" is usually referring to the individual beats in a measure, in Jazz you would usually use "Bars" which is in classical terms, a "Measure". So using the term "Bars" is really the most used term when referring to whatever grouping of the notes indicated by the time signature, However, "Bars" is interchangeable with "Measures" so it just depends on your preferences (in musical composition, I prefer the term "Measure").
Answer: The correct way to TIME anything is in hours, minutes and seconds.
But if you're talking about describing the length of a piece of music, it depends on context.  For a TV advert you're mostly worried about the time. For scoring to film or tv you might need to consider 'frames'. If you're scoring a routine for 'Strictly' you may want to consider 'dancers' counts' which can be beats, bars, half-bars... according to style and tempo.  If you're making EDM it will doubtless be bars or beats. (Bars aren't always 4 beats of course, even in EDM.)

Count music in beats, bars or seconds?


How to show language switcher only on home page

Question: In my multilanguage site i am using Language switcher (User interface text) and I have it located in block called "Help". This block is shown in the middle of the site, where I want it. But I want it to be displayed only on homepage. I tried to hide by the restriction of a content type. But I wasn't successful.
Answer: Set block visibility to only show on <front>


Open document in my app from mail link in Android

Question: User receives a mail in android, which contains a link. That link has to get a document (PDF) from the server (this is fine), but it has to open it directly in my app.
How can this be done?
Answer: You'll have to add an Intent Filter like the following to your activity in the AndroidManifest.xml:
<code><intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="file" />
    <data android:host="*" />
    <data android:pathPattern=".*\\.pdf" />
</intent-filter>
</code>
Please note there is no way to force the system to open a pdf file in your app. If there are multiple apps that can handle the intent, the user will have to choose from a list.
Comment: Thanks. When will the user get the choice to select the PDF app? In the Browser? Is there another way to force the system to open it with my app, maybe without an URL?
Comment: I am afraid I don't understand the question in your first comment.
Comment: Ok, I'll try to explain it. What will happen, if I use your code above? When the user will open a PDF document, will he get a choice to open the PDF with: Adobe Reader, ThinkFreeOffice or MyAPP?
Comment: Exactly. If there are multiple apps that are able to open PDF files, the user will have to choose. However, if the user chooses to always open PDF files with an app, the dialog won't be displayed again.


clustering using two or more lists

Question: I would like to cluster words or sentences depending on if they get matched by an entry in another list.
Like so:
searchterms = ["windows pc", "linux laptop", "some gibberish"]
osCluster = ["windows", "linux"]

What I now want to do is go trough the searchterms and classify them using the osCluster list. In the end I want to have a csv like format like this:

windows pc, windows
linux laptop, linux
some gibberish, N/A

for now I have something like this:
for searchterm in searchterms:
for os in osCluster:
    if os in searchterm:
        print searchterm, os

which results in:
windows pc windows
linux laptop linux
[Finished in 0.0s]

However, I would like to tag the "some gibberish" as "N/A". If I just add:
else:
        print searchterm

this will results in:
windows windows
windows
linux
linux linux
gibberish
gibberish
[Finished in 0.0s]

I understand that this is what I have written the programm to do. But I think it is the wrong way of thinking. It would be much appreaciated if you can point me in the right direction with this.
Answer: You were very close.  Here are some fix-ups:
>>> searchterms = ["windows pc", "linux laptop", "some gibberish"]
>>> osCluster = ["windows", "linux"]

>>> for term in searchterms:
        found_cluster = 'N/A'
        for cluster in osCluster:
            if cluster in term:
                found_cluster = cluster
                break
        print('%-15s | %s' % (term, found_cluster))

windows pc      | windows
linux laptop    | linux
some gibberish  | N/A

Comment: @eLudium Updated to have just a single occurrence of the search term.
Comment: Thanks for help. What do I have to do if I want to add another cluster, or two, three more. Should I make some kind of csv, so I only read the first column (searchterm) and then start adding columns as clusters? So that in the end it be like: I really like windows pc (searchterm), windows(os), like(verb), ...(more clusters).

clustering using two or more lists


Are there any natural measures that can be put on the space of models?

Question: I've already asked this question is Philosophy.SE and is a 'soft' question.
An undecidable proposition, as in Gödel's Incompleteness theroem, is one whose truth value cannot be determined, because it evaluates as true in some models, and false in others.
One could argue that this is an opening for a more complex notion of truth.
Is there some natural way of establishing a magnitude for this, so perhaps expanding the binary notion of truth (false/true) into a more sophisticated one. Perhaps if a natural probability measure is available on the space of models?
Comment: Somewhat relevant: http://intelligence.org/wp-content/uploads/2013/03/Christiano-et-al-Naturalistic-reflection-early-draft.pdf
Comment: @Yuan: great, this is pretty much what I was looking for.
Answer: I don't think Gödel's incompleteness theorem (mentioned in the question) has much to do with this.  You don't need to get anywhere near Gödel's incompleteness theorem to know that some statements are true in some models and false in others.  For example, the existence of multiplicative inverses of elements other than $0$ is true in $\mathbb Z\bmod n$ if $n$ is prime, and false if $n$ is composite.  That's taught in undergraduate courses to students who may never have heard of Gödel.
One can put probability measures on spaces of models, and then ask about the probability that a particular statement is true.  But whether any is "natural" is clearly a much harder question.
Here's one small result I heard asserted once: Let's say you have a first-order language with finitely many relation symbols.  If one regards all isomorphism classes of models of finite size $n$ as equally probable, then each statement in this language has some probability of being true in models of size $n$.  And then for each statement one can take a limit as $n\to\infty$.  A mathematician I spoke to claimed to have published this result: in every instance the limit is either $0$ or $1$.  I don't remember his name.
I've never heard any such results for infinite models.
Answer: "An undecidable proposition, as in Gödel's Incompleteness theorem, is one whose truth value cannot be determined."
That's not quite right. If $G$ is a Gödel sentence for theory $T$, then to be sure $T$ can't settle whether $G$ or not-$G$. But some other theory might well be able to do just that. For example, some quite modest theories -- ones that almost any mathematician believes -- determine that the canonical Gödel sentence for first-order Peano arithmetic is true.


How to integrate $\int (x^{6}+x^{9})^{\frac{1}{6}}dx$?

Question: How to evaluate $$\int (x^{6}+x^{9})^{\frac{1}{6}}dx?$$
I am trying to evaluate this integral by taking out a common factor of $x^{6}$. Now the integral is  $$\int x(1+x^{3})^{\frac{1}{6}}dx.$$
Now I am thinking of writing $x=\frac{x^{2}}{x}$. So, the above integral is becoming $$\int \frac{x^{2}(1+x^{3})^{\frac{1}{6}}}{x}dx$$. Now I substituted $x^{3}=u$. So, $x^{2}dx=\frac{1}{3}du$.
Therefore, the integral will be $$\frac{1}{3}\int\frac{(1+u)^{\frac{1}{6}}}{u^{\frac{1}{3}}}du.$$
Now, I am thinking of substituting $u=tan^{3}\theta$. So, $du=3(tan^{2}\theta)(sec^{2}\theta)d\theta$. So, the above integral will be $$\int (1+tan^{3}\theta)^{\frac{1}{6}}(tan\theta)(sec^{2}\theta)d\theta.$$ But after this step I can't proceed further. Please help me out.
Comment: Pro tip: type an integral into Wolfram Alpha. If it cannot do it, or (like here) it spews something strange looking (here a hypergeometric function), the indefinite integral (usually) cannot be written in terms of elementary functions at all. Meaning that either somebody is pulling your leg, or you are supposed to do something else with it. Caveat: There are people who think of hypergeometric functions as elementary. If you need to ask, you are not among them :-)
Comment: why this question has $3$ downvotes ???
Comment: https://www.wolframalpha.com/input?i2d=true&i=Integrate%5BPower%5B%5C%2840%29Power%5Bx%2C6%5D%2BPower%5Bx%2C9%5D%5C%2841%29%2CDivide%5B1%2C6%5D%5D%2Cx%5D
Comment: Not sure why this is getting downvoted, the person asking has presented what they are asking clearly and showed what they have tried.
Comment: Please show me the full solution.
Comment: Can you tell me the sources from which you take these integrals?
Answer: You cannot avoid hypergeometric function or the binomial expansion.
Making the problem more general
$$I=\int \left(x^n+x^{3 n/2}\right)^{\frac{1}{n}}\,dx=\frac{2 }{5}x^{5/2} \,
   _2F_1\left(-\frac{5}{n},-\frac{1}{n};\frac{n-5}{n};-x^{-n/2}
   \right)$$ which is
$$\frac{2\,x^{5/2}}{\Gamma \left(-\frac{1}{n}\right) }\sum_{k=0}^\infty (-1)^{k+1}\,\frac{ \Gamma \left(k-\frac{1}{n}\right)}{(k
   n-5)\, \Gamma (k+1)}\,\,x^{-\frac{k n}{2}}$$


addEventListener sendo chamado irregularmente

Question: Tenho o seguinte código:

const setup = async() => {
    var arrayDados = [];
    let teuarray = [];
    var comeco = 4;
    var index = 2300;

    teuarray.push({id:1,nome: "arrayDados[i]"},{id:2,nome: "arrayDados[i]"});
    const lista = document.getElementById('lista');

    teuarray.map((cliente)=> {
      let divRowT = document.createElement("div");
      divRowT.className = "row-table";
      let divDivT = document.createElement("div");
      divDivT.className = "div-table";

      let id = document.createElement("a");
      id.className = "col-table";
      id.addEventListener("click", retornaPai(), false);
      id.href = "";
      let idValue = document.createElement("div");
      idValue.appendChild(document.createTextNode(cliente.id));
      id.appendChild(idValue);
      divDivT.appendChild(id);

      let nome = document.createElement("a");
      nome.className = "col-table";
      nome.addEventListener("click", retornaPai(), false);
      nome.href = "";
      let nomeValue = document.createElement("div");
      nomeValue.appendChild(document.createTextNode(cliente.nome));
      nome.appendChild(nomeValue);
      divDivT.appendChild(nome);

      let divColT = document.createElement("div");
      divColT.className = "col-table";
      let btnExcluir = document.createElement("input");
      btnExcluir.type = "button";
      btnExcluir.id = cliente.id;
      btnExcluir.value = "Excluir";
      btnExcluir.addEventListener("click", excluir, false);
      divColT.appendChild(btnExcluir);
      divDivT.appendChild(divColT);

      divRowT.appendChild(divDivT);
      lista.appendChild(divRowT);
    });
  }
  function retornaPai(nome) {
    // var pai = window.opener;

    console.log("teste");
    // pai.document.getElementById('usuario').value = nome;
    // pai.document.getElementById("buscarUsuario").onclick();
  }
  function excluir() {
    let btnSelecionado = event.currentTarget;
    console.log(btnSelecionado.id);
    var posicao = (btnSelecionado.id - 2300)/56;
    let url = decodeURI("http://192.168.1.142/limpaUsuario?");
    let params = "a="+posicao;
    sendConf(url,params,"excluído");
  }

.table{
  }
  .row-table-head, .div-table, .row-table{
    display: grid;
    grid-template-columns: 50px 180px 70px;
    width: 300px;
    margin: auto;
  }
  .row-table-head{
    display: block;
  }
  .row-table a{
    text-decoration: none;
    color: #000;
  }
  .div-table:hover{
    background-color: #a0a0a0;
  }
  .row-table-head .col-table{
    padding: 6px 8px;
    border: 1px solid #ccc;
  }
  .row-table .col-table{
   padding: 0px 6px;
  }

IMPEXPROS

LISTA TODOS USUARIOS

Não entendo por qual motivo a função retornaPai() está sendo chamada 4 vezes, sendo que o meu addEventListener deveria chama-lá somente quando clicasse no elemento HTML.
Alguém sabe me dizer o motivo?
Answer: Estás a correr a função quando tens retornaPai() como argumento do addEventListener... tens de tirar os () para passares uma referência à função e não chamar a função antes mesmo do auscultador de eventos ser registado...
Se queres passar argumentos à função podes fazer assim:

const setup = async() => {
  var arrayDados = [];
  let teuarray = [];
  var comeco = 4;
  var index = 2300;

  teuarray.push({
    id: 1,
    nome: "arrayDados[i]"
  }, {
    id: 2,
    nome: "arrayDados[i]"
  });
  const lista = document.getElementById('lista');

  teuarray.map((cliente) => {
    let divRowT = document.createElement("div");
    divRowT.className = "row-table";
    let divDivT = document.createElement("div");
    divDivT.className = "div-table";

    let id = document.createElement("a");
    id.className = "col-table";
    id.addEventListener("click", retornaPai.bind(null, cliente.nome), false);
    id.href = "";
    let idValue = document.createElement("div");
    idValue.appendChild(document.createTextNode(cliente.id));
    id.appendChild(idValue);
    divDivT.appendChild(id);

    let nome = document.createElement("a");
    nome.className = "col-table";
    nome.addEventListener("click", function(){ retornaPai(cliente.nome); }, false);
    nome.href = "";
    let nomeValue = document.createElement("div");
    nomeValue.appendChild(document.createTextNode(cliente.nome));
    nome.appendChild(nomeValue);
    divDivT.appendChild(nome);

    let divColT = document.createElement("div");
    divColT.className = "col-table";
    let btnExcluir = document.createElement("input");
    btnExcluir.type = "button";
    btnExcluir.id = cliente.id;
    btnExcluir.value = "Excluir";
    btnExcluir.addEventListener("click", excluir, false);
    divColT.appendChild(btnExcluir);
    divDivT.appendChild(divColT);

    divRowT.appendChild(divDivT);
    lista.appendChild(divRowT);
  });
}

function retornaPai(nome) {
  // var pai = window.opener;

  console.log("teste", nome);
  // pai.document.getElementById('usuario').value = nome;
  // pai.document.getElementById("buscarUsuario").onclick();
}

function excluir() {
  let btnSelecionado = event.currentTarget;
  console.log(btnSelecionado.id);
  var posicao = (btnSelecionado.id - 2300) / 56;
  let url = decodeURI("http://192.168.1.142/limpaUsuario?");
  let params = "a=" + posicao;
  sendConf(url, params, "excluído");
}
.table {}

.row-table-head,
.div-table,
.row-table {
  display: grid;
  grid-template-columns: 50px 180px 70px;
  width: 300px;
  margin: auto;
}

.row-table-head {
  display: block;
}

.row-table a {
  text-decoration: none;
  color: #000;
}

.div-table:hover {
  background-color: #a0a0a0;
}

.row-table-head .col-table {
  padding: 6px 8px;
  border: 1px solid #ccc;
}

.row-table .col-table {
  padding: 0px 6px;
}

IMPEXPROS

LISTA TODOS USUARIOS

Comment: E como eu faria para passar um dado para a função, por exemplo:  retornaPai(cliente.nome)?
Comment: @VitorPereira juntei duas maneiras diferentes de fazer no código da resposta. Escolhe o que preferes, são diferentes mas para o teu caso são semelhantes.
Comment: Obrigado Sergio, funcionou como previsto!


If $f$ is a bijection, then an invariant set A satisfies $f^{n}(A)=A$.

Question: This question is within the context of my course on Dynamical Systems (book Introduction to Dynamical Systems, by Brin and Stuck).
Let $X$ be a non empty set and consider the map $f:X \to X$.  For $n \in \mathbb{N}_{0}=\mathbb{N} \bigcup \left\{ 0 \right\}$, $f^{n}$ represents the $n$-fold composition, i.e., $f^{n}=f\circ \cdots \circ f$ (n times).
Given a subset $A \subset X$, we say it is $f$-invariant if $f^{n}(A) \subset A$ for all $n \in \mathbb{N}_{0}$.
I need to show that, if $f$ is a bijection, then the $f$-invariant set satisfies $f^{n}(A)=A$.
So far, given that $f$ is a bijection, I have been able to show that $f^{-n}(A^{c}) \subset A^{c}$ for all $n \in \mathbb{N}_{0}$, where $f^{-n}=f^{-1}\circ \cdots \circ f^{-1}$ (n times), but I haven't been able to go further than this to show that $A \subset f^{n}(A)$.
Any hint?
Comment: Is $X$ finite? If not, a counterexample is $f(x)=x/2$, $A=[-1,1]$.
Comment: I think the condition of $f$-invariance is $f^t(A)\subseteq A,\forall t\in\mathbb Z$. Otherwise @Rahul provides a counterexample.
Comment: Hi guys, thank you very much (@Rahul) for pointing this out.  I base my question on what I've read so far in the book I mentioned, where they are focusing on discrete-time dynamical systems, and where in particular $t$ can be in either $\mathbb{Z}$ or $\mathbb{N}$.  Hence I was trying to prove for the latter set.
@Rahul: If we restrict $X$ to be finite, then the claim can be proven?
Answer: I checked the book you mentioned. The definition of $f$-invariance is
$$f^t(A)\subseteq A,$$ for any $t$ in the appropriate range. And when $f$ is bijective, then the range ought to be $\mathbb Z$. Hence the condition is $f(A)\subseteq A$ and $f^{-1}(A)\subseteq A$. From these two conditions we deduce easily that $f(A)=A$.
If we consider $t$ in $\mathbb N$, then $A$ should be finite for the statement to hold. If $A$ is not finite, then a counter-example is given by the comment of @Rahul. If $f(A)\subseteq A$ and $A$ is finite, then the statement also holds: as $f$ is bijective, the two sets $A$ and $f(A)$ have the same (finite) cardinality. Since two finite sets one of which is contained in another must be equal, $f(A)=A$.

Hope this helps.
Comment: Hi awllower.  Thank you for your answer.  Yes, I see that given that $f$ is bijective, $t$ can be extended to be in $\mathbb{Z}$;
Comment: I've edited to include the case $A$ finite, as you asked in a comment.
Comment: Thanks again.  Very clear now.


Routing to Specific flutter Screen on click notification

Question: How to go to specific screen on click notification? i used cloud function in javascript and when i click on the notification, it open me the app not the specific screen
<code> _fcm.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    getOrder(message['data']['order_id']);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ListTile(
          title: Text(message['notification']['title']),
          subtitle: Text(message['notification']['body']),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text('Ok'),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DetailOrder()));
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DetailOrder()));
  },
);
</code>
Answer: You could try to use named routes + global navigator key, it worked for me in a slightly different situation.
First setup a global navigator key like this:
<code>...
class MyApp extends StatelessWidget {
  static final navigatorKey = GlobalKey<NavigatorState>();
  ...
</code>
Then right below define the named routes manager:
<code>...
Route routes(RouteSettings settings) {
  if (settings.name == "/") {
    return MaterialPageRoute(
      builder: (_) => HomePage(),
    );
  } else if (settings.name.startsWith("/details/")) {
    try {
      String id = settings.name.split("/")[2];
      return MaterialPageRoute(
        builder: (_) => DetailPage(id),
      );
    } catch (e) {
      return MaterialPageRoute(
        builder: (_) => HomePage(),
      );
    }
  } else {
    return MaterialPageRoute(
      builder: (_) => HomePage(),
    );
  }
}
...
</code>
and add both the navigatorKey and the routes to the MaterialApp:
<code>...
@override
Widget build(BuildContext context) {
  return MaterialApp(
    initialRoute: "/",
    onGenerateRoute: routes,
    title: 'MyApp',
    navigatorKey: navigatorKey,
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: HomePage(),
  );
}
...
</code>
After setting all this up you can navigate between your homepage and details using the navigator key like this:
<code>MyApp.navigatorKey.currentState.pushNamed("/"); // to navigate to HomePage
MyApp.navigatorKey.currentState.pushNamed("/details/1"); // to navigate to DetailPage
</code>
Hope it works, good luck!
Comment: @DjamilaJada if this answer was helpful, marking it as "Correct" is also a way to say thank you.


How to prove $f(U,V)=||A-UVU^T||_F^2$ is convex?

Question: I think one way is to verify if both $\frac{\partial^2 f}{\partial U^2}$ and $\frac{\partial^2 f}{\partial V^2}$ are postive semi-definite, is there other way to prove it?
Comment: Take $A=0$, and $U,V$ to be scalars. Show that the resulting function $(u,v) \mapsto u^4v^2$ is **not** convex.
Answer: You can do a Positive definite matrix check, eigenvalue test. But for doing that you need to simplify the expression.


How to Correctly Save the State of a Custom View in Android

Question: At the very beginning, let's try to answer the question - why should we actually save the state of the views?
Imagine a situation in which you fill a large questionnaire in a certain application on your smartphone . At some point, you accidentally rotate the screen or you want to check something in another application and, after returning to the questionnaire, it turns out that all the fields are empty. Such a situation effectively discourage users from using the application. For the purposes of this example, let's create a view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <androidx.appcompat.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
</LinearLayout>

And its corresponding class, that inflates the xml:
class CustomSwitchViewNoId @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    init {
        LayoutInflater.from(context).inflate(R.layout.view_custom_switch_no_id, this)
    }
}

Instead of rotating the screen every time to check the effect, we can enable the appropriate option in the developer settings of the phone
(Settings -> Developer options -> Don't keep activities -> turn it on).

As you can see - the state has not been saved. Let's recall the hierarchy that is called by Android to save and read the state:
Save state:

saveHierarchyState(SparseArray container)
dispatchSaveInstanceState(SparseArray container)
onSaveInstanceState()

Restore state:

restoreHierarchyState(SparseArray container)
dispatchRestoreInstanceState(SparseArray container)
onRestoreInstanceState(Parcelable state)

Let's see the internal implementation of saveHierarchyState:
public void saveHierarchyState(SparseArray container) {
    dispatchSaveInstanceState(container);
}

Which leads us to dispatchSaveInstanceState:
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
    super.dispatchSaveInstanceState(container);
    final int count = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < count; i++) {
        View c = children[i];
        if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
            c.dispatchSaveInstanceState(container);
        }
    }
}

That calls for the container and every child dispatchSaveInstanceState(container):
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
    if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
        mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
        Parcelable state = onSaveInstanceState();
        if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
            throw new IllegalStateException(
                    "Derived class did not call super.onSaveInstanceState()");
        }
        if (state != null) {
            // Log.i("View", "Freezing #" + Integer.toHexString(mID)
            // + ": " + state);
            container.put(mID, state);
        }
    }
}

As we can see in the 3rd line, there is check if the view has an ID assigned to call onSaveInstanceState() and put the state into the container, where the ID is a key.
Let's add the needed ID and see what happens:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/customViewSwitchCompat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/customViewEditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
</LinearLayout>

It works! Great, let's add two more our custom views. In the end, we created this whole thing so as not to have to duplicate the code and check if everything is still working.

So the problems is the when including multiple view, their state is not correctly restored. And it looks as if all views retrieve the state of the last child. How can we solve this problem?
Answer: Well, looking at the implementation of saveHierarchyState and dispatchSaveInstanceState, we can observe that every state is stored in one container and is shared for the entire view hierarchy. Let's draw up the current hierarchy:

As you can see, the tags @+id/customViewSwitch and @+id/customViewEditText and are repeated, so the generated sparse array saves the children of @+id/switch1, then @+id/switch2, and finally @+id/switch3.
From the documentation, we are able to learn that SparseArray is:

SparseArray maps integers to Objects and, unlike a normal array of
Objects, its indices can contain gaps. SparseArray is intended to be
more memory-efficient than a HashMap , because it avoids auto-boxing
keys and its data structure doesn't rely on an extra entry object for
each mapping.

Let's check how the container behaves when we pass the same key again:
val array = SparseArray()
array.put(1, "test1")
array.put(1, "test2")
array.put(1, "test3")
Log.i("TAG", array.toString())

The result is:
I/TAG: {1=test3}

So new values overwrite the previous ones. Considering the fact that the key in the previous case is ID, this explains why each of the views received the state of the last child.

Here is one solution to this problem.
At the beginning, we should overwrite 2 callbacks: dispatchSaveInstanceState and dispatchRestoreInstanceState:
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
    dispatchFreezeSelfOnly(container)
}

override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
    dispatchThawSelfOnly(container)
}

This way, super.onSaveInstanceState() will only return the super state, avoiding children views.
We are now ready to handle the state inside onSaveInstanceState and onRestoreInstanceState. Let's start with the saving process:
override fun onSaveInstanceState(): Parcelable? {
    return saveInstanceState(super.onSaveInstanceState())
}

Now It's time to restore the state:
override fun onRestoreInstanceState(state: Parcelable?) {
    super.onRestoreInstanceState(restoreInstanceState(state))
}

And here are the Viewgroup extenstion functions
fun ViewGroup.saveChildViewStates(): SparseArray<Parcelable> {
    val childViewStates = SparseArray<Parcelable>()
    children.forEach { child -> child.saveHierarchyState(childViewStates) }
    return childViewStates
}

fun ViewGroup.restoreChildViewStates(childViewStates: SparseArray<Parcelable>) {
    children.forEach { child -> child.restoreHierarchyState(childViewStates) }
}

fun ViewGroup.saveInstanceState(state: Parcelable?): Parcelable? {
    return Bundle().apply {
        putParcelable("SUPER_STATE_KEY", state)
        putSparseParcelableArray("SPARSE_STATE_KEY", saveChildViewStates())
    }
}

fun ViewGroup.restoreInstanceState(state: Parcelable?): Parcelable? {
    var newState = state
    if (newState is Bundle) {
        val childrenState = newState.getSparseParcelableArray<Parcelable>("SPARSE_STATE_KEY")
        childrenState?.let { restoreChildViewStates(it) }
        newState = newState.getParcelable("SUPER_STATE_KEY")
    }
    return newState
}

In this example, we call the restoreHierarchyState function for each child to which I pass the previously saved SparseArray. Let's check how the hierarchy looks now:

And now here is the result:

Everything works well! This is one of the ways to save the state of your own view, but there is another interesting solution using the BaseSavedState class. You can learn more from the original blog post by Marcin Stramowski


Correlation and P Value

Question: I have run correlation on SPSS for the variables of number of employees in a bank and Net profit margin for the data of 10 years. Results show the correlation coefficient '-0.1649' and p-value '0.649'.
I am unable to interpret the result and need help.
Comment: It just indicates that there is not strong evidence that the correlation is different from 0. To determine if there is a slight negative correlation as the estimate suggests you would need a much larger sample size.
Answer: It appears you have data for one bank for 10 years, so N = 10. The low, negative correlation only indicates that for the bank you chose, for the 10 years you have, the linear relationship was small and negative.
Unless you are willing to posit that either a) These 10 years are a random sample of all years from your bank or b) These 10 years are a random sample from those 10 years for some larger population of banks then you won't be doing any inference and the p value isn't important. (And positing either of those things seems unjustified, at least to me).
What I would do is plot the ratio of profit to employees over time and see if anything interesting appears.
Comment: Yes, I have taken data for one bank earlier. Later on, I have run correlation for the 10 years data of 6 banks (60 observations) and found the following results. R = 0.231, Sig (2-tailed) = 0.076. I am actually confused whether p-value will matter over here as per which the above results show that the same are not statistically significant because p-value > 0.05 whereas correlation (R) = 0.231 that means slight positive correlation.
Comment: If you try to do this for 6 banks then your data is not independent and correlation really isn't appropriate. You would want a multilevel model.
Answer: Your data shows a slight negative correlation between number of employees and net profit.  (correlation coefficient of -0.17).
Your data is consistent with a world in which there was no true correlation between number of employees and net profit, in that it is not unlikely that the data shows a slight negative correlation due to random chance (p-value of 0.65).
In short, almost all rational people would not take this data as proof that there is a negative association between number of employees and net profit.

Correlation and P Value